Skip to content

feat: multi-table INSERT ALL / INSERT FIRST ... INTO ... SELECT (#27470) - #27560

Merged
fengttt merged 37 commits into
matrixorigin:mainfrom
fengttt:feat-multi-insert
Aug 25, 2026
Merged

fengttt merged 37 commits into
matrixorigin:mainfrom
fengttt:feat-multi-insert

Conversation

@fengttt

@fengttt fengttt commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Feature

Which issue(s) this PR fixes:
issue #27470

What this PR does / why we need it:

Snowflake-style multi-table INSERT: insert the rows of one source query into several tables — possibly with different schemas — in one statement. Design doc: docs/design/multi_insert.md.

Syntax

-- Unconditional: every source row goes to every target.
INSERT ALL
  INTO t1 [(cols)] [VALUES (exprs)]
  INTO t2 [(cols)] [VALUES (exprs)]
SELECT ... ;

-- Conditional.
INSERT {ALL | FIRST}
  WHEN cond1 THEN INTO t1 [(cols)] [VALUES (...)] [INTO ...]
  WHEN cond2 THEN INTO t2 ...
  [ELSE INTO tN ...]
SELECT ... ;

WHEN conditions and VALUES expressions are evaluated against the source query's output columns; INTO t without VALUES inserts positionally. INSERT ALL routes a row to every WHEN whose condition is true, INSERT FIRST to the first one only; rows matching no WHEN go to ELSE; a NULL condition never matches. The same table may appear in several INTO clauses. WITH and prepared statements work.

Per the issue's scope, targets with foreign keys and external tables are rejected with a clear error; ON DUPLICATE KEY UPDATE / IGNORE / RETURNING / OVERWRITE are not part of the syntax. One grammar limitation: a parenthesized source subquery directly after a bare INTO t is a parse error (indistinguishable from a column list) — write SELECT ... without parentheses or give a column list.

Design

The source query is bound once and materialized in a SINK (step 0). Every target table becomes its own step reading it through a SINK_SCAN, followed by the unchanged modern single-table insert pipeline:

SINK_SCAN → [FILTER on the WHEN condition] → PROJECT (VALUES)
          → casts/defaults/auto-increment → Lock → DEDUP joins → MULTI_UPDATE

This is the same fan-out the engine already uses for IVF/fulltext maintenance; no operator or compiler changes — the planner only assembles existing nodes, so constraints, indexes (B-tree/unique/fulltext/ivfflat), defaults, auto-increment, atomicity, affected rows and privileges are inherited from single-table INSERT. INSERT FIRST / ELSE are expressed as earlier cond IS NOT TRUE filters. When the same table appears in several clauses, the clauses are widened to the union of their column lists and merged with UNION ALL in front of one write pipeline, so cross-clause duplicate keys are rejected exactly like in-batch duplicates of one INSERT ... SELECT. The sink is a streaming, in-memory channel fan-out (one batch per consumer edge, shared ref-counted batches, backpressure), not a materialization to disk.

The doc also records the chained/selector-based single-pipeline alternative that was considered, its costs and benefits, and why the sink design was kept.

Changes

  • Parser: tree.MultiInsert AST; grammar for INSERT ALL / FIRST ... INTO ... [WHEN/ELSE] ... SELECT (regenerated with zero conflicts).
  • Planner: pkg/sql/plan/bind_multi_insert.go; the tail of initInsertReplaceStmt is extracted into appendInsertReplaceSourceCasts / castInsertSourceColumn so single-table INSERT/REPLACE and every multi-insert target share it (single-table behaviour unchanged).
  • Frontend: MultiInsert classified as DML (transactions, INSERT privilege on every target, last_insert_id, db remapping, PREPARE).
  • Test mock: fulltext-indexed docs_ft table.

Tests

  • Parser unit tests (round trips, AST shape, syntax errors) and planner unit tests (step/node shape, FIRST/ELSE filter composition, same-table merge into one MULTI_UPDATE with UNION ALL, fulltext maintenance retained, rejected targets).
  • BVT, 415 statements across five files under test/distributed/cases/dml/insert/: multi_insert (smoke coverage incl. EXPLAIN), multi_insert_conditional (ALL vs FIRST over overlapping WHENs, ELSE, NULL conditions, condition/source shapes, atomicity, transactions), multi_insert_schema (different target schemas, types, constraints, conversions, other-db/temporary targets), multi_insert_big (300k-row source so every target writes S3 objects, asserted via metadata_scan; late failure rolls back already-flushed objects), multi_insert_skew (extreme imbalance, empty targets, ELSE that never fires / takes everything).
  • Regression: full pkg/sql/plan suite, the whole dml/insert BVT directory (2000/2000), lint/vet. Verified by hand: affected-row sums, PREPARE/EXECUTE with parameters, privilege denial when one target lacks INSERT.

🤖 Generated with Claude Code

https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6

…ixorigin#27470)

Snowflake-style multi-table insert:

  INSERT ALL INTO t1 [(cols)] [VALUES (...)] INTO t2 ... SELECT ...
  INSERT {ALL | FIRST}
      WHEN cond THEN INTO t1 ... [INTO ...]
      [WHEN ... THEN INTO ...]
      [ELSE INTO ...]
  SELECT ...

Parser: new tree.MultiInsert AST (INTO clauses with optional column list
and VALUES expressions evaluated over the source query's output columns);
grammar with no new conflicts (a parenthesized source directly after a
bare INTO is rejected, since it is indistinguishable from a column list).

Planner: the source query is bound once and materialized in a SINK
(step 0). Every target table gets its own write step reading it through a
SINK_SCAN -> [FILTER on the WHEN condition] -> PROJECT (VALUES) and then
the regular modern insert pipeline (casts/defaults/auto-increment, lock,
dedup joins, MULTI_UPDATE), so primary/unique keys and B-tree indexes are
maintained exactly as for a single INSERT, and IVF/fulltext indexes get
their usual maintenance steps. INSERT FIRST and ELSE are expressed as
"earlier condition IS NOT TRUE" filters, so a NULL condition never
matches. When the same table appears in several INTO clauses, the clauses
are widened to the union of their column lists and merged with UNION ALL
in front of one write pipeline, so duplicate keys produced by different
clauses are rejected like in-batch duplicates of one INSERT ... SELECT.
Affected rows are summed over targets; a failure in any target rolls back
the whole statement. Tables with foreign keys and external tables are
rejected, per the issue's scope.

Frontend: MultiInsert is classified as DML (transactions, INSERT
privilege on every target, last_insert_id, db remapping, PREPARE).
- multi_insert_conditional.sql (107): INSERT ALL vs INSERT FIRST over
  overlapping WHEN conditions, ELSE, NULL conditions, subquery/LIKE/BETWEEN/
  IS NULL conditions, computed source aliases, several INTOs per WHEN, the
  same table under several WHENs, aggregate/join/union/limit/distinct/empty
  sources, atomicity and explicit transactions. Every assertion is checked
  against the equivalent filtered SELECT or a join between targets.
- multi_insert_schema.sql (74): destination tables with different shapes,
  types and constraints (unique/secondary/composite/fake pk, auto-increment,
  NOT NULL, CHECK, generated, cluster by), json/enum/binary/date conversions,
  other-database and temporary targets, a target that is also the source,
  case-insensitive and qualified column lists, widened same-table clauses.
- multi_insert_big.sql (73): 300k rows x ~520 bytes so every target's Multi
  Update flushes S3 objects (asserted through metadata_scan), FIRST/ALL over
  the big source, a merged 600k-row same-table write, a late duplicate that
  rolls back already-flushed objects of another target, mo_ctl flush and
  re-read, big insert in a rolled-back transaction.

All four multi_insert*.sql files pass in mo-tester compare mode.
…ches (matrixorigin#27470)

multi_insert_skew.sql (82): on the 300k-row source, one WHEN takes
(almost) everything while siblings take 3 rows, 1 row or nothing; an ELSE
that never fires; WHENs that never match; ELSE taking everything; nothing
matching with no ELSE (statement succeeds, writes nothing); empty source;
skew in the other direction (1 wide row vs 299,999 narrow rows); the same
table fed by a dominant clause and an empty one; an empty target still
enforcing its constraints later; small-scale replicas of every shape.

Object assertions (metadata_scan) are restricted to the deterministic
cases: the write mode is chosen at compile time from the planner estimate
(Outcnt x SingleLineSizeEstimate > DistributedThreshold), so only dominant
targets (objects for every row) and empty targets (no objects in either
mode) are checked. multi_insert_big.sql comments corrected accordingly
(its narrow 300k-row target is on the S3 path too) and the doc's test plan
describes the rule and the new file.
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

…ooks

- remap_db: the target's schema was remapped twice (remapDbInTableExpr on
  the table expr, then remapInsertTarget on the same SchemaName field);
  remapInsertTarget now only rewrites the qualified column names, as the
  table expr remap already handles the schema. Test covers targets,
  VALUES, WHEN conditions and the source query.
- compile2: rewriteAutoModeToPre / forceModePre now reach a MultiInsert's
  source query like Insert.Rows / Replace.Rows, so a vector search in
  auto mode inside INSERT ALL ... SELECT gets the pre-mode rebuild.

@fengttt fengttt left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Self-review of the multi-insert change (multi-angle sweep: correctness, control path, resource lifecycle, compatibility, failure modes, contract, performance; functional closure of parser → planner → compile → frontend → tests). Two fixes and several decision-log items; each inline thread says which.

Comment thread pkg/frontend/remap_db.go Resolved
Comment thread pkg/sql/compile/compile2.go Resolved
Comment thread pkg/sql/plan/bind_multi_insert.go Resolved
Comment thread pkg/sql/plan/bind_multi_insert.go Resolved
Comment thread pkg/sql/plan/bind_multi_insert.go Resolved
Comment thread pkg/sql/plan/bind_multi_insert.go Resolved
…atrixorigin#27560 review)

@iamlinjunhong's P2. The level-i selector projection rebuilt "did any earlier
selector match" from all i earlier selectors, so the routing bookkeeping was
O(W^2) in plan size and per-row work -- at the 127-clause cap, thousands of
prior-selector visits for every source row, contradicting the linear
clause-cost bound the cap was justified with.

INSERT FIRST now uses two projections per WHEN:

    level i-A:  sel_i     = if(matched, false, cond_i)
    level i-B:  matched   = matched OR istrue(sel_i)

The split is required because a projection cannot reference its own outputs:
matched_i needs sel_i, produced in the same projection, so it is accumulated in
the next one from materialized columns. Each level is now O(1) and the column
layout is stable (source, carriers, matched, selectors).

ELSE under FIRST also becomes one column test instead of one term per WHEN,
since the flag already answers "did anything claim this row". INSERT ALL is
unchanged: with no first-match rule there is no cumulative flag, and its ELSE
genuinely has to test every selector.

Semantics re-verified on a server build: volatile FIRST still partitions
exactly (1000 rows, 0 overlap), an unreachable erroring predicate is still
skipped, and three-way FIRST + ELSE routing is 300/300/400.

TestMultiInsertFirstSelectorChainIsLinear pins the property: doubling the WHEN
count must not more than triple the boolean bookkeeping, so a return to the
prefix rebuild fails the test rather than only showing up in a benchmark.

@aunjgr aunjgr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed exact head b33a62e01ee35cb3239cf6daab75deace1384177 against merge base ae12701a888fac102e9641cc7cbb8706527366d8.

I audited the complete parser → AST/remap/rewrite → planner → sink/branch/write-step → privilege/status/transaction closure, including the latest fixes. Each INSERT FIRST condition is now lazily masked per row and evaluated once, with a cumulative matched column that keeps routing linear; INSERT ALL selectors remain one evaluation shared by every target. Unmaskable later-WHEN and conditional-VALUES subqueries are rejected before flattening. Same-table clauses share one dedup/write pipeline, the auto-increment guard is conservative across prepare-time sql_mode changes, and multi-target LAST_INSERT_ID no longer assigns meaning to unrelated counters. Source/target privileges, irregular index maintenance, positional sink pruning, affected-row aggregation, cancellation/drain ownership, prepared rebuild, and atomic failure paths are closed. I found no blocking issue.

@XuPeng-SH XuPeng-SH 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.

Requesting changes on exact head 9a98ef9315bdb0e3d62a0637d24a8be84e218caa.

[P1 correctness] Restore the session-visible process value when suppressing an ambiguous multi-target insert id.

SetStatementLastInsertIDIfEarlier updates both StatementLastInsertID and LastInsertID (pkg/vm/process/types.go), but the new MultiInsert response path only declines to copy the statement value into the OK packet/session. It never restores proc.LastInsertID. doComQuery reuses that process for every statement in one COM_QUERY and resets only StatementLastInsertID before the next statement (mysql_cmd_executor.go:5567). Therefore the suppressed cross-table minimum leaks into the next statement in the same request.

I reproduced this deterministically with a focused frontend test: establish session/process LAST_INSERT_ID=51, simulate two target PRE_INSERT publications 101 and 1, run respStatus with two auto-increment PRE_INSERT nodes. The OK packet reports 0 and ses.GetLastInsertID() remains 51, but proc.GetLastInsertID() is 1. Thus INSERT ALL ...; SELECT LAST_INSERT_ID(); submitted as one multi-statement COM_QUERY returns the arbitrary suppressed value instead of 51. Separate-statement BVT calls hide the bug because a new process is initialized from the session on the next request.

Please keep the statement coordinator separate from session-visible state, or restore proc.LastInsertID from the session baseline on the ambiguous path before another statement can run. Add a frontend unit regression that checks all three states (OK packet, Session, Process) and a same-COM_QUERY control.

[P2 performance] The FIRST selector fix still builds and executes O(W^2) projection bookkeeping; the new test only counts boolean function nodes and misses it.

Both projection levels carry every prior selector (for j := 0; j < i at bind_multi_insert.go:443 and for j := 0; j <= i at line 462). Across W WHENs that is W^2 column expressions/executors. Projection.Prepare creates an executor per expression and Projection.Call / EvalProjection iterates every executor for every input batch, so these are not free plan-only references. My independent plan probe measured:

WHEN=8   PROJECT_exprs=129
WHEN=32  PROJECT_exprs=1281
WHEN=64  PROJECT_exprs=4609
WHEN=126 PROJECT_exprs=16885

The committed TestMultiInsertFirstSelectorChainIsLinear counts only or, istrue, and isnottrue, so it stays green while total projection work is quadratic. Please either make the full selector materialization linear or make the supported bound/performance contract honest and test total plan/executor work rather than a selected subset of function names.

[P2 documentation] The latest restrictions are not reflected consistently in the design document. The binding section still says subqueries in WHEN and VALUES are flattened, without documenting that later FIRST WHEN subqueries and every conditional VALUES subquery are now rejected. The same-table coverage row also still says the expression form is accepted under NO_AUTO_VALUE_ON_ZERO, while 06ce2900c3 deliberately rejects non-constant expressions in every mode. Please update the public limitations and coverage claims with the code change.

Validation: full pkg/sql/plan, pkg/sql/parsers/..., pkg/frontend, and pkg/sql/compile tests passed; focused multi-insert/parser/frontend/compile race tests passed 10x. The P1 probe fails only on the expected process-state assertion (expected 51, actual 1).

fengttt and others added 2 commits August 25, 2026 04:01
…origin#27560 review)

XuPeng-SH, three findings on 9a98ef9.

[P1] Suppressing the ambiguous multi-target insert id was not enough.
SetStatementLastInsertIDIfEarlier writes the session-visible LastInsertID
as well as the statement one, and doComQuery reuses the process for the
next statement of the same COM_QUERY while resetting only the statement
value. The suppressed cross-table minimum therefore answered the next
statement's LAST_INSERT_ID(). The ambiguous path now puts the session's
value back on the process. Reproduced exactly as reported --
session/process 51, publications 101 and 1, OK packet 0 and session 51
but process 1 -- and the new frontend test asserts all three states plus
the same-COM_QUERY control (it fails without the fix with expected 51,
actual 1).

[P2 perf] The FIRST selector chain was quadratic and the test hid it.
Carrying one boolean selector per WHEN made each level re-project all the
earlier ones -- W^2 expressions, and W^2 executors built by
Projection.Prepare and run by Projection.Call for every batch. INSERT
FIRST now carries a single int32 route column holding the index of the
WHEN that claimed the row (-1 for none):

    route_i = if(route_{i-1} >= 0, route_{i-1}, if(cond_i, i, -1))

one projection per WHEN instead of two, and a branch filters on
`route = i` rather than a boolean, so ELSE is `route = -1`. Laziness is
unchanged and now rests on nesting: EvalIff evaluates a false branch only
on the rows whose condition was false and passes that selection to the
child executor, which a nested if propagates -- so cond_i still runs only
on rows an earlier WHEN did not claim. Measured total plan work is now
215 expressions for 8 WHENs and 815 for 32, 25 per added WHEN, against
129 and 1281 before. INSERT ALL is unchanged: a row may match several
WHENs, so it keeps one selector per WHEN in a single projection.

TestMultiInsertFirstSelectorChainIsLinear counted only or/istrue/isnottrue
and stayed green while the real work was quadratic. It is replaced by
TestMultiInsertFirstRoutingWorkIsLinear, which counts every expression
node in every ProjectList and FilterList and asserts both the growth
ratio and a bounded per-WHEN cost.

[P2 docs] The design doc now documents the route column, that a subquery
is rejected in a later FIRST WHEN and in the VALUES of any conditional
clause (flattening would run it for rows the branch never receives), and
that a non-constant expression in a merged clause's auto_increment column
is rejected in every sql_mode, not accepted under NO_AUTO_VALUE_ON_ZERO.

Multi-insert BVT: 518/518 statements green across all five files.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
@fengttt

fengttt commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

All three fixed in f4739ebe21 (head 70780642b6 after merging upstream/main). Thank you — the P1 was real and the P2 test criticism was exactly right.

[P1] Process state restored. You were right that declining to copy the value was not enough: SetStatementLastInsertIDIfEarlier writes LastInsertID too, and doComQuery resets only StatementLastInsertID, so the suppressed cross-table minimum answered the next statement of the same COM_QUERY. The ambiguous path now restores the process from the session baseline:

} else {
    execCtx.proc.SetLastInsertID(ses.GetLastInsertID())
}

pkg/frontend/multi_insert_last_insert_id_test.go reproduces your case verbatim — session/process 51, publications 101 then 1 — and asserts all three states plus the same-COM_QUERY control (clear the statement value, then read the process). It fails without the fix with expected: 0x33, actual: 0x1, i.e. your expected 51 / actual 1. Two companion cases cover the single-auto-increment-target path (all three states reach 101) and the no-auto-increment path (everything keeps 51).

[P2 perf] The chain is now genuinely linear, and the test measures total work. You are right that the pass-through was the quadratic term and that my test measured a subset of function names, so it could not see it. INSERT FIRST no longer carries one boolean per WHEN. It carries a single int32 route column — the index of the WHEN that claimed the row, -1 for none:

level i:  route_i = if(route_{i-1} >= 0, route_{i-1}, if(cond_i, i, -1))

One projection per WHEN instead of two, one decision column instead of i of them, so nothing is re-projected. A branch filters on route = i, and ELSE on route = -1, instead of a boolean column and isnottrue.

Laziness is preserved and now rests on the nesting: EvalIff evaluates its false branch only on the rows whose condition was false and passes that selection into the child executor (evalExpression.go:970-985), and a nested if propagates it (trueBranch[i] = selectList[i]). So cond_i still runs only on rows an earlier WHEN did not claim — your and aptend's counterexamples still hold.

Measured total plan work, counting every expression node in every ProjectList and FilterList:

WHENs before after
8 129 (your probe) 215
32 1281 (your probe) 815

25 expressions per added WHEN, flat, versus 48 and rising. TestMultiInsertFirstSelectorChainIsLinear is replaced by TestMultiInsertFirstRoutingWorkIsLinear, which counts all expression nodes and all projections and asserts both the growth ratio and a bounded per-WHEN cost — your measurements of the old design trip both bounds.

INSERT ALL is deliberately unchanged: a row may match several WHENs at once, so there is no single route; its selectors are already one projection and therefore already linear.

[P2 docs] Updated. The Routing section now describes the two shapes separately (route column for FIRST, per-WHEN selectors for ALL) with the laziness and linearity arguments. The binding section documents that a subquery is rejected in a later FIRST WHEN and in the VALUES of any conditional clause, with the reason — flattening turns it into a join that runs for every row regardless of routing. The same-table coverage row now says a non-constant expression in a merged clause's auto_increment column is rejected in every sql_mode, matching 06ce2900c3, instead of claiming it is accepted under NO_AUTO_VALUE_ON_ZERO.

Validation. pkg/sql/plan, pkg/frontend, pkg/sql/compile, pkg/sql/parsers/... all pass (the one failure, TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp, reproduces on a clean origin/main worktree — timezone-dependent, unrelated). Focused -race -count=20 on the three changed behaviours passed. Multi-insert BVT: 518/518 statements green across all five files, which is the real check that the route rewrite preserved routing semantics.

@XuPeng-SH XuPeng-SH 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.

Requesting changes on a3a519c.

The previous blockers are fixed in this head: ambiguous multi-target insert IDs no longer leak process state, INSERT FIRST routing is linear and preserves lazy WHEN evaluation, and the focused/full normal plus race suites pass.

[P1] Branch subqueries lose statement-level binding metadata. The source bind stores stmt.Source.RewriteOption in srcCtx.remapOption, but appendMultiInsertSelectors creates condCtx with NewBindContext(builder, nil), and bindMultiInsertBranchSource creates bCtx the same way; both copy only the snapshot. Consequently, supported subqueries in WHEN predicates and VALUES expressions are extra read sides that bypass statement rewrite policy, and they also cannot resolve statement-level CTEs.

I reproduced both paths with temporary checked planner tests:

  1. Configure an inline rewrite from tpch.nation to SELECT r_regionkey FROM tpch.region. A WHEN EXISTS subquery and an unconditional VALUES scalar subquery that still reference n_nationkey both plan successfully. If rewrite reached those reads, planning must fail because the rewritten relation has no n_nationkey.
  2. A WITH vip AS (...) INSERT ALL statement whose WHEN subquery reads vip fails with table vip does not exist.

Please propagate the statement declaration context needed by selector and VALUES subqueries, including CTE/rewrite/remap/snapshot metadata as appropriate, without accidentally inheriting the SELECT source row bindings. Add checked regressions for both WHEN and unconditional VALUES subqueries under rewrite policy, plus statement-level CTE references from those two locations.

Validation on this exact head:

  • existing MultiInsert tests: PASS
  • focused race/stress, count=20: PASS
  • full related plan/frontend/compile/parser packages: PASS
  • full related packages with -race: PASS
  • the two temporary rewrite and CTE counterexamples: FAIL as described

Lifecycle Q1-Q3 review found no additional confirmed blocker: sink edges remain bounded, same-table UNION stays on the eager path, and failure cancellation/drain uses the existing ownership paths. The requested change is for functional and read-policy closure.

fengttt and others added 2 commits August 25, 2026 05:53
…origin#27560 review)

XuPeng-SH, P1 on a3a519c: a subquery in a WHEN condition or in a
clause's VALUES is another read performed by this statement, but both were
bound in a fresh root context (NewBindContext(builder, nil) plus a
snapshot copy). Two things followed, both reproduced as described:

- Read-policy bypass. The source bind puts the statement's RewriteOption
  on srcCtx.remapOption; a fresh root has none, so a branch subquery read
  the base table directly even when the statement's rewrite policy had
  remapped it.
- Statement CTEs were unreachable: `WITH vip AS (...) INSERT ALL ... WHEN
  EXISTS (SELECT ... FROM vip)` failed with `table vip does not exist`.

Both now bind under newCTEDeclarationContext(builder, srcCtx), which
already exists for exactly this shape: it carries the declaration scope --
CTEs, rewrite/remap option, snapshot, view state -- and then detaches from
srcCtx, so the source block's own row bindings are NOT inherited and the
source columns remain reachable only through the alias the binder adds.
The write pipeline's context is deliberately left alone: a target is
written, not read, so it must not inherit a read rewrite.

Regressions cover both locations for both failures:
TestMultiInsertBranchSubqueriesObeyRewritePolicy drives the real
`/*+ {"rewrites": ...} */` hint path through AddRewriteHints, with a
no-rewrite control, and asserts planning now fails because the rewritten
relation lacks the column the subquery resolves;
TestMultiInsertBranchSubqueriesSeeStatementCTEs asserts a statement CTE
resolves from both places. All four subtests fail without the fix -- the
rewrite ones with "An error is expected but got nil", the CTE ones with
`table "vip" does not exist`.

Multi-insert BVT: 518/518 green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
@fengttt

fengttt commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in da662d9186 (head f5c29c6fa1 after merging upstream/main). Both paths were real, and the fix turned out to be a context that already exists for exactly this shape.

Cause. appendMultiInsertSelectors and bindMultiInsertBranchSource both built their context as NewBindContext(builder, nil) plus a snapshot copy. A fresh root has no remapOption and no cteByName, so a subquery in a WHEN or in a clause's VALUES — which is another read performed by this statement — was bound outside the statement's read policy and outside its WITH scope.

Fix. Both now bind under newCTEDeclarationContext(builder, srcCtx). That helper carries the declaration scope — CTEs, rewrite/remap option, snapshot, view state — and then sets parent = ctx.parent, detaching from srcCtx itself. So the statement's metadata propagates while the source block's row bindings do not: the source columns stay reachable only through the alias the binder adds explicitly, which is the constraint you asked for. The existing ambiguity and binding tests still pass, which is the check that nothing leaked in.

The write pipeline's context (tCtx) is deliberately left as a plain root: a target is written, not read, so it must not inherit a read rewrite.

Regressions, both locations for both failures:

  • TestMultiInsertBranchSubqueriesObeyRewritePolicy — drives the real /*+ {"rewrites": {"tpch.dept": "select 1 as x"}} */ hint through AddRewriteHints, exactly as production attaches it, for a WHEN EXISTS subquery and an unconditional VALUES scalar subquery. The source reads nation, which the rewrite does not touch, so only the branch subquery is under test; each case has a no-rewrite control that must plan. Under the rewrite, planning must now fail because the rewritten relation has no deptno.
  • TestMultiInsertBranchSubqueriesSeeStatementCTEs — WITH vip AS (...) referenced from both a WHEN subquery and an unconditional VALUES subquery.

All four subtests fail without the fix, with your symptoms: the rewrite pair as An error is expected but got nil (i.e. the bypass), the CTE pair as SQL parser error: table "vip" does not exist.

Validation on this head. pkg/sql/plan, pkg/frontend, pkg/sql/compile, pkg/sql/parsers/... pass — the single failure, TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp, reproduces on a clean origin/main worktree and is timezone-dependent, unrelated. Multi-insert BVT 518/518 green.

The design doc now records the binding scope and why the write pipeline is excluded.

@XuPeng-SH XuPeng-SH 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.

Requesting changes on f5c29c6.

[P1] Preserve the statement and source CTE scopes separately when the source SELECT has its own WITH.

The parser accepts a statement-level WITH before INSERT and a separate WITH on the trailing source SELECT. These are distinct lexical scopes: WHEN predicates and INTO VALUES subqueries may see the statement CTEs, while source-local CTEs must remain private to the source query.

The current implementation collapses those scopes:

  • bindMultiInsert moves stmt.With to stmt.Source.With only when Source.With is nil (pkg/sql/plan/bind_multi_insert.go:177-178). If the source already has a WITH, the statement CTE is never installed in srcCtx.
  • appendMultiInsertSelectors and bindMultiInsertBranchSource then derive their branch declaration contexts from srcCtx. This both loses the outer CTE and exposes the source-local CTE to syntactically preceding WHEN/VALUES expressions.

I reproduced all four directions with temporary planner tests:

  1. WHEN EXISTS referencing a statement-level outer_vip, with a separate source WITH, fails with table outer_vip does not exist.
  2. An unconditional VALUES scalar subquery referencing outer_vip fails the same way.
  3. WHEN EXISTS referencing source_only, declared only in the trailing source WITH, incorrectly plans successfully.
  4. An unconditional VALUES scalar subquery referencing source_only also incorrectly plans successfully.

This rejects valid SQL and accepts invalid SQL whose branch routing/value can be computed from the wrong namespace, so it is a data-correctness blocker.

Please model the declaration scopes independently: source binding should see the outer statement CTEs plus its own local CTEs; WHEN/VALUES branch contexts should see the statement CTEs and statement rewrite/remap/snapshot metadata, but neither source-local CTEs nor source row bindings. Add checked regressions for both WHEN and unconditional VALUES in both directions.

The previous blocker is fixed for the simple no-source-WITH case: the added rewrite-policy and statement-CTE tests pass, as do the routing, same-table merge, auto-increment, sink-pruning, and irregular-index regressions.

Validation on this exact head:

  • all affected Go packages: PASS
  • go vet on all affected Go packages: PASS
  • focused MultiInsert race suite, count=10: PASS
  • four temporary dual-scope counterexamples: FAIL as described

Lifecycle Q1-Q3 review found no additional confirmed blocker: sink fan-out remains bounded, synthesized same-table UNION stays on the eager path, and failure cancellation/drain follows the existing ownership paths.

fengttt and others added 2 commits August 25, 2026 07:16
…review)

XuPeng-SH, P1 on f5c29c6. A statement-level WITH and a WITH on the
trailing source SELECT are different lexical scopes and can both appear;
the code collapsed them two ways at once:

- bindMultiInsert moved stmt.With into stmt.Source.With only when the
  source had no WITH of its own, so with both present the statement CTE
  was never installed anywhere. `WITH outer AS (...) INSERT ALL WHEN
  EXISTS (... outer ...) ... WITH local AS (...) SELECT ...` failed with
  `table "outer_vip" does not exist` -- valid SQL rejected.
- the branch contexts were derived from the source context, so a CTE the
  source declared privately, after the WHEN/VALUES that reference it, was
  visible to them -- invalid SQL accepted, with routing and values
  computed from the wrong namespace.

The scopes are now modelled independently. The statement's CTEs are
installed on the statement bind context via preprocessCte, so the source
(its child) sees them and a source-local WITH stays on the source context
alone. The statement's rewrite option -- which AddRewriteHints attaches to
the source query but which governs every read the statement performs -- is
lifted to the statement context too, and WHEN/VALUES bind under a
declaration context built from that: statement CTEs plus statement
rewrite/remap/snapshot, and neither source-local CTEs nor source row
bindings.

TestMultiInsertBranchSubqueriesSeeStatementScopeOnly covers both
directions for both locations. All four subtests fail without the fix,
with the reported symptoms: `table "outer_vip" does not exist` for the two
that must plan, `An error is expected but got nil` for the two that must
be rejected.

Multi-insert BVT: 518/518 green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
@fengttt

fengttt commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in 9ddcae1793. You are right that my previous fix traded one scope error for another — deriving the branch contexts from the source made the source's private CTEs visible to expressions that lexically precede them, and the stmt.Source.With == nil guard silently dropped the statement's own WITH whenever the source had one.

The two scopes are now modelled independently.

  • The statement's CTEs are installed on the statement bind context (preprocessCte(&tree.Select{With: stmt.With}, bindCtx)) instead of being pushed into stmt.Source.With. The source query is a child of that context, so it still sees them; a source-local WITH is installed by bindSelect on the source context alone and stays private there.
  • The statement's rewrite option is lifted to the statement context. AddRewriteHints attaches it to the source query, but it governs every read the statement performs, so the statement scope is where it belongs.
  • WHEN and clause VALUES bind under newCTEDeclarationContext(builder, bindCtx): statement CTEs plus statement rewrite/remap/snapshot, and neither source-local CTEs nor source row bindings. The source columns remain reachable only through the alias the binder adds explicitly.

The write pipeline's context is still a plain root — a target is written, not read.

TestMultiInsertBranchSubqueriesSeeStatementScopeOnly covers all four directions you listed, both locations × both scopes, with the source declaring its own WITH so the collapse is actually exercised. Without the fix all four fail with your symptoms:

WHEN sees the statement CTE alongside a source WITH          → table "outer_vip" does not exist
unconditional VALUES sees the statement CTE alongside …      → table "outer_vip" does not exist
WHEN must not see a source-local CTE                         → An error is expected but got nil
unconditional VALUES must not see a source-local CTE         → An error is expected but got nil

Worth noting for anyone reproducing: the first two only fail if the source's WITH is at the top level of the source SELECT. My initial draft wrapped it in a derived table, which leaves stmt.Source.With == nil and so still took the old move-it-across path and passed — I rewrote the cases to use a true source-level WITH.

Validation on this head. pkg/sql/plan, pkg/sql/compile, pkg/frontend, pkg/sql/parsers/... pass; the sole failure, TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp, reproduces on a clean origin/main worktree (timezone-dependent, unrelated). Multi-insert BVT 518/518 green. The design doc now shows the two scopes and what each is allowed to see.

@XuPeng-SH XuPeng-SH 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.

Requesting changes on exact head 7cf290fbee1e05a9b7c6d1cff59994e94f787320.

The previous statement-vs-source CTE visibility blocker is fixed: outer CTEs remain visible to WHEN/VALUES and the source, while source-local CTEs no longer leak into branch scopes. One P1 read-policy closure gap remains.

[P1 correctness/policy] Install the statement rewrite policy before snapshotting statement CTE declaration contexts.

In bindMultiInsert, preprocessCte(..., bindCtx) runs at lines 191-194, and only afterwards is stmt.Source.RewriteOption assigned to bindCtx.remapOption at lines 199-200. preprocessCte immediately creates each CTERef.declarationCtx through newCTEDeclarationContext; that context copies remapOption and then detaches from bindCtx. The later assignment therefore reaches the source and branch contexts, but never the already-created statement CTE contexts.

I reproduced the bypass with a temporary checked planner test:

/*+ {"rewrites": {"tpch.dept": "select 1 as x"}} */
WITH d AS (SELECT deptno FROM dept)
INSERT ALL INTO t2 (a, b) VALUES (deptno, 2)
SELECT deptno FROM d;

The no-hint control plans. Under the rewrite, every read of tpch.dept should resolve to a relation that has only x, so the CTE body must fail on deptno. This head instead plans successfully: the statement CTE reads the unrewritten base table. The new direct WHEN/VALUES rewrite tests stay green because those declaration contexts are created after the assignment, so they do not cover this path.

Please lift the rewrite/remap option onto bindCtx before preprocessCte snapshots any declaration context (or explicitly propagate the complete policy into every CTE declaration context). Add a regression for a statement CTE body, ideally covering both a table rewrite and database remap, including the case where the trailing source has its own WITH.

Validation on this exact head:

  • full pkg/sql/plan, pkg/sql/parsers/..., pkg/frontend, and pkg/sql/compile: PASS
  • focused multi-insert/parser/frontend/compile -race -count=5: PASS
  • temporary statement-CTE rewrite counterexample: FAIL as described; removed after verification

The broader correctness/performance/unhappy-path recheck found no additional confirmed blocker: FIRST routing remains linear and lazy, same-table grouping and privilege extraction remain closed, and sink cancellation/backpressure follows the existing bounded ownership paths.

fengttt and others added 2 commits August 25, 2026 08:40
…rixorigin#27560 review)

XuPeng-SH, P1 on 7cf290f. preprocessCte creates a declaration context
per statement CTE through newCTEDeclarationContext, and that context
copies remapOption and then detaches from bindCtx. Assigning the
statement's rewrite policy after preprocessCte therefore reached the
source and the branch contexts but never the CTE bodies, so

  /*+ {"rewrites": {"tpch.dept": "select 1 as x"}} */
  WITH d AS (SELECT deptno FROM dept)
  INSERT ALL INTO t2 (a, b) VALUES (deptno, 2) SELECT deptno FROM d

planned successfully: the CTE read the unrewritten base table. The
existing WHEN/VALUES rewrite tests could not see it, since those contexts
are built after the assignment.

The assignment now precedes preprocessCte.

TestMultiInsertStatementCTEObeysRewritePolicy covers a statement CTE body
under a table rewrite, with and without the trailing source declaring its
own WITH, each with a no-policy control; both fail without the fix with
"An error is expected but got nil". The requested remapdb direction is not
asserted: the planner mock's Resolve ignores the database name and stamps
back whatever was requested, so a database remap has no observable effect
under it -- both policies travel on the same remapOption, which is what
the ordering governs.

Multi-insert BVT: 518/518 green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
@fengttt

fengttt commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in 9f4854b27d (head a9d7f1bb8f after merging upstream/main). Good catch on the ordering — the policy was reaching everything except the contexts that were snapshotted before it existed.

Fix. bindCtx.remapOption = stmt.Source.RewriteOption now runs before preprocessCte, so every CTERef.declarationCtx that newCTEDeclarationContext snapshots already carries the policy. The comment at the call site records why the order matters, since the two statements otherwise look independent.

Regression. TestMultiInsertStatementCTEObeysRewritePolicy plans your statement through the real AddRewriteHints path, with a no-policy control for each case:

  • a statement CTE body under {"rewrites": {"tpch.dept": "select 1 as x"}}
  • the same with the trailing source declaring its own WITH, so the fix is exercised in the dual-scope shape too

Both fail without the fix with An error is expected but got nil, and pass with it.

One direction I did not assert, and why. I could not make remapdb observable in the planner mock: MockCompilerContext.Resolve ignores the database argument entirely and stamps whatever was requested back onto the returned TableDef, so the remapped statement plans identically with and without the hint (I probed it — the scan comes back db=tpch either way). A subtest there would assert nothing. Both policies ride on the same remapOption field, which is exactly what this ordering governs, so the table-rewrite cases cover the mechanism; if you would rather see remapdb pinned down, it needs either a mock that validates database names or a BVT case, and I am happy to add whichever you prefer.

Validation on this head. pkg/sql/plan, pkg/sql/compile, pkg/frontend, pkg/sql/parsers/... pass — the sole failure, TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp, reproduces on a clean origin/main worktree (timezone-dependent, unrelated). Multi-insert BVT 518/518 green. The design doc now states the ordering constraint.

@XuPeng-SH XuPeng-SH 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.

Requesting changes on exact head a9d7f1bb8ffbcda5c0839559df1c27abf191795c.

The previous correctness/read-policy blockers are fixed in this head. The source-once + per-physical-table write-pipeline design is sound, same-table clauses converge before one dedup/MULTI_UPDATE, and the focused routing/frontend/parser plus sink lifecycle race suites pass. One performance/design blocker remains.

[P2 performance] INSERT FIRST routing is still quadratic for a wide source; the committed linearity test only exercises one source column.

carriedPrefix at bind_multi_insert.go:426-438 re-emits every source column and every distinct condition carrier at each of the W projection levels. Therefore total projection work is O(W * (M + C)), where M is the source width and C is the number of distinct columns read by WHEN conditions. A normal shape with W conditions reading W different source outputs has M/C proportional to W, so the optimized plan and runtime executor work are still O(W²). This is not plan-only bookkeeping: Projection.Prepare creates one executor per ProjectList entry and Projection.Call evaluates every executor for every input batch.

I reproduced it with a temporary checked planner probe using the same total-expression walk as TestMultiInsertFirstRoutingWorkIsLinear, but generating WHEN c0 = 0 ... WHEN cN = 0 over SELECT 0 AS c0, ... N AS cN:

WHENs   total exprs   PROJECT nodes   max PROJECT width
8       199           19              9
16      459           35              17
32      1171          67              33
64      3363          131             65
126     10524         255             127

The current regression at bind_multi_insert_test.go:583-640 always binds every condition and every target value to the single deptno column. It proves only the fixed-width special case and therefore stays green while the documented per-WHEN bounded-work contract is false.

Please build the lazy first-match route in a bounded number of projections—for example, normalize the final child/carriers once and emit one nested if(cond_0, 0, if(cond_1, 1, ... -1)) route expression, relying on the same recursive EvalIff selection propagation—or an equivalent O(M + C + W) shape. Add a regression where added WHENs also introduce distinct source columns and count the complete optimized plan work.

Unhappy-path/lifecycle recheck found no additional blocker: sink edges are bounded, the synthesized same-table UNION remains eager on this plan shape, and failure cancellation/release follows the existing paths. Focused affected-package and sink/merge race tests passed repeatedly.

fengttt and others added 2 commits August 25, 2026 11:49
…ixorigin#27560 review)

XuPeng-SH, P2 on a9d7f1b. The route column removed one quadratic term
but not the other: carriedPrefix re-emitted every source column and every
condition carrier at each of the W levels, so the cost was O(W * (M + C)).
For the ordinary shape where W conditions read W different source columns,
M and C grow with W and the plan is quadratic again. My linearity test
bound every condition to the single deptno column, so M and C were
constant and it could not see this.

The chain is gone. The whole decision is one nested expression in one
projection above the conditions' own node:

    route = if(cond_0, 0, if(cond_1, 1, ... if(cond_{W-1}, W-1, -1)))

Laziness is unchanged and still rests on EvalIff: it evaluates a false
branch only on the rows whose condition was false and passes that
selection to the child executor, which the next nested if propagates. Each
cond_i therefore runs once and only on rows no earlier WHEN claimed.
Verified end to end on a live server -- a later WHEN of
cast('bad' as signed) does not error when an earlier WHEN claims every
row, and does error when a row reaches it, which is aptend's original
counterexample.

Nothing needs carrying between levels any more, so the carrier machinery
(collectMultiInsertCarriers, rewriteMultiInsertColRefs) is deleted.

Measured with a generator where each added WHEN also adds a source column
it reads, counting every expression node in every ProjectList and
FilterList:

    WHENs    chained    one projection
    8          272         146
    32        2204         530
    126          -        2034

16 expressions per added WHEN, flat. TestMultiInsertFirstRoutingWorkIsLinear
now uses that widening generator and asserts total expressions, projection
count and widest projection; it fails on the chained implementation with
"2204 is not less than 1632". TestMultiInsertFirstMasksLaterConditions now
asserts the nested chain's shape and first-match order directly.

Multi-insert BVT: 518/518 green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
@fengttt

fengttt commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in d2c376c91b (head 1e57b5acc8 after merging upstream/main). You were right on both halves: the route column removed one quadratic term and left the other, and my test could not see it because every condition bound to the same single column, so M and C never grew.

The chain is gone. The whole decision is now one nested expression in one projection above the conditions' own node — the shape you suggested:

route = if(cond_0, 0, if(cond_1, 1, ... if(cond_{W-1}, W-1, -1)))

Nothing has to be carried between levels, so collectMultiInsertCarriers and rewriteMultiInsertColRefs are deleted with the chain.

Laziness is unchanged and still rests on EvalIff: it evaluates a false branch only on the rows whose condition was false and passes that selection into the child executor, which the next nested if propagates. I checked it end to end on a live server rather than trusting the plan shape — with a later WHEN cast('bad' as signed) = 1:

  • when an earlier WHEN claims every row, all 3 rows land in the first target and nothing errors;
  • when no row is claimed earlier, it errors with invalid argument cast to int, bad value bad — aptend's original counterexample, still reproducing.

Measured with your generator shape (each added WHEN also adds a source column it reads; total expression nodes across every ProjectList and FilterList):

WHENs chained one projection
8 272 146
32 2204 530
64 — 1042
126 — 2034

16 expressions per added WHEN, flat. (My absolute numbers differ slightly from your probe's because the generated SQL isn't identical; the growth is the point, and mine reproduce the same quadratic on the old code.)

The test now measures what the contract claims. TestMultiInsertFirstRoutingWorkIsLinear uses the widening generator and asserts three things over the complete optimized plan: total expression nodes, projection count, and widest projection — that last one is what pins "the routing lives in one projection" rather than growing a column per WHEN. Against the chained implementation it fails with "2204" is not less than "1632". TestMultiInsertFirstMasksLaterConditions now walks the nested chain directly and asserts its first-match order and that no OR chain is rebuilt.

Validation on this head. pkg/sql/plan, pkg/sql/compile, pkg/frontend, pkg/sql/parsers/... pass — the sole failure, TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp, reproduces on a clean origin/main worktree (timezone-dependent, unrelated). Multi-insert BVT 518/518 green. The design doc now records both corrections, including why the first one looked linear and wasn't.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/feature size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants