Skip to content

vtgate: fix union merging through reference-table alternates - #20755

Open
GrahamCampbell wants to merge 1 commit into
vitessio:mainfrom
GrahamCampbell:union-reference-alternate-merging
Open

GrahamCampbell wants to merge 1 commit into
vitessio:mainfrom
GrahamCampbell:union-reference-alternate-merging

Conversation

@GrahamCampbell

@GrahamCampbell GrahamCampbell commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Description

A UNION DISTINCT between a reference table and a table in the keyspace holding one of its copies panics with VT13001: [BUG] did not expect this method to be called. When the two sides' keyspaces differ, the planner makes them mergeable by swapping in the alternate route prebuilt at route-creation time, but unions merge later, during horizon planning, and the prebuilt route still holds the unplanned bare table it was created with. As soon as the union pushes its result columns into that source — the weight-string columns DISTINCT needs — the bare table operator panics in Table.AddColumn. UNION ALL survives because it pushes nothing.

The fix stops using the prebuilt alternate as the merge payload. A declined cross-keyspace pairing is retried by resolving every real table under the moved side to its copy in the other side's keyspace through the VSchema — the table itself, a ReferencedBy copy, or a reference source, so routing rules stay in effect — and pointing the planned operators at those copies in place, undoing the move when the retry still cannot merge. Predicates and projections pushed after route creation are preserved because the operators are kept, physical renames keep the original name as an alias so column references still resolve, and later column pushes land on operators the planner has analyzed. A side already composed of a merged union is not moved: the remaining phases no longer normalize the shape that produces, so composite pairings stay split for now. A branch carrying an aggregate, limit, distinct or ordering stays split from a sharded source, including when a subquery elsewhere in the statement expanded its horizon, because moving it onto the sharded routing would run that operator once per shard. Join and subquery merging keep the prebuilt-route mechanism: they merge during physical planning, when every route source is still a bare table, and that path is covered and correct.

Fourteen planner cases in reference_cases.json cover both merge orders, the differing-physical-name rewrite, predicate preservation through the rewrite, the sharded-source routing preservation, the composite pairings that stay split, a no-copy control, and pin the already-working UNION ALL path; the four single-table DISTINCT cases fail on main with the panic. The reference-copy cases are skip_e2e like the rest of that file's, since the e2e fixture does not define the copy tables. Recursive CTE merging shares the swap through prepareInputRoutes and likely has the same latent panic, left for a follow-up. This is part one of the fix for #20754, and since the panic exists in released versions it is probably worth backporting.

Related Issue(s)

Part one of #20754.

Checklist

  • "Backport to:" labels have been added if this change should be back-ported to release branches
  • If this change is to be back-ported to previous releases, a justification is included in the PR description
  • Tests were added or are not required
  • Did the new or modified tests pass consistently locally and on CI?
  • Documentation was added or is not required

Deployment Notes

UNION DISTINCT queries pairing a reference table with a table in a keyspace holding one of its copies previously failed to plan with an internal error; they now plan as a single merged route. No migrations or configuration changes.

AI Disclosure

This PR was written primarily by Fable.


graph LR
    subgraph json [JSON support]
        direction TB
        PR20625["#20625 (merged)<br>mysql/json: fix MarshalTo discarding accumulated output for nested blob and bit values"]
        PR20632["#20632<br>vtgate: preserve IN value lists in complex aggregate projections"]
        PR21205["#21205<br>evalengine, mysql/json: fix JSON and TIME equality in compiled and interpreted paths"]
        PR20682["#20682 (draft)<br>evalengine: support constant-folded JSON values as literals"]
        PR20683["#20683 (draft)<br>evalengine, sqlparser: MySQL comparison domains; nested BETWEEN parentheses"]
        PR20626["#20626 (draft)<br>vtgate: support cross-shard JSON_ARRAYAGG and JSON_OBJECTAGG"]
        PR20625 --> PR20682
        PR21205 --> PR20682
        PR20682 --> PR20683
        PR20632 --> PR20626
        PR20683 --> PR20626
    end

    subgraph union [Union routing]
        direction TB
        PR20628["#20628<br>vtgate: track per-source copies of pushed join predicates so merges skip them"]
        PR20629["#20629 (merged)<br>vtgate: fix None routing handling when merging unions"]
        PR20630["#20630 (draft)<br>vtgate: merge unions on join-predicate-free routings when all sources agree"]
        PR20755["#20755<br>vtgate: fix union merging through reference-table alternates"]
        PR20756["#20756 (draft)<br>vtgate: merge empty reference branches through rewritten copies"]
        PR20628 --> PR20630
        PR20629 --> PR20630
        PR20630 --> PR20756
        PR20755 --> PR20756
    end

    subgraph cte [Recursive CTEs]
        direction TB
        PR20759["#20759<br>vtgate: expand qualified stars without JOIN USING coalescing"]
        PR20633["#20633 (draft)<br>vtgate: validate the declared column list length of CTEs and derived tables"]
        PR20631["#20631 (draft)<br>vtgate: bind recursive CTE column filters as arguments in unmerged term queries"]
        PR20759 --> PR20633
        PR20633 --> PR20631
    end

    json ~~~ union ~~~ cte
Loading

Copilot AI balanced review requested due to automatic review settings July 29, 2026 19:29

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added this to the v25.0.0 milestone Jul 29, 2026
@vitess-bot

vitess-bot Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Review Checklist

Hello reviewers! 👋 Please follow this checklist when reviewing this Pull Request.

General

  • Ensure that the Pull Request has a descriptive title.
  • Ensure there is a link to an issue (except for internal cleanup and flaky test fixes), new features should have an RFC that documents use cases and test cases.

Tests

  • Bug fixes should have at least one unit or end-to-end test, enhancement and new features should have a sufficient number of tests.

Documentation

  • Apply the release notes (needs details) label if users need to know about this change.
  • New features should be documented.
  • There should be some code comments as to why things are implemented the way they are.
  • There should be a comment at the top of each new or modified test to explain what the test does.

New flags

  • Is this flag really necessary?
  • Flag names must be clear and intuitive, use dashes (-), and have a clear help text.

If a workflow is added or modified:

  • Each item in Jobs should be named in order to mark it as required.
  • If the workflow needs to be marked as required, the maintainer team must be notified.

Backward compatibility

  • Protobuf changes should be wire-compatible.
  • Changes to _vt tables and RPCs need to be backward compatible.
  • RPC changes should be compatible with vitess-operator
  • If a flag is removed, then it should also be removed from vitess-operator and arewefastyet, if used there.
  • vtctl command output order should be stable and awk-able.

@vitess-bot vitess-bot Bot added NeedsWebsiteDocsUpdate What it says NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsBackportReason If backport labels have been applied to a PR, a justification is required labels Jul 29, 2026
@GrahamCampbell
GrahamCampbell force-pushed the union-reference-alternate-merging branch from cf59812 to 04337dd Compare July 29, 2026 19:43
Copilot AI review requested due to automatic review settings July 29, 2026 19:43

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI review requested due to automatic review settings July 29, 2026 22:32
@GrahamCampbell
GrahamCampbell force-pushed the union-reference-alternate-merging branch from 04337dd to 85b309b Compare July 29, 2026 22:32

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

This comment was marked as resolved.

@devin-ai-integration devin-ai-integration Bot 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.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Open in Devin Review

@codecov

codecov Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 113 lines in your changes missing coverage. Please review.
✅ Project coverage is 4.92%. Comparing base (70c7a72) to head (ebfb020).
⚠️ Report is 597 commits behind head on main.

Files with missing lines Patch % Lines
...o/vt/vtgate/planbuilder/operators/union_merging.go 0.00% 104 Missing ⚠️
go/vt/vtgate/planbuilder/operators/horizon.go 0.00% 8 Missing ⚠️
.../vt/vtgate/planbuilder/operators/query_planning.go 0.00% 1 Missing ⚠️

❗ There is a different number of reports uploaded between BASE (70c7a72) and HEAD (ebfb020). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (70c7a72) HEAD (ebfb020)
1 0
Additional details and impacted files
@@             Coverage Diff             @@
##             main   #20755       +/-   ##
===========================================
- Coverage   69.67%    4.92%   -64.75%     
===========================================
  Files        1614       60     -1554     
  Lines      216793     8448   -208345     
===========================================
- Hits       151044      416   -150628     
+ Misses      65749     8032    -57717     
Flag Coverage Δ
partial 4.92% <0.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Copilot AI review requested due to automatic review settings August 28, 2026 11:17

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI review requested due to automatic review settings August 28, 2026 18:32
@GrahamCampbell
GrahamCampbell force-pushed the union-reference-alternate-merging branch from 4ec9eb2 to a07ae0c Compare August 28, 2026 18:32

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a07ae0cf8f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread go/vt/vtgate/planbuilder/testdata/reference_cases.json Outdated
Comment thread go/vt/vtgate/planbuilder/operators/union_merging.go
Copilot AI review requested due to automatic review settings September 11, 2026 16:09
@GrahamCampbell
GrahamCampbell force-pushed the union-reference-alternate-merging branch from a07ae0c to 83729bf Compare September 11, 2026 16:09

Copilot AI 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.

🟡 Changes recommended

Alternate rewrites can multiply volatile evaluation and shard-sensitive expanded operators, producing incorrect UNION results.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details
  • Files reviewed: 5/5 changed files
  • Comments generated: 2
  • Review effort level: Balanced

Comment on lines +369 to +370
_ = Visit(route.Source, func(op Operator) error {
if horizon, ok := op.(*Horizon); ok && !horizon.computesRowByRow(ctx) {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed. With a subquery anywhere in the statement pushOrExpandHorizon expands instead of pushing, the Aggregator (or Limit, Distinct, Ordering) is then pushed under the single-shard reference route on its own, and the horizon check saw nothing: select count(*) from main_2.sharded_sales_ref where exists (select 1) union all select 0 from user.sales_extra planned as one scatter route running select count(*) from sales as sharded_sales_ref where exists (select 1 from dual) union all select 0 from sales_extra on every shard, one count per shard instead of one total. The same happened for LIMIT, DISTINCT, GROUP BY and HAVING, and with the subquery in the other branch (... union all select 0 from user.sales_extra where exists (select 1)). Main merges these through the bare prebuilt alternate and drops the operators entirely (select 1 from sales as sharded_sales_ref union all ...), so the path stays owned here. computesRowByRow now also stops on an Aggregator, Window, Distinct, Ordering or Limit under the moved route, the operators expandHorizon produces, so these pairings stay a Concatenate with the reference branch on main_2, while plain-column branches with a subquery (select col1 from main_2.sharded_sales_ref where exists (select 1) union all select cola from user.sales_extra) still merge onto the scatter routing. New goldens pin the aggregate and limit forms.

resolvable = false
return io.EOF
}
if alt.VTable.Type != vindexes.TypeReference && alt.VTable.Keyspace.Sharded {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Pre-existing, and not widened here. A reference branch has always been folded into the sharded side's scatter routing once both sides are in one keyspace: on main, select id from ref where rand() < 0.5 union select id from user plans to the identical Distinct over a scatter route with rand() < 0.5 inside the pushed union, and union_cases.json already pins that shape for select id from ref_with_source where id in (null) union select id from user. The cross-keyspace UNION ALL form, select id from source_of_ref where rand() < 0.5 union all select id from user, merges into the same scatter route on main too, except that the prebuilt alternate drops the rand() < 0.5 predicate altogether (select id from ref_with_source as source_of_ref union all select id from user); this PR keeps the predicate and lets the DISTINCT form, which panicked, reach the shape the ALL form already had. Nothing in the planner classifies expressions as volatile, so handling it in this merge would be new policy that has to start with the same-keyspace case, and I'd rather track that separately than in this PR.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Correction: the union_cases.json case I cited has a none-routed reference branch, so it shows the merged shape but not a live branch running per shard; the live same-keyspace form is not pinned on main, and select id from ref where rand() < 0.5 union select id from user is the reproduction.

@GrahamCampbell
GrahamCampbell force-pushed the union-reference-alternate-merging branch 2 times, most recently from 44cdd80 to eb7224a Compare September 24, 2026 01:10
Signed-off-by: Graham Campbell <hello@gjcampbell.co.uk>
@GrahamCampbell
GrahamCampbell force-pushed the union-reference-alternate-merging branch from eb7224a to ebfb020 Compare September 24, 2026 09:42

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Component: VTGate NeedsBackportReason If backport labels have been applied to a PR, a justification is required NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsWebsiteDocsUpdate What it says

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants