Skip to content

vtgate: avoid duplicate reference rows in UNION ALL - #21354

Open
patnaikankit wants to merge 40 commits into
vitessio:mainfrom
patnaikankit:patnaikankit/fix-ref-arm
Open

patnaikankit wants to merge 40 commits into
vitessio:mainfrom
patnaikankit:patnaikankit/fix-ref-arm

Conversation

@patnaikankit

@patnaikankit patnaikankit commented Oct 2, 2026 •

Copy link
Copy Markdown

Description

UNION ALL can repeat reference-table or dual rows when their route is merged into, or later widened to, a multi-shard route. Preserve that routing constraint through UNION, join, subquery, alternate-route, and CTE merges while retaining safe single-shard merges. Reference-preserving outer joins remain separate from multi-shard reads; multi-table DML retains its scatter statement. Reference-copy selection after a refused join merge preserves derived projections and limits, and any resulting cross-keyspace read is checked against the actual route keyspaces. DML exemptions apply only to joins containing a target table; independent read subqueries retain their outer-join safety checks.

Keep ordering and LIMIT placement correct when these queries split into VTGate operations. Push an upper limit only when deduplication occurs before the route-local limit and any required ordering accompanies it. Ordered split UNION arms retain the helper columns needed by the outer sort; route-only helpers are trimmed after parent offset planning. Mapped arm ordering qualifies table columns on a separate copy, retaining their semantic dependencies without changing the SELECT expressions or output field names. This prevents SELECT aliases from shadowing the ordering columns, including when a later arm refuses the pushdown. Scalar aggregate arms block mapped ordering pushdown instead of leaking route-local helper columns. Arm-local literal sort keys are omitted from pushed ORDER BY clauses so MySQL cannot interpret them as column positions. Arm-local LIMITs remain barriers before and after Horizon expansion: neither outer ordering nor an upper limit may change which rows those arms select. Routes that receive pushed arm ordering record that fact so helper truncation remains delayed until parent offset planning, including generated DISTINCT derived tables. A VTGate projection blocks upper-limit pushdown when expressions or dropped columns can make distinct inputs equal again. Plain column projections that preserve every UNION output column retain safe arm limits, including filters, aliases, reordered columns, and nested derived tables. Queries without the outer DISTINCT also retain safe limit pushdown. Align helper-column offsets across mixed UNION arms and rebind columns added above generated derived tables through their output aliases. Preserve MySQL's weight-string fallback when the planner does not know a text column's collation: result fields can report the connection collation. Mixed-collation split UNION sorting remains a separate follow-up after this PR (#21957).

Recursive term WHERE predicates now use the same active-CTE binding mechanism as ON predicates. Depth guards such as WHERE c.lvl < 5 therefore bind the current recursive row in newly split reference/dual plans and existing ordinary split plans. Other predicates on the term table remain intact. Recursive plan descriptions expose the active Distinct and ScaleWorkLimitBySeed flags, using the existing description serializer's convention of omitting false values.

No-route IN fallbacks retain evaluated lists in a copy of the caller's bind variables: __vals for single-column vindexes, and __vals0, __vals1, etc. for tuple-valued columns of multi-column vindexes. Scalar columns retain their original bindings and do not create list variables. This preserves reference rows from a merged UNION DISTINCT after a non-planable lookup miss in buffered and streaming execution.

Regression tests cover reference and dual provenance at merge sites, lookup misses, recursive CTE routing, cross-keyspace read policy, DML, mixed UNION ordering, hidden columns, and LIMIT placement. Additional regressions cover UPDATE scalar subqueries, safe single-shard recursive DISTINCT, explicit rejection of recursive DISTINCT when a replicated-seed merge is refused, and early CTE seed reference-copy selection without losing projected columns. Execution tests include duplicate-heavy outer DISTINCT inputs, computed DISTINCT projections over cross-keyspace UNIONs, and mixed UNION results larger than the limit, in OLTP and streaming modes. Planner tests also cover pass-through DISTINCT projections that retain safe arm limits.

Locally verified for review 6015660208:

  • make lint: zero issues.
  • Full engine, planner, operator, executor and CLI help-output suites. The CTE snapshot changes only to expose the active per-seed work flag; existing serialized descriptions continue omitting false values.
  • Rebuilt Vitess binaries, then ran the full UNION e2e suite and the full lookup suite twice. The new cyclic depth-guard test compares WHERE and ON placement for reference, dual and ordinary seeds in OLTP and OLAP, checking the returned values and depth counter against MySQL.
  • All nine CI-pinned Vitess Tester workloads (153 queries), plus the 14-query cross-keyspace OLAP workload.
  • Focused Concatenate, recursive execution and IN fallback tests under the race detector. BIT(16)/BIT(64) buffered and streaming coercion checks also pass 20 repeated race-enabled runs. Streaming assertions permit the ordinary parallel path to deliver arms in either order.
  • Five new mutations independently catch disabled sort-type compatibility, missing recursive WHERE binding, omitted Distinct and per-seed-work diagnostic fields, and rejection of valid eight-byte BIT values. Fifteen earlier mutations recheck SELECT-copy, overflow/draining, helper/LIMIT, recursive seed policy, reserved-session and reference-copy/keyspace protections. All edits were restored.

Before the fix, the new recursive WHERE e2e test fails with errno 1054 for the unbound c.lvl column. The final fixture casts seed columns to BIGINT and starts the depth counter at zero, maintaining strict result comparisons without relying on literal-width metadata or identical constant output expressions. Initial concurrent e2e attempts stopped during tablet registration before test execution; successful final runs were sequential with fresh data roots.

The serialized-stream memory test and the new depth-guard e2e test skip vtgate binaries below v25 for upgrade/downgrade runs. The complete old-binary upgrade matrix was not executed locally.

Related Issue(s)

Fixes #20902

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

This PR fixes query correctness without adding SQL syntax, flags, or configuration. The user-visible behavior and operational effects are covered in Deployment Notes; no separate website documentation is required. No release-branch backport is currently requested. Any backport should be evaluated separately given the UNION routing and recursive CTE execution changes.

Deployment Notes

Some UNION plans now stay split across VTGate routes, so aggregation and sorting can fetch more rows into VTGate and use more memory. Ordered LIMITs over UNIONs that were already split also no longer use the unsafe unordered per-arm caps described in #21956. A scatter UNION DISTINCT with ORDER BY ... LIMIT reads every distinct row from each shard, including typed columns (for example, select intcol from user union select intcol from music order by intcol limit 3). Split UNION arms also read in full when compatible arm sort types cannot be established, such as without schema tracking, or a scalar aggregate blocks mapped ordering pushdown. In these cases VTGate applies the final ORDER BY and LIMIT after those reads; OLTP execution can therefore reach --max-memory-rows or tablet result-size limits. An outer DISTINCT over a VTGate projection that computes expressions or drops distinct-key columns may also need all arm rows before LIMIT; truncating the arm inputs can otherwise return too few distinct projected values. Plain column projections that preserve the UNION's distinct keys keep safe arm limits. In-memory sorting remains subject to --max-memory-rows. Derived queries with unexpanded SELECT * over split UNION branches may require schema tracking, and views over these plans may require --enable-views. A derived column list over a newly split reference UNION ALL, such as select c from (select id from user union all select id from ref) t(c), now fails with VT13001. This is the existing split-UNION derived-column-list limitation exposed by preventing the incorrect reference merge; the equivalent query with an unsharded arm already has that limitation.

Mixed-collation ordering in split UNIONs remains open in #21957 and is planned as a separate follow-up after this PR. This includes a constant text arm such as select 'All' as name from dual combined with a text-column arm when connection and column collations differ: their arm-local weight strings can still sort the combined result incorrectly. Mixed integer/string sort keys are also affected, for example select intcol from user union all select 'a' from dual order by intcol limit 3; comparing arm-local weight strings can disagree with MySQL's UNION result ordering. These mixed-type cases remain part of that separate follow-up. ENUM and SET ordering are included in the same deferred scope: table-local ordering and weight strings can follow definition indexes/bit values, while the UNION result orders as strings. For example, enum('b','a','c') can return b first from a split reference UNION where MySQL's UNION would return a. Equal per-arm type/collation keys alone do not establish compatible final UNION ordering for these types.

Concatenate executes UNION arms sequentially in reserved-connection sessions as well as transactions, preventing concurrent arm use of a shared session connection. Ordinary sessions retain parallel execution. Reserved sessions can therefore trade arm-level parallelism for safe connection use. The conservative policy also serializes independent cross-keyspace reserved-session arms; target-aware parallelism is a possible separate optimization, not part of this change. Serialized OLAP execution retains arm results until their common output types are known. Those retained rows now share one --max-memory-rows budget across all arms, checked before appending each chunk. When the buffer limit is reached, VTGate discards further chunks and drains the active arm before returning RESOURCE_EXHAUSTED with MySQL errno 1153. No further UNION arms are started. Draining avoids cancelling a tablet's live transactional stream, preserving the caller's transaction and preceding writes, while keeping retained rows within the same shared budget. The error is returned only after that arm finishes, so a large or slow arm can still consume query work, network traffic and time after the buffer fills. Normal client cancellation and query timeouts can still interrupt the query and transaction. This also bounds the pre-existing transactional streaming buffer. The explicit IGNORE_MAX_MEMORY_ROWS hint can bypass this retained-row check, consistently with other row buffers; the independent recursive term-work cap remains active.

If a derived projection or LIMIT prevents selecting a bare reference copy after a refused join merge, the original route and its wrapper are retained. When the resulting read crosses keyspaces, prevent_cross_keyspace_reads is enforced against those actual keyspaces unless ALLOW_CROSS_KEYSPACE_READS is supplied.

A reference LEFT JOIN onto a multi-shard route, such as select r.id from source_of_ref r left join user u on u.id = r.id, now runs as a VTGate nested loop with one right-hand query per reference row. Split arms can retain their own decimal or temporal formatting even when the values compare equal.

Recursive CTEs that already execute in VTGate retain the existing bound of 1,000 cumulative term executions, independently of --max-memory-rows. Newly split reference/dual seeds under UNION ALL receive a work allowance of 1,000 term executions per seed row, with at least one allowance for an empty seed. Only the existing rejected replicated-seed merge marks a plan for this scaling; ordinary sharded and unsharded seeds keep the fixed bound. UNION ALL also stops at 1,000 expansion levels. VTGate UNION DISTINCT retains its fixed 1,000-term bound because recursive deduplication remains outside this PR. Exceeding either recursion bound returns VT09030 (MySQL errno 3636), consistently with the existing recursion limit.

Buffered recursion retains all output rows and is bounded by --max-memory-rows (300,000 by default). Streaming recursion bounds the retained current and next levels together. Row-memory errors preserve their state across streamed callback aggregation and use MySQL errno 1153 (ER_NET_PACKET_TOO_LARGE). IGNORE_MAX_MEMORY_ROWS bypasses only these retained-row checks: it cannot lift the independent cumulative term-work or depth bounds. Lowering or raising --max-memory-rows no longer changes the recursive work allowance. Releasing completed levels does not reset the work counter. One term invocation may still query multiple shards. Cancellation and configured timeouts still stop execution.

When a recursive CTE merge is refused because it would repeat a reference or dual seed across shards, UNION DISTINCT now fails explicitly with VT12001: VTGate recursion does not deduplicate across levels or shards. Existing recursive DISTINCT plans over ordinary sharded tables and unsharded seeds from another keyspace are retained. Their pre-existing general deduplication gap is outside this PR. CTE seed planning selects same-keyspace reference copies before projections when safe; any remaining cross-keyspace recursion obeys PreventCrossKeyspaceReads and the explicit ALLOW_CROSS_KEYSPACE_READS override. This policy also applies to recursive CTEs without reference tables: an unsharded seed with a sharded term in another keyspace now fails with VT12001 when prevent_cross_keyspace_reads denies that read, unless explicitly overridden.

AI Disclosure

Codex assisted with implementation, planner regressions, and end-to-end coverage. The author reviews the changes.

Copilot AI balanced review requested due to automatic review settings October 2, 2026 08:03
@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 Oct 2, 2026
@github-actions github-actions Bot added this to the v25.0.0 milestone Oct 2, 2026
@vitess-bot

vitess-bot Bot commented Oct 2, 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.

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 review overview

🟡 Changes recommended

A later merge can still widen a reference-containing single-shard union to Scatter and duplicate its rows.

Review effort: Balanced
Findings: 1 High severity

Open (1)
What changed in this PR

Addresses #20902 by separating reference and dual inputs from multi-shard UNION ALL routes to avoid repeated rows.

Changes:

  • Adds merge guards, including checks before alternate-route preparation.
  • Adds planner regressions and alternate-routing unit tests.
File Description
go/​vt/​vtgate/​planbuilder/​testdata/​union_cases.json Adds a dual/scatter regression case.
go/​vt/​vtgate/​planbuilder/​testdata/​reference_cases.json Adds reference/scatter cases in both arm orders.
go/​vt/​vtgate/​planbuilder/​operators/​union_merging.go Guards unsafe multi-shard merges.
go/​vt/​vtgate/​planbuilder/​operators/​union_merging_test.go Tests alternate-route merge eligibility.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI balanced review requested due to automatic review settings October 2, 2026 08:16

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 review overview

🟡 Changes recommended

Mixed unions can still duplicate rows, and valid single-shard wildcard queries can now fail.

Review effort: Balanced
Findings: 2 High severity

Open (2)
Resolved since last review (1)

@patnaikankit
patnaikankit marked this pull request as draft October 2, 2026 08:30
Copilot AI balanced review requested due to automatic review settings October 2, 2026 10:28

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 review overview

🟡 Changes recommended

Overbroad reference-join provenance can reject previously supported UNION ALL queries without schema tracking.

Review effort: Balanced
Findings: 1 High severity

Open (1)
Resolved since last review (2)

Copilot AI balanced review requested due to automatic review settings October 2, 2026 10:48

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 review overview

🟡 Changes recommended

Provenance handling still permits duplicate reference rows in aggregate-derived joins and rejects previously supported subquery UNION queries.

Review effort: Balanced
Findings: 2 High severity

Open (2)
Resolved since last review (1)

Copilot AI balanced review requested due to automatic review settings October 2, 2026 11:41

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 review overview

🔵 Needs a closer look

Cross-cutting planner changes need human review and execution-level validation of result semantics.

Review effort: Balanced
Findings: None

Resolved since last review (2)

@patnaikankit
patnaikankit marked this pull request as ready for review October 2, 2026 13:58
Copilot AI balanced review requested due to automatic review settings October 2, 2026 13:59

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 review overview

🔵 Needs a closer look

Cross-operator provenance tracking affects query semantics and needs execution-level validation and final human review.

Review effort: Balanced
Findings: None

@patnaikankit

Copy link
Copy Markdown
Author

@frouioui @arthurschreiber, please take a look at the changes and let me know if there is anything that I might have missed / not considered.

@patnaikankit

Copy link
Copy Markdown
Author

@mattlord, addressed points 1–5 in d5bb194:

  • Delayed UNION-arm truncation to preserve the outer sort’s helpers.
  • Omitted literal arm-local sort keys while retaining safe LIMIT pushdown.
  • Added helper-offset bounds checks.
  • Enforced the operator-configured term budget in both modes, independently of IGNORE_MAX_MEMORY_ROWS.
  • Preserved MySQL errno 1153, including through streaming callback error aggregation.

For point 6, I plan to handle #21957 separately after this PR. The description and Deployment Notes now state that explicitly.

I rechecked the earlier regressions without rewriting existing planner snapshots. Full unit suites, recursive race tests, rebuilt UNION e2e, all nine tester workloads (151 queries), 12 additional streaming queries, and lint passed. Twelve targeted mutation checks were also caught by the regressions.

@mattlord mattlord left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the update @patnaikankit! All five points from my last review are fixed at this head. I ran the queries in OLTP and streaming mode, through VTGate's executor against MySQL 8.0:

  • The textcol and count(*) unions return MySQL's rows.
  • The arms no longer send order by 0 or order by 1, and normalized :vtgN literals are skipped too.
  • The weight-string offset check is in place.
  • IGNORE_MAX_MEMORY_ROWS no longer lifts the Term cap.
  • Both recursive limits return errno 1153.

Another full pass over this head found two more problems in the ordered LIMIT pushdown. The first gives wrong rows without a reference table.

  1. Blocking: I think that the outer ordering shouldn't be pushed into an arm that has its own LIMIT.

    • routesForUnionArm walks through an arm's VTGate Limit to the route below it, and setUpperLimit's shouldVisit (query_planning.go:604-622) has no *Limit case.
    • So the arm's route gets the outer ORDER BY and :__upper_limit underneath the arm's own LIMIT. Its scatter merge then sorts by the outer key: the plan shows 0 ASC where main has 0 DESC.
    • The arm's Limit therefore keeps the wrong rows. With typed id columns, as schema tracking provides, (select id from user order by id desc limit 2) union all (select id from music) order by id limit 3 returns [1, 2, 100] in both modes, where MySQL and main return [11, 12, 100].
    • When the arm's LIMIT is inside its route, it gets lost instead. (select id, intcol from ref order by intcol desc limit 1) union all (select id, intcol from user) order by intcol limit 3 sends order by ref.intcol desc, intcol asc limit 3 to the reference arm, so it can return more than the one row its limit 1 allows. On main that query is merged and correct. main already has this problem for an unsharded arm in another keyspace, but splitting reference arms now brings it to them.
    • In a scratch run, stopping shouldVisit at a *Limit fixed the first query and its variants. I think that mapUnionArmOrdering should also refuse an arm whose route already has a LIMIT. Both queries could go into TestUnionAllOrderedLimitPushdown. No?
  2. Blocking: I think that the arm-route truncation shouldn't depend on the route's source being a *Limit (union.go:72).

    • When a UNION DISTINCT arm is wrapped in the generated dt(c0, ...) derived table, Union.planOffsets skips it, so the route-only merge-sort helper stays in that arm's output.
    • select cast(id as signed) as x, id from user union select cast(id as signed) as x, id from unsharded order by x limit 3, with untyped columns (no schema tracking and no column types in the VSchema), sends five columns from the user arm and four from the unsharded arm. Both modes then fail with ERROR 1222 (21000): The used SELECT statements have a different number of columns, and main returns MySQL's rows. The test vschema in planbuilder reproduces it.
    • TestOrderedUnionLimitKeepsHelperColumns only checks routes whose TruncateColumnCount is set, so it doesn't catch an arm that was never truncated.
    • I wonder if setUpperLimit could record the routes that get an arm ordering, and Union.planOffsets could truncate exactly those, whatever their source looks like. The test could then check that every Concatenate input has the same width. What do you think?
  3. I wonder if Concatenate should run its arms sequentially in a reserved-connection session, as it does in a transaction (concatenate.go:152 and :202).

    • Outside a transaction, it runs arms in parallel. A split select id from ref union all select id from user always sends the reference arm to one of the scatter's shards.
    • In a session that holds reserved connections (temporary tables, GET_LOCK() and so on), both queries then use the same reserved connection on that shard at once. A scratch executor test showed the two queries with the same reservedID. From the code, VTTablet's TxPool.GetAndLock returns in use (ABORTED) to the second one; I couldn't run that part end to end.
    • main already does this when two single-shard arms land on one shard, such as ... where id = 1 union all ... where id = 2. But every split reference or dual union in such a session can now hit it.
  4. I think that the reference-copy swap that mergeOrJoin now does after a refused merge (route_planning.go:306-309) should check the same thing that canReplaceCTESeed checks for CTE seeds.

    • The copy is the bare table, so a derived table around it is dropped. select u.id from (select id from source_of_ref limit 1) dt left join user u on u.col = 5 sends select 1 from ref_with_source as source_of_ref, and then runs one user scatter for every reference row instead of one.
    • main loses the limit 1 as well, inside its merged scatter, so the result is no worse. But the cost now grows with the size of the reference table.
  5. I think that the Deployment Notes should mention a few more changes:

    • Ordered LIMITs over unions that main already split no longer get the unordered per-arm limit (#21956). When the arms' sort types can't be shown to match, for example without schema tracking, each arm is read in full. In OLTP mode that can reach --max-memory-rows. One example is select id from user union all select id from unsharded order by id limit 5.
    • --max-memory-rows now also caps recursive Term executions, but its help text doesn't say so. With it set below 1,000, recursions that run on main now fail, and the UNION DISTINCT cap is really the smaller of 1,000 and that flag.
    • With prevent_cross_keyspace_reads set, a cross-keyspace recursive CTE without any reference table now fails with VT12001. One example is an unsharded seed with a sharded Term.
    • The arm-local weight strings in #21957 also mis-sort mixed integer and string keys. select intcol from user union all select 'a' from dual order by intcol limit 3 returns [a, -5, 0], where MySQL and main return [-5, 0, 10].

Thanks for sticking with this one!

A non-planable lookup miss leaves no per-shard bind maps. Preserve the
evaluated IN tuple when sending a marked route to an arbitrary shard,
without mutating the caller's bindings.

Cover buffered and streaming fallback bindings and merged reference UNION
DISTINCT lookup misses end to end. Clear the existing unique lookup table
between test runs so the expanded fixture remains repeatable.

Signed-off-by: Ankit Patnaik <ankit.123patnaik123@gmail.com>

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.

🔵 Needs a closer look

Human assessment is needed because an unpublished finding identifies missing indexed bindings in the multi-column IN fallback, causing reference UNION DISTINCT queries to fail in both buffered and streaming execution.

No open issues 🎉

Review effort: Balanced

@mattlord mattlord left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the update @patnaikankit! The __vals binding for a no-route IN fallback works for single-column vindexes. TestSelectINNoRouteBindsFallbackValues fails if I drop the binding, skip it in streaming mode, or write it into the caller's map.

  1. Blocking: I think that the fallback should also bind __vals0, __vals1 and so on when the route's vindex has more than one column (engine/route.go:135-142).

    • For a MultiColumn vindex, inMultiCol binds one list for each IN column (shardVarsMultiCol, routing.go:660), and the planner writes those names into the query. select id from ref union select cola from multicol_tbl where cola in (1, 2) and colb in (3, 4) merges into one IN route on multicolIdx that sends ... where cola in ::__vals0 and colb in ::__vals1, and the reference arm gives that route NoRoutesSpecialHandling.
    • Route.anyShard evaluates only route.Values[0] and binds it as __vals. So when every value misses, such as an unknown region in a region_json vindex, the fallback query has no __vals0, and VTTablet fails it with missing bind var __vals0. I checked this in a scratch engine test: I gave a multicol route values that all miss, and ran the fallback's bind variables through GenerateQuery, as VTTablet does. On main the same query returns no rows on a miss, as in #21959, so it's wrong either way, but this commit is meant to return the reference rows.
    • In a scratch change, I bound __vals<i> for each route.Values[i] that evaluates to a tuple, which is how generateRowColValues tells lists from single values. That fixed the multi-column cases, and the engine tests still passed. A multi-column case in TestSelectINNoRouteBindsFallbackValues would pin it. #21962 has the same Route.anyShard, so it needs the same change. What do you think?
  2. Blocking: Points 1 and 2 from my last review still apply at this head, since this commit doesn't change the planner. The route under an arm's own LIMIT still sorts by the outer key (0 ASC). The cast(id as signed) UNION DISTINCT still sends five columns from the user arm and four from the unsharded arm.

  3. Points 3, 4 and 5 from my last review still apply too.

Thanks for sticking with this one!

Keep arm-local LIMITs as barriers before and after Horizon expansion. Track
pushed arm ordering explicitly so generated DISTINCT wrappers do not leak
route-only sort helpers.

Serialize concatenation in reserved sessions, preserve derived wrappers
when selecting reference copies, and enforce the actual keyspace policy
when a copy cannot safely replace its input. Clarify the recursive work
limit in the max-memory-rows help text.

Add planner, concurrency, and execution regressions. Update four route
queries in snapshots to preserve their existing local limits.

Validation: full engine, planner, operator, and executor suites; race checks
for concatenation, recursive execution, and IN fallback; rebuilt binaries
with full UNION e2e and lookup e2e twice; 153 tester queries plus 14 OLAP
queries; nine targeted mutation checks; full lint (zero issues).

Deployment notes prepared for the PR description: ordered UNION limits
with incompatible or unknown arm sort types read full arm inputs and may
reach memory/result-size budgets. Reserved-session arms run sequentially.
Derived inputs that cannot safely use a bare reference copy retain their
original keyspace and obey cross-keyspace policy. Recursive term work is
capped by max-memory-rows; DISTINCT has the smaller of that cap and 1000.
Cross-keyspace recursive CTE policy also applies without reference tables.
Mixed integer/string arm-local weight sorting remains deferred to vitessio#21957.

Signed-off-by: Ankit Patnaik <ankit.123patnaik123@gmail.com>
Use indexed list names for multi-column vindexes when no destinations are
found. Bind every tuple input under its original column index, skip scalar
inputs, and preserve the caller's bind variables. Single-column routes
continue to use __vals.

Cover list/list, scalar/list, and list/scalar misses in buffered and
streaming execution, including VTTablet-style GenerateQuery substitution.
The six multi-column cases fail before the fix. Five targeted mutations
catch omitted columns, wrong indexes, scalar-list confusion, caller-map
mutation, and incorrect values.

Validation: full engine, planner, and operator suites; IN routing race
checks; rebuilt binaries with full UNION e2e and lookup e2e twice; all nine
CI-pinned tester workloads (153 queries) plus the 14-query OLAP workload;
full lint (zero issues).

Signed-off-by: Ankit Patnaik <ankit.123patnaik123@gmail.com>

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

Reserved-session streaming buffers all UNION results before delivering rows without enforcing MaxMemoryRows, creating an unbounded memory-exhaustion risk in VTGate.

1 open issue

Review effort: Balanced

Comment thread go/vt/vtgate/engine/concatenate.go Resolved

@mattlord mattlord left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the update @patnaikankit! Last review's blockers are fixed at this head. I checked them with plan probes against main and with mutations:

  • The no-route IN fallback binds __vals0, __vals1 and so on for a multi-column vindex, and leaves scalar columns alone. TestSelectINNoRouteBindsFallbackValues fails if I bind __vals for every column, bind only the first column, or bind a scalar column as a list.
  • An arm with its own LIMIT keeps its own ordering (0 DESC under order by user.intcol desc limit 2), and the reference arm keeps its limit 1.
  • Both arms of the cast(id as signed) UNION DISTINCT now return four columns. TestOrderedDistinctUnionArmWidths fails if unionOrderingPushed is never set or never used.
  • The derived reference input keeps its limit 1, and the cross-keyspace check fires when it isn't swapped.
  1. Blocking: I think that go/flags/endtoend/vtgate.txt and vtcombo.txt need the new --max-memory-rows help text. The text changed in go/vt/vtgate/vtgate.go:199, but both files still have the old line. With this head's binaries, TestHelpOutput/vtgate and TestHelpOutput/vtcombo fail on that line alone. make generate-flag-testdata regenerates them from built binaries.

  2. Blocking: I agree with Copilot's thread on concatenate.go:204.

    • The reserved-session change came from my point 3 last time, and I missed that sequentialStreamExec holds every arm's rows in VTGate until the last arm finishes.
    • Transactions already work that way on main. But now OLAP queries in any session with a reserved connection are held in memory too, where main streamed them: a cross-keyspace UNION ALL, for example, or a split reference union, which main merged into one route.
    • I wonder if the sequential path could get each arm's fields from its GetFields first, as Concatenate.GetFields does, and then stream the arms one after another. That would also stop transactions from buffering. A simpler option is to check --max-memory-rows while it buffers, at least in reserved sessions. What do you think?
  3. I think that a planner test should pin the sharded arm case too. TestReferenceUnionArmKeepsLocalLimit covers the reference arm. But if I remove both the *Limit case in setUpperLimit's shouldVisit and the containsLimit check in mapUnionArmOrdering, the planner and operator tests still pass, so only the e2e queries in TestUnionAllOrderedLimitPushdown catch it. Adding (select intcol from user order by intcol desc limit 2) union all (select col from user) order by intcol limit 3 to that test would catch it without the cluster.

Thanks for sticking with this one!

Apply the shared row-memory budget before retaining each chunk across all
serialized UNION arms. Preserve the resource-exhausted error and MySQL
errno 1153 when a source aggregates callback errors. Keep the existing
IGNORE_MAX_MEMORY_ROWS behavior for retained rows.

Regenerate vtgate/vtcombo help snapshots for the updated flag description.
Pin sharded arm ordering below a local LIMIT, including the early planning
phase before a shard-local limit can provide another barrier.

Add budget, concurrency, error-state, and physical UNION regressions. The
pre-fix binaries return 2002 rows with a 2000-row budget; the fixed path
rejects the result and retains the explicit row-memory override.

Deployment note prepared for the PR: reserved and transactional OLAP UNIONs
still buffer to resolve common output types, but retained rows across all
arms now share max-memory-rows. Overflow returns RESOURCE_EXHAUSTED and
MySQL errno 1153. The explicit row-memory hint can bypass this buffer bound;
it does not lift recursive term-work limits. Ordinary streams stay parallel.

Validation: engine, planner, operator, executor, and all CLI help-output
suites; streaming/routing race checks; rebuilt binaries with full UNION e2e
and lookup e2e twice; 153 tester queries plus 14 OLAP queries; eight targeted
mutation checks; repository lint (zero issues).

Signed-off-by: Ankit Patnaik <ankit.123patnaik123@gmail.com>
@patnaikankit

Copy link
Copy Markdown
Author

Thanks @mattlord! Addressed the latest review and Copilot’s concern:

Regenerated the vtgate/vtcombo help snapshots; all help-output tests pass.

Added a shared row-memory budget across serialized UNION arms, checked before retaining chunks. RESOURCE_EXHAUSTED and errno 1153 survive callback-error aggregation. The existing row-memory override remains supported; recursive work limits are unchanged. Added the sharded LIMIT planner case and an early-phase operator regression. Removing both cited guards now fails without a cluster.

Deployment notes now describe the bounded buffering behavior. Please take another look when you have a chance.

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.

🔵 Needs a closer look

Human review is needed to assess an unpublished concern that nonfatal type checks in rebinding tests can allow execution to continue into nil-pointer dereferences.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@mattlord mattlord left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the update @patnaikankit! Last review's points are fixed at this head:

  • With this head's binaries, TestHelpOutput/vtgate and TestHelpOutput/vtcombo pass.
  • TestConcatenateSequentialStreamMemoryLimit fails if I drop the budget check, count rows per arm instead of across arms, stop returning the cached error after an aggregated source error, ignore the IGNORE_MAX_MEMORY_ROWS hint, or move the boundary by one.
  • TestUpperLimitStopsAtArmLimit fails if I remove the *Limit barrier from setUpperLimit, so the arm-LIMIT guard no longer depends on the e2e tests.
  1. Blocking: I think that the ordering that mapUnionArmOrdering pushes into each arm should qualify its columns.

    • At go/vt/vtgate/planbuilder/operators/query_planning.go:718, the pushed ORDER BY is the arm's select expression as written. MySQL resolves an unqualified name in ORDER BY to a select alias before a table column.
    • So select col as a, intcol as col from user union all select col41, col41 from unsharded_fk_allow.u_tbl4 order by a limit 5 sends select col as a, intcol as col from user order by col asc limit :__upper_limit to each shard. Each shard keeps the five rows with the smallest intcol, not the smallest col, so the final top five are wrong.
    • I checked the arm query on MySQL 8.0.46 and 8.4.9 over the rows (col, intcol) = (30, 1), (20, 2), (10, 3), (5, 4). With limit 2 it returns a = 30, 20, while MySQL's own UNION returns 5, 10. With 5 as col in place of intcol as col, the arm isn't sorted at all.
    • main doesn't push an ORDER BY here (that's #21956). For a single route, both main and this head already qualify the column: order by user.col asc.
    • I think that we should qualify the column the same way, or skip the pushdown when the name matches another alias in the arm, and add this query as a planner case and to TestUnionAllOrderedLimitPushdown. No?
  2. Blocking: I think that hitting the new buffer limit in sequentialStreamExec shouldn't roll back the caller's transaction.

    • The callback returns its RESOURCE_EXHAUSTED error from inside the shard stream (go/vt/vtgate/engine/concatenate.go:342-344). ScatterConn.endAction (go/vt/vtgate/scatter_conn.go:117-118) calls SetRollback() for any RESOURCE_EXHAUSTED or ABORTED shard error. So multiGoTransaction rolls back every shard session, and the session leaves the transaction.
    • I checked this with an executor test in go/vt/vtgate: maxMemoryRows = 3, an OLAP transaction that inserts into main1, then select id from main1 union all select id from user where id = 1 with two rows per arm.
      • At this head the SELECT fails, session.InTransaction() is false afterwards, and the insert is rolled back. The following COMMIT returns no error and commits nothing.
      • On main, the SELECT returns the four rows and the transaction stays open.
    • So an application that handles the error and goes on to commit loses its earlier writes without being told. MySQL doesn't roll back a transaction for a failed SELECT. The existing --max-memory-rows checks don't either: MemorySort returns a plain error from the same kind of stream callback (memory_sort.go:105), and the OLTP check in ScatterConn.ExecuteMultiShard runs after the shard calls.
    • I think that the callback could return a plain sentinel error to stop the stream, since sequentialStreamExec already returns the cached bufferErr once the source returns. TestSerializedUnionStreamMemoryLimit could then check that the transaction is still open after the error, for example by reading back a row inserted earlier in the same transaction. No?
  3. Blocking: I think that the helper columns need trimming on arms that aren't a bare Route too.

    • Take select * from (select count(*) c from user union all select count(*) from unsharded) t order by c limit 10. setUpperLimit (query_planning.go:620-622) pushes the mapped ordering into the route under the scalar Aggregate, so that route returns count(*), weight_string(count(*)).
    • Union.planOffsets (union.go:64-72) trims only arms that are a *Route. So the Aggregate arm keeps two columns while the unsharded arm is cut to one, and the query fails with errno 1222 ("The used SELECT statements have a different number of columns").
    • main plans both arms at one column and returns the counts. No reference table is involved.
    • The bare form from an earlier round, select 1 as c from dual union all select count(*) from user order by c limit 3, lines up now. It's the derived table around the UNION that misses the trim: select * from (select count(*) c from user union all select 7 from dual) t order by c limit 10 fails the same way.
    • A width check over generated UNION queries found about 90 of this shape that line up on main and not at this head.
    • TestOrderedDistinctUnionArmWidths requires every arm to be a Route, so it can't see this.
    • I wonder if the simplest fix is to skip the arm ordering for a route under a scalar Aggregator, which returns one row per shard anyway, or to trim at the arm's root rather than only on a bare Route.
    • A related shape with untyped columns, select id from user union select id from music union all select id from user_extra order by id limit 3, now gets a three-column Distinct arm next to a two-column arm. There main only returned rows through the unordered per-arm caps of #21956, and the same query without LIMIT already fails this way on main, so the aggregate case is the clearer one.
    • What do you think?
  4. I wonder if recursive CTEs that main already evaluates in VTGate should keep main's work bound.

    • In go/vt/vtgate/engine/recurse_cte.go:67 and :90 (:162 and :186 when streaming), a UNION ALL recursion now counts levels, and the only bound on term executions is --max-memory-rows (300,000 by default). Each term execution can be a scatter.
    • Take a cyclic or runaway CTE whose levels hold many rows, with no reference table or dual seed. On main it fails with VT09030 after 1,000 term queries; now it can send up to 300,000 queries before it fails.
    • I suggested level counting in an earlier round, and it does match MySQL's cte_max_recursion_depth. But tying the work cap to --max-memory-rows also means that an operator who lowers that flag to protect VTGate memory gets a tighter recursion limit.
    • Could the work cap get its own bound that keeps main's 1,000 term executions by default (or scales with the seed for the newly split reference and dual seeds), rather than reusing --max-memory-rows? What do you think?
  5. I think that the Deployment Notes should cover two more plan changes.

    • A scatter UNION DISTINCT with ORDER BY ... LIMIT now reads every distinct row from every shard, even with typed columns. An example is select intcol from user union select intcol from music order by intcol limit 3, where main sent an unordered limit :__upper_limit.
      • The notes say full reads happen only when compatible sort types can't be established.
      • Pushing order by intcol limit :__upper_limit into that merged route would also be correct, since each shard deduplicates its own rows first.
    • A derived column list over a newly split reference UNION ALL, such as select c from (select id from user union all select id from ref) t(c), now fails with VT13001. main merged it, with the duplicate rows, and fails the same way with unsharded in place of ref.

Thanks for sticking with this one!

Qualify mapped arm ORDER BY columns so select aliases cannot shadow their
original table bindings. Stop mapped ordering at aggregate arms rather than
leaking route-only helper columns into Concatenate.

Stop serialized streams with a plain internal error on buffer overflow and
return the cached RESOURCE_EXHAUSTED client error after the source finishes,
preserving earlier writes and the caller's transaction.

Restore the 1000-term work bound independently of row-memory policy. Scale
only newly split replicated seeds using the existing rejected-merge marker.
Update row-override tests and regenerate the CLI help snapshots.

Validation: full engine/planner/operator/executor/help suites; rebuilt
binaries; full UNION e2e; lookup e2e twice; 153 CI-pinned tester queries plus
14 OLAP queries; focused race tests; 16 mutation checks; lint (zero issues).

Signed-off-by: Ankit Patnaik <ankit.123patnaik123@gmail.com>

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.

🔵 Needs a closer look

Human assessment is needed because a critical UNION planning path can bypass cross-keyspace read restrictions, and this finding was omitted from the published review.

No open issues 🎉

Review effort: Balanced

@patnaikankit

Copy link
Copy Markdown
Author

Thanks @mattlord! Addressed the latest review:

  • Qualified pushed ordering columns to prevent alias shadowing.
  • Preserved the caller’s transaction and earlier writes after buffer overflow.
  • Blocked ordering pushdown beneath aggregates to prevent helper-column leaks.
  • Restored the independent 1,000-term work bound, scaling only newly split reference/dual seeds.
  • Updated deployment notes for scatter UNION DISTINCT reads and derived column-list limitations.

Full UNION e2e, lookup e2e twice, 167 tester queries, unit suites, race checks, and lint all passed. Sixteen mutation checks also verified the new fixes and earlier regression protections.

Please take another look when you have a chance. I’ll address any further review feedback next weekend.

@mattlord mattlord left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the update @patnaikankit! Last review's points are fixed at this head:

  • TestUnionArmOrderingQualifiesColumns fails if I drop the qualifier. TestDerivedUnionScalarAggregateArmWidth fails if I remove the *Aggregator case from routesForUnionArm. Both derived count(*) unions now send one column from every arm.
  • TestConcatenateSequentialStreamMemoryLimit fails if the callback goes back to returning the RESOURCE_EXHAUSTED error itself.
  • The recursive work cap is back to 1,000 term executions, scaled only for the rejected replicated seeds. The engine and planner tests fail if I drop the scaling, scale every plan, set ScaleWorkLimitBySeed to a constant, move the boundary by one, or go back to --max-memory-rows.
  1. Blocking: I think that the qualifier should go on a copy of the arm's expression, not on the arm's own select expression.

    • ctx.SemTable.Clone(expr) at go/vt/vtgate/planbuilder/operators/query_planning.go:721 hands back the same ColName nodes here (I compared the pointers in a debug build). So the walk below it sets Qualifier on the arm's own SELECT list.
    • MySQL names an unaliased expression column after its text, and Concatenate takes its field names from the first arm. So select cast(id as signed) from user union all select cast(id as signed) from unsharded order by 1 limit 3 now sends select cast(`user`.id as signed), ... to the user shards, and the client gets a column named cast(`user`.id as signed). MySQL and main return cast(id as signed). I checked the arm query's column name on MySQL 8.0.46 and 8.4.9.
    • The change stays even when the pushdown is refused afterwards. select cast(id as signed) from user union all (select cast(id as signed) from unsharded limit 1) order by 1 limit 3 pushes no ordering, but it still sends the qualified expression. The same happens with a reference arm, ... union all select cast(id as signed) from ref order by 1 limit 3, which main merged.
    • I think that we could build the qualified expression with sqlparser.CopyOnRewrite, replacing each unqualified ColName with a new qualified one and copying its dependencies. TestUnionArmOrderingQualifiesColumns could also check that the first arm's select list is unchanged. mcmp.Exec doesn't compare column names, so running these queries through ExecWithColumnCompare in TestUnionAllOrderedLimitPushdown would catch this end to end. No?
  2. Blocking: I think that a test should cover the bufferFull return for a chunk that arrives after the limit was hit.

    • At go/vt/vtgate/engine/concatenate.go:344, a callback that runs after bufferErr is set returns bufferFull. The other shards of a scatter arm reach that line, because they keep streaming after one shard's chunk trips the limit.
    • If I change that line back to return bufferErr, every test still passes. The concurrent-callbacks source delivers only two chunks, and the second one trips the limit. In a real scatter, those other shards would then return RESOURCE_EXHAUSTED and roll the transaction back again.
    • A third chunk in the concurrent-callbacks case catches it: with left.results = append(left.results, first, first), the test passes at this head and fails with that line reverted.
  3. I wonder if the Deployment Notes should say that a large arm can still end the transaction, or if the arm should be drained instead.

    • Any error from the callback makes grpctabletconn's StreamExecute return and cancel the stream (go/vt/vttablet/grpctabletconn/conn.go:156-161). Inside a transaction, VTTablet streams with StreamOnce (go/vt/vttablet/tabletserver/query_executor.go:2048-2049). When the context ends before the fetch does, Conn.terminate kills the whole MySQL connection (go/vt/vttablet/tabletserver/connpool/dbconn.go:223-226), and that rolls back the shard's transaction.
    • So it seems like the transaction survives only when the overflowing arm's shard streams have already finished. That holds in TestSerializedUnionStreamMemoryLimit, where each shard sends one small chunk. With an arm larger than the tablet's stream buffer, I think that the client gets errno 1153, and then an error on its next statement or COMMIT on that shard. I haven't run this against a real tablet.
    • MemorySort's limit on main behaves the same way, and I missed this when I suggested the sentinel last time. The callback could discard the rest of the arm's rows after the limit, rather than stopping the stream. That would keep the transaction, at the cost of reading the arm in full. Otherwise, the notes could say that the transaction can be lost. What do you think?
  4. Since the work cap no longer uses --max-memory-rows, I think that the flag's help text can go back to main's wording. That would also drop the two flag golden changes.

Thanks for sticking with this one!

Qualify mapped arm ordering through copy-on-write, retaining semantic
information without changing SELECT expressions or client field names.
Cover accepted and refused pushdown, including arm-local LIMITs.

Discard and drain remaining chunks after the serialized buffer fills,
then return the cached resource error without starting another arm.
This preserves active tablet transactions and preceding writes through
COMMIT. Add a third concurrent chunk and verify no callback interrupts
the stream, including callbacks after overflow.

Restore the main max-memory-rows help text and remove net flag golden
changes. Keep existing LIMIT, helper-column, reserved-session and
recursive-work protections intact.

Validation: full UNION e2e; lookup e2e twice; 167 CI-pinned tester queries;
engine/planner/operator/executor/help suites; focused race tests;
15 mutation checks; metadata e2e mutant; lint (zero issues).

Signed-off-by: Ankit Patnaik <ankit.123patnaik123@gmail.com>

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.

🔵 Needs a closer look

Coupled changes to routing provenance, LIMIT/offset planning, recursive execution, and transactional stream draining require planner/engine specialist review and runtime validation of query correctness and transaction preservation.

No open issues 🎉

Review effort: Balanced

@patnaikankit

Copy link
Copy Markdown
Author

Thanks @mattlord! Addressed all four points in 5aada71:

  • Qualified ordering expressions through copy-on-write, preserving SELECT expressions, dependencies and output column names even when pushdown is refused.
  • Added the third concurrent chunk to cover callbacks after overflow.
  • Changed overflow handling to discard further chunks and drain the active arm. The large-stream e2e case verifies that earlier writes survive and commit successfully. Deployment notes explain the additional work and latency from draining.
  • Restored main’s flag wording, removing the net golden-file changes.

Column-name e2e checks use quoted output names because of the existing UNION ordinal-normalization issue; planner tests retain the exact ORDER BY 1 cases.

Please take another look when you have a chance. I’ll address any further feedback next weekend.

@patnaikankit

Copy link
Copy Markdown
Author

@mattlord can you please take another look? I have resolved the latest review comments

@mattlord mattlord left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the update @patnaikankit! Last review's points are fixed at this head:

  • TestUnionArmOrderingPreservesSelectExpressions and TestUnionArmOrderingQualifiesColumns fail if I put the in-place qualification back.
  • The concurrent-callbacks case fails if either overflow site in sequentialStreamExec returns an error again. aggregated-source-error fails if the source error wins over the cached one.
  • The flag text is back to main's.
  1. Blocking: I think that TestSerializedUnionStreamMemoryLimit needs utils.SkipIfBinaryIsBelowVersion(t, 25, "vtgate"), like the other new tests in that file.

    • The union package runs in upgrade_downgrade_query_serving_queries_2 (test/config.json). That workflow has a vtgate=N-1, vttablet=N leg, which runs release-24.0's VTGate.
    • There, Concatenate has no shared row budget, and select id from ref union all select id1 from t1 merges into one route. So the query succeeds and require.ErrorContains(..., "in-memory row count exceeded allowed limit of 2000") fails.
    • CI hasn't run the upgrade jobs on this PR yet, so this hasn't shown up.
  2. Blocking: I think that a test should cover the arm sort-type check in mapUnionArmOrdering (go/vt/vtgate/planbuilder/operators/query_planning.go:708, commonTypes[i] != typeKey).

    • That check is what keeps the per-arm ORDER BY ... LIMIT from being pushed when the arms sort differently. If I make it always false, every test in planbuilder and operators still passes.
    • With that change, select textcol1 from user union all select col41 from unsharded_fk_allow.u_tbl4 order by 1 limit 3 pushes order by u_tbl4.col41 asc limit :__upper_limit into the INT16 arm. MySQL sorts that UNION as strings, so a numeric top-3 such as 1, 2, 3 can drop 10, which sorts before 2, and the query returns the wrong rows.
    • A planner test with mixed typed arms, such as the query above or intcol against col4, that checks no arm gets :__upper_limit would catch it.
  3. I wonder if a recursion guard in the WHERE clause should keep working for reference and dual seeds.

    • Take with recursive c as (select id as n, 1 as lvl from ref union all select u.id, c.lvl + 1 from c join user u on u.col = c.n where c.lvl < 5) select n from c. It now plans as a RecurseCTE whose term sends select u.id, :c_lvl + 1 ... from `user` as u where c.lvl < 5 and u.col = :c_n.
    • The c.lvl in the WHERE clause isn't replaced by a bind variable, so I think every term execution fails with unknown column c.lvl. Written in the ON clause, it becomes :c_lvl < 5 and works.
    • main merged this query into one scatter route, which returned the wrong rows but ran. It already sends the same broken term for a sharded seed, so the binding gap is pre-existing. This PR makes WHERE c.lvl < N, a common depth guard, fail for every reference or dual seed.
    • I think that we should either bind CTE-only WHERE predicates in the split term, or list this in the Deployment Notes and file an issue for it. What do you think?
  4. I think that ENUM and SET sort keys belong with the #21957 follow-up, and in the Deployment Notes.

    • select e from user union all select e from ref order by e limit 1, with e enum('b','a','c'), now splits. Each arm sorts by e, and the outer sort compares weight_string, which both follow the enum index.
    • MySQL sorts the UNION's result as a string. On 8.0.46 and 8.4.9, the union returns a, b, b, c, while order by e on one table returns b first, and weight_string(e) is index-based (8000000000000001).
    • So this returns b where MySQL returns a. main merged it into one route, which sorted correctly, apart from the repeated reference rows. Unions that main already split have the same ordering issue, so this isn't new, but this PR exposes it to reference unions.
  5. I wonder if the serialized path could be limited to arms that can share a shard session.

    • concatenate.go:202 now buffers every UNION in a reserved-connection session. That includes cross-keyspace OLAP unions, which main streamed, which can't share a reserved connection, and which now fail past --max-memory-rows.
    • Two independent reviews raised this again this round. The serialization came from my earlier suggestion, and the Deployment Notes do describe it. So this is a question about scope, not a request. Is always-serial the simpler trade-off you'd rather keep?
  6. RecurseCTE.description() (go/vt/vtgate/engine/recurse_cte.go:231) doesn't show Distinct or ScaleWorkLimitBySeed. So vexplain and the planner goldens can't show which plans get the per-seed work allowance. It seems like adding them to Other would make that visible.

  7. In CoerceTo (go/vt/vtgate/evalengine/api_coerce.go:32), changing len(raw) > len(buf) to >= would reject every BIT(64) value, and no test fails. A BIT(64) case in TestConcatenateCoercesBitValues would cover it. Separately, the BIT result ("65" for b'01000001' against a string arm) matches what MySQL 8.0.46 and 8.4.9 return, so that part looks right.

  8. About the UNION ordinal issue that the e2e comment mentions: on main, the normalizer turns select id from user union all select id from unsharded order by 1 limit 3 into order by :vtg1, and the planner then drops the sort entirely. Both arms get a bare limit :__upper_limit with no MemorySort. That seems like a silent wrong-result bug on its own. Is there an issue for it?

Thanks for sticking with this one!

Use the existing CTE predicate binding mechanism for active recursive
WHERE predicates, matching ON-clause behavior without rewriting ordinary
term-table predicates. Expose Distinct and ScaleWorkLimitBySeed in plan
descriptions and update the active per-seed work snapshot.

Skip the serialized-stream memory test below vtgate v25 for upgrade runs.
Pin mixed sort-type rejection in both arm directions and cover BIT(64)
coercion in buffered and streaming execution without requiring arm order.
Add cyclic WHERE/ON depth-guard e2e coverage for reference, dual and
ordinary seeds with strict MySQL result comparisons.

Validation: engine/planner/operator/executor/help suites; rebuilt binaries;
full UNION e2e; lookup e2e twice; 167 CI-pinned tester queries; race checks;
20 repeated BIT race runs; 20 targeted mutations; lint (zero issues).
The full old-binary upgrade matrix was not run locally.

Signed-off-by: Ankit Patnaik <ankit.123patnaik123@gmail.com>

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.

🔵 Needs a closer look

Human assessment is needed to evaluate recursive-CTE binding risks in subquery predicates and regression-test compatibility with supported pre-v25 vtgate binaries.

No open issues 🎉

Review effort: Balanced

@patnaikankit

Copy link
Copy Markdown
Author

Thanks @mattlord! Pushed d673001 with the version skip, mixed-sort/BIT64 regressions, recursive WHERE binding fix and plan-description flags. Updated the ENUM/SET notes and kept the conservative reserved-session policy.

@mattlord mattlord left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the update @patnaikankit! Last review's points are fixed at this head:

  • TestRecursiveWherePredicatesAreBound fails without the new binding in addWherePredsToSubQueryBuilder. The binding also fixes the comma-join form on main: from c, user u where u.id = c.n now sends u.id = :c_n as an EqualUnique route, where main sent an unbound u.id = c.n to every shard. A guard in the WHERE clause of a c left join user u term lands on the outer side, which keeps the WHERE semantics, and fully merged recursive CTEs still send the original c.lvl < 5.
  • TestUnionArmOrderingRejectsMixedSortTypes fails if the sort-type check always passes, TestConcatenateCoercesBitValues/BIT64 fails with >=, and TestRecursiveDistinctPreservesExistingPlans fails if Distinct isn't shown.
  • TestSerializedUnionStreamMemoryLimit now skips for VTGate below v25.

One pre-existing thing I noticed while checking the WHERE binding, which isn't for this PR: a correlated EXISTS on the CTE in the term, such as ... from c join user u on u.col = c.n where exists (select 1 from music m where m.user_id = c.n), sends select u.id, :c_lvl + 1 as ..., c.n from user as u where u.col = :c_n as the semi-join's outer side. That c.n is unbound, so I think it fails with unknown column. main plans the same query the same way for both reference and sharded seeds, so this PR doesn't change it. It seems worth its own issue.

Looks good to me. Thanks for sticking with this one!

@patnaikankit

Copy link
Copy Markdown
Author

Hi @arthurschreiber @frouioui, Matt has approved this PR after multiple rounds of review, and his feedback has been addressed. Can you please take a look and review it as well? Can you also update or remove the remaining Needs* labels as appropriate? I don’t have permission to change them, and they’re blocking the label check. Thanks!

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: Query Serving 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 Type: Bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Reference table arm merged into a multi-shard UNION ALL route returns its rows once per shard

3 participants