Repository navigation
vtgate: avoid duplicate reference rows in UNION ALL - #21354
patnaikankit wants to merge 40 commits into
Conversation
Review ChecklistHello reviewers! 👋 Please follow this checklist when reviewing this Pull Request. General
Tests
Documentation
New flags
If a workflow is added or modified:
Backward compatibility
|
There was a problem hiding this comment.
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
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.
There was a problem hiding this comment.
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
Open (2)
Resolved since last review (1)
|
@frouioui @arthurschreiber, please take a look at the changes and let me know if there is anything that I might have missed / not considered. |
|
@mattlord, addressed points 1–5 in d5bb194:
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
left a comment
There was a problem hiding this comment.
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
textcolandcount(*)unions return MySQL's rows. - The arms no longer send
order by 0ororder by 1, and normalized:vtgNliterals are skipped too. - The weight-string offset check is in place.
IGNORE_MAX_MEMORY_ROWSno longer lifts theTermcap.- 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.
-
Blocking: I think that the outer ordering shouldn't be pushed into an arm that has its own
LIMIT.routesForUnionArmwalks through an arm's VTGateLimitto the route below it, andsetUpperLimit'sshouldVisit(query_planning.go:604-622) has no*Limitcase.- So the arm's route gets the outer
ORDER BYand:__upper_limitunderneath the arm's ownLIMIT. Its scatter merge then sorts by the outer key: the plan shows0 ASCwheremainhas0 DESC. - The arm's
Limittherefore keeps the wrong rows. With typedidcolumns, as schema tracking provides,(select id from user order by id desc limit 2) union all (select id from music) order by id limit 3returns[1, 2, 100]in both modes, where MySQL andmainreturn[11, 12, 100]. - When the arm's
LIMITis 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 3sendsorder by ref.intcol desc, intcol asc limit 3to the reference arm, so it can return more than the one row itslimit 1allows. Onmainthat query is merged and correct.mainalready has this problem for an unsharded arm in another keyspace, but splitting reference arms now brings it to them. - In a scratch run, stopping
shouldVisitat a*Limitfixed the first query and its variants. I think thatmapUnionArmOrderingshould also refuse an arm whose route already has aLIMIT. Both queries could go intoTestUnionAllOrderedLimitPushdown. No?
-
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 DISTINCTarm is wrapped in the generateddt(c0, ...)derived table,Union.planOffsetsskips 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 theuserarm and four from theunshardedarm. Both modes then fail withERROR 1222 (21000): The used SELECT statements have a different number of columns, andmainreturns MySQL's rows. The test vschema inplanbuilderreproduces it.TestOrderedUnionLimitKeepsHelperColumnsonly checks routes whoseTruncateColumnCountis set, so it doesn't catch an arm that was never truncated.- I wonder if
setUpperLimitcould record the routes that get an arm ordering, andUnion.planOffsetscould truncate exactly those, whatever their source looks like. The test could then check that everyConcatenateinput has the same width. What do you think?
- When a
-
I wonder if
Concatenateshould run its arms sequentially in a reserved-connection session, as it does in a transaction (concatenate.go:152and:202).- Outside a transaction, it runs arms in parallel. A split
select id from ref union all select id from useralways 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 samereservedID. From the code, VTTablet'sTxPool.GetAndLockreturnsin use(ABORTED) to the second one; I couldn't run that part end to end. mainalready 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 ordualunion in such a session can now hit it.
- Outside a transaction, it runs arms in parallel. A split
-
I think that the reference-copy swap that
mergeOrJoinnow does after a refused merge (route_planning.go:306-309) should check the same thing thatcanReplaceCTESeedchecks 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 = 5sendsselect 1 from ref_with_source as source_of_ref, and then runs oneuserscatter for every reference row instead of one. mainloses thelimit 1as well, inside its merged scatter, so the result is no worse. But the cost now grows with the size of the reference table.
- The copy is the bare table, so a derived table around it is dropped.
-
I think that the Deployment Notes should mention a few more changes:
- Ordered
LIMITs over unions thatmainalready 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 isselect id from user union all select id from unsharded order by id limit 5. --max-memory-rowsnow also caps recursiveTermexecutions, but its help text doesn't say so. With it set below 1,000, recursions that run onmainnow fail, and theUNION DISTINCTcap is really the smaller of 1,000 and that flag.- With
prevent_cross_keyspace_readsset, a cross-keyspace recursive CTE without any reference table now fails with VT12001. One example is an unsharded seed with a shardedTerm. - 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 3returns[a, -5, 0], where MySQL andmainreturn[-5, 0, 10].
- Ordered
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>
There was a problem hiding this comment.
🔵 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
left a comment
There was a problem hiding this comment.
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.
-
Blocking: I think that the fallback should also bind
__vals0,__vals1and so on when the route's vindex has more than one column (engine/route.go:135-142).- For a
MultiColumnvindex,inMultiColbinds one list for eachINcolumn (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 oneINroute onmulticolIdxthat sends... where cola in ::__vals0 and colb in ::__vals1, and the reference arm gives that routeNoRoutesSpecialHandling. Route.anyShardevaluates onlyroute.Values[0]and binds it as__vals. So when every value misses, such as an unknown region in aregion_jsonvindex, the fallback query has no__vals0, and VTTablet fails it withmissing bind var __vals0. I checked this in a scratch engine test: I gave amulticolroute values that all miss, and ran the fallback's bind variables throughGenerateQuery, as VTTablet does. Onmainthe 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 eachroute.Values[i]that evaluates to a tuple, which is howgenerateRowColValuestells lists from single values. That fixed the multi-column cases, and the engine tests still passed. A multi-column case inTestSelectINNoRouteBindsFallbackValueswould pin it. #21962 has the sameRoute.anyShard, so it needs the same change. What do you think?
- For a
-
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
LIMITstill sorts by the outer key (0 ASC). Thecast(id as signed)UNION DISTINCTstill sends five columns from theuserarm and four from theunshardedarm. -
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>
mattlord
left a comment
There was a problem hiding this comment.
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
INfallback binds__vals0,__vals1and so on for a multi-column vindex, and leaves scalar columns alone.TestSelectINNoRouteBindsFallbackValuesfails if I bind__valsfor every column, bind only the first column, or bind a scalar column as a list. - An arm with its own
LIMITkeeps its own ordering (0 DESCunderorder by user.intcol desc limit 2), and the reference arm keeps itslimit 1. - Both arms of the
cast(id as signed)UNION DISTINCTnow return four columns.TestOrderedDistinctUnionArmWidthsfails ifunionOrderingPushedis never set or never used. - The derived reference input keeps its
limit 1, and the cross-keyspace check fires when it isn't swapped.
-
Blocking: I think that
go/flags/endtoend/vtgate.txtandvtcombo.txtneed the new--max-memory-rowshelp text. The text changed ingo/vt/vtgate/vtgate.go:199, but both files still have the old line. With this head's binaries,TestHelpOutput/vtgateandTestHelpOutput/vtcombofail on that line alone.make generate-flag-testdataregenerates them from built binaries. -
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
sequentialStreamExecholds 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, wheremainstreamed them: a cross-keyspaceUNION ALL, for example, or a split reference union, whichmainmerged into one route. - I wonder if the sequential path could get each arm's fields from its
GetFieldsfirst, asConcatenate.GetFieldsdoes, and then stream the arms one after another. That would also stop transactions from buffering. A simpler option is to check--max-memory-rowswhile it buffers, at least in reserved sessions. What do you think?
- The reserved-session change came from my point 3 last time, and I missed that
-
I think that a planner test should pin the sharded arm case too.
TestReferenceUnionArmKeepsLocalLimitcovers the reference arm. But if I remove both the*Limitcase insetUpperLimit'sshouldVisitand thecontainsLimitcheck inmapUnionArmOrdering, the planner and operator tests still pass, so only the e2e queries inTestUnionAllOrderedLimitPushdowncatch it. Adding(select intcol from user order by intcol desc limit 2) union all (select col from user) order by intcol limit 3to 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>
|
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. |
There was a problem hiding this comment.
🔵 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
left a comment
There was a problem hiding this comment.
Thanks for the update @patnaikankit! Last review's points are fixed at this head:
- With this head's binaries,
TestHelpOutput/vtgateandTestHelpOutput/vtcombopass. TestConcatenateSequentialStreamMemoryLimitfails 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 theIGNORE_MAX_MEMORY_ROWShint, or move the boundary by one.TestUpperLimitStopsAtArmLimitfails if I remove the*Limitbarrier fromsetUpperLimit, so the arm-LIMIT guard no longer depends on the e2e tests.
-
Blocking: I think that the ordering that
mapUnionArmOrderingpushes into each arm should qualify its columns.- At
go/vt/vtgate/planbuilder/operators/query_planning.go:718, the pushedORDER BYis the arm's select expression as written. MySQL resolves an unqualified name inORDER BYto 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 5sendsselect col as a, intcol as col from user order by col asc limit :__upper_limitto each shard. Each shard keeps the five rows with the smallestintcol, not the smallestcol, 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). Withlimit 2it returnsa= 30, 20, while MySQL's ownUNIONreturns 5, 10. With5 as colin place ofintcol as col, the arm isn't sorted at all. maindoesn't push anORDER BYhere (that's #21956). For a single route, bothmainand 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?
- At
-
Blocking: I think that hitting the new buffer limit in
sequentialStreamExecshouldn'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) callsSetRollback()for any RESOURCE_EXHAUSTED or ABORTED shard error. SomultiGoTransactionrolls 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 intomain1, thenselect id from main1 union all select id from user where id = 1with two rows per arm.- At this head the
SELECTfails,session.InTransaction()is false afterwards, and the insert is rolled back. The followingCOMMITreturns no error and commits nothing. - On
main, theSELECTreturns the four rows and the transaction stays open.
- At this head the
- 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-rowschecks don't either:MemorySortreturns a plain error from the same kind of stream callback (memory_sort.go:105), and the OLTP check inScatterConn.ExecuteMultiShardruns after the shard calls. - I think that the callback could return a plain sentinel error to stop the stream, since
sequentialStreamExecalready returns the cachedbufferErronce the source returns.TestSerializedUnionStreamMemoryLimitcould 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?
- The callback returns its RESOURCE_EXHAUSTED error from inside the shard stream (
-
Blocking: I think that the helper columns need trimming on arms that aren't a bare
Routetoo.- 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 scalarAggregate, so that route returnscount(*), weight_string(count(*)). Union.planOffsets(union.go:64-72) trims only arms that are a*Route. So theAggregatearm keeps two columns while theunshardedarm is cut to one, and the query fails with errno 1222 ("The used SELECT statements have a different number of columns").mainplans 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 theUNIONthat misses the trim:select * from (select count(*) c from user union all select 7 from dual) t order by c limit 10fails the same way. - A width check over generated
UNIONqueries found about 90 of this shape that line up onmainand not at this head. TestOrderedDistinctUnionArmWidthsrequires every arm to be aRoute, 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 bareRoute. - 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-columnDistinctarm next to a two-column arm. Theremainonly returned rows through the unordered per-arm caps of #21956, and the same query withoutLIMITalready fails this way onmain, so the aggregate case is the clearer one. - What do you think?
- Take
-
I wonder if recursive CTEs that
mainalready evaluates in VTGate should keepmain's work bound.- In
go/vt/vtgate/engine/recurse_cte.go:67and:90(:162and:186when streaming), aUNION ALLrecursion 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
dualseed. Onmainit 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-rowsalso 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 anddualseeds), rather than reusing--max-memory-rows? What do you think?
- In
-
I think that the Deployment Notes should cover two more plan changes.
- A scatter
UNION DISTINCTwithORDER BY ... LIMITnow reads every distinct row from every shard, even with typed columns. An example isselect intcol from user union select intcol from music order by intcol limit 3, wheremainsent an unorderedlimit :__upper_limit.- The notes say full reads happen only when compatible sort types can't be established.
- Pushing
order by intcol limit :__upper_limitinto 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 asselect c from (select id from user union all select id from ref) t(c), now fails with VT13001.mainmerged it, with the duplicate rows, and fails the same way withunshardedin place ofref.
- A scatter
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>
|
Thanks @mattlord! Addressed the latest review:
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
left a comment
There was a problem hiding this comment.
Thanks for the update @patnaikankit! Last review's points are fixed at this head:
TestUnionArmOrderingQualifiesColumnsfails if I drop the qualifier.TestDerivedUnionScalarAggregateArmWidthfails if I remove the*Aggregatorcase fromroutesForUnionArm. Both derivedcount(*)unions now send one column from every arm.TestConcatenateSequentialStreamMemoryLimitfails 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
ScaleWorkLimitBySeedto a constant, move the boundary by one, or go back to--max-memory-rows.
-
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)atgo/vt/vtgate/planbuilder/operators/query_planning.go:721hands back the sameColNamenodes here (I compared the pointers in a debug build). So the walk below it setsQualifieron the arm's ownSELECTlist.- MySQL names an unaliased expression column after its text, and
Concatenatetakes its field names from the first arm. Soselect cast(id as signed) from user union all select cast(id as signed) from unsharded order by 1 limit 3now sendsselect cast(`user`.id as signed), ...to theusershards, and the client gets a column namedcast(`user`.id as signed). MySQL andmainreturncast(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 3pushes 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, whichmainmerged. - I think that we could build the qualified expression with
sqlparser.CopyOnRewrite, replacing each unqualifiedColNamewith a new qualified one and copying its dependencies.TestUnionArmOrderingQualifiesColumnscould also check that the first arm's select list is unchanged.mcmp.Execdoesn't compare column names, so running these queries throughExecWithColumnCompareinTestUnionAllOrderedLimitPushdownwould catch this end to end. No?
-
Blocking: I think that a test should cover the
bufferFullreturn for a chunk that arrives after the limit was hit.- At
go/vt/vtgate/engine/concatenate.go:344, a callback that runs afterbufferErris set returnsbufferFull. 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. Theconcurrent-callbackssource 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-callbackscase catches it: withleft.results = append(left.results, first, first), the test passes at this head and fails with that line reverted.
- At
-
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'sStreamExecutereturn and cancel the stream (go/vt/vttablet/grpctabletconn/conn.go:156-161). Inside a transaction, VTTablet streams withStreamOnce(go/vt/vttablet/tabletserver/query_executor.go:2048-2049). When the context ends before the fetch does,Conn.terminatekills 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 orCOMMITon that shard. I haven't run this against a real tablet. MemorySort's limit onmainbehaves 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?
- Any error from the callback makes
-
Since the work cap no longer uses
--max-memory-rows, I think that the flag's help text can go back tomain'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>
There was a problem hiding this comment.
🔵 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
|
Thanks @mattlord! Addressed all four points in 5aada71:
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. |
|
@mattlord can you please take another look? I have resolved the latest review comments |
mattlord
left a comment
There was a problem hiding this comment.
Thanks for the update @patnaikankit! Last review's points are fixed at this head:
TestUnionArmOrderingPreservesSelectExpressionsandTestUnionArmOrderingQualifiesColumnsfail if I put the in-place qualification back.- The
concurrent-callbackscase fails if either overflow site insequentialStreamExecreturns an error again.aggregated-source-errorfails if the source error wins over the cached one. - The flag text is back to
main's.
-
Blocking: I think that
TestSerializedUnionStreamMemoryLimitneedsutils.SkipIfBinaryIsBelowVersion(t, 25, "vtgate"), like the other new tests in that file.- The
unionpackage runs inupgrade_downgrade_query_serving_queries_2(test/config.json). That workflow has avtgate=N-1, vttablet=Nleg, which runs release-24.0's VTGate. - There,
Concatenatehas no shared row budget, andselect id from ref union all select id1 from t1merges into one route. So the query succeeds andrequire.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.
- The
-
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 ... LIMITfrom being pushed when the arms sort differently. If I make it always false, every test inplanbuilderandoperatorsstill passes. - With that change,
select textcol1 from user union all select col41 from unsharded_fk_allow.u_tbl4 order by 1 limit 3pushesorder by u_tbl4.col41 asc limit :__upper_limitinto the INT16 arm. MySQL sorts that UNION as strings, so a numeric top-3 such as1, 2, 3can drop10, which sorts before2, and the query returns the wrong rows. - A planner test with mixed typed arms, such as the query above or
intcolagainstcol4, that checks no arm gets:__upper_limitwould catch it.
- That check is what keeps the per-arm
-
I wonder if a recursion guard in the
WHEREclause should keep working for reference anddualseeds.- 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 aRecurseCTEwhose term sendsselect u.id, :c_lvl + 1 ... from `user` as u where c.lvl < 5 and u.col = :c_n. - The
c.lvlin theWHEREclause isn't replaced by a bind variable, so I think every term execution fails with unknown columnc.lvl. Written in theONclause, it becomes:c_lvl < 5and works. mainmerged 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 makesWHERE c.lvl < N, a common depth guard, fail for every reference ordualseed.- I think that we should either bind CTE-only
WHEREpredicates in the split term, or list this in the Deployment Notes and file an issue for it. What do you think?
- Take
-
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, withe enum('b','a','c'), now splits. Each arm sorts bye, and the outer sort comparesweight_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, whileorder by eon one table returnsbfirst, andweight_string(e)is index-based (8000000000000001). - So this returns
bwhere MySQL returnsa.mainmerged it into one route, which sorted correctly, apart from the repeated reference rows. Unions thatmainalready split have the same ordering issue, so this isn't new, but this PR exposes it to reference unions.
-
I wonder if the serialized path could be limited to arms that can share a shard session.
concatenate.go:202now buffers every UNION in a reserved-connection session. That includes cross-keyspace OLAP unions, whichmainstreamed, 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?
-
RecurseCTE.description()(go/vt/vtgate/engine/recurse_cte.go:231) doesn't showDistinctorScaleWorkLimitBySeed. Sovexplainand the planner goldens can't show which plans get the per-seed work allowance. It seems like adding them toOtherwould make that visible. -
In
CoerceTo(go/vt/vtgate/evalengine/api_coerce.go:32), changinglen(raw) > len(buf)to>=would reject everyBIT(64)value, and no test fails. ABIT(64)case inTestConcatenateCoercesBitValueswould cover it. Separately, the BIT result ("65"forb'01000001'against a string arm) matches what MySQL 8.0.46 and 8.4.9 return, so that part looks right. -
About the UNION ordinal issue that the e2e comment mentions: on
main, the normalizer turnsselect id from user union all select id from unsharded order by 1 limit 3intoorder by :vtg1, and the planner then drops the sort entirely. Both arms get a barelimit :__upper_limitwith noMemorySort. 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>
mattlord
left a comment
There was a problem hiding this comment.
Thanks for the update @patnaikankit! Last review's points are fixed at this head:
TestRecursiveWherePredicatesAreBoundfails without the new binding inaddWherePredsToSubQueryBuilder. The binding also fixes the comma-join form onmain:from c, user u where u.id = c.nnow sendsu.id = :c_nas anEqualUniqueroute, wheremainsent an unboundu.id = c.nto every shard. A guard in theWHEREclause of ac left join user uterm lands on the outer side, which keeps theWHEREsemantics, and fully merged recursive CTEs still send the originalc.lvl < 5.TestUnionArmOrderingRejectsMixedSortTypesfails if the sort-type check always passes,TestConcatenateCoercesBitValues/BIT64fails with>=, andTestRecursiveDistinctPreservesExistingPlansfails ifDistinctisn't shown.TestSerializedUnionStreamMemoryLimitnow 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!
|
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! |

Description
UNION ALLcan repeat reference-table ordualrows 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 < 5therefore 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 activeDistinctandScaleWorkLimitBySeedflags, 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:
__valsfor 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
dualprovenance 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.Before the fix, the new recursive WHERE e2e test fails with errno 1054 for the unbound
c.lvlcolumn. 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
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 DISTINCTwithORDER BY ... LIMITreads 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-rowsor 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 unexpandedSELECT *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 asselect 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 dualcombined 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 exampleselect 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 returnbfirst from a split reference UNION where MySQL's UNION would returna. 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-rowsbudget 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 explicitIGNORE_MAX_MEMORY_ROWShint 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_readsis enforced against those actual keyspaces unlessALLOW_CROSS_KEYSPACE_READSis 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/dualseeds 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_ROWSbypasses only these retained-row checks: it cannot lift the independent cumulative term-work or depth bounds. Lowering or raising--max-memory-rowsno 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
dualseed across shards,UNION DISTINCTnow 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 obeysPreventCrossKeyspaceReadsand the explicitALLOW_CROSS_KEYSPACE_READSoverride. This policy also applies to recursive CTEs without reference tables: an unsharded seed with a sharded term in another keyspace now fails with VT12001 whenprevent_cross_keyspace_readsdenies that read, unless explicitly overridden.AI Disclosure
Codex assisted with implementation, planner regressions, and end-to-end coverage. The author reviews the changes.