Skip to content

[Bug]: prepared INSERT SELECT corrupts base and stored generated-column values #29146

Closed

Description

@Ariznawlll

Description

A prepared INSERT ... SELECT that assigns a parameterized expression to a base column of a table with a stored generated column persists mutually inconsistent values. The base column is shifted or zeroed after the first row, while the stored generated column contains the value computed from the intended base input.

The same SQL executed directly is correct. The same prepared projection written to a table without a generated column is also correct. A CTE and Snowflake-style multi-table INSERT both reach the defect, but neither is required.

Environment

  • Branch: main
  • Commit: d8ddce92b1c5c172111b50aefe6b6b200b2589cb
  • Deployment: local 1 LogService / 1 TN / 2 CN; SQL ports 16001 and 16002

Steps to reproduce

CREATE DATABASE ps_gen_repro;
USE ps_gen_repro;

CREATE TABLE src(id INT PRIMARY KEY, v INT);
INSERT INTO src VALUES (1,10),(2,20),(3,30);

CREATE TABLE gen(
  id INT PRIMARY KEY,
  v INT,
  g INT AS (v + 1) STORED,
  INDEX iv(v)
);

PREPARE p FROM
  'INSERT INTO gen(id,v) SELECT id,v+? FROM src WHERE id<=?';
SET @delta=7,@cut=3;
EXECUTE p USING @delta,@cut;
DEALLOCATE PREPARE p;

SELECT id,v,g,v+1 AS recomputed FROM gen ORDER BY id;

Actual behavior

+----+------+------+------------+
| id | v    | g    | recomputed |
+----+------+------+------------+
|  1 |   17 |   18 |         18 |
|  2 |    0 |   28 |          1 |
|  3 |   27 |   38 |         28 |
+----+------+------+------------+

Rows 2 and 3 violate the declared invariant g = v + 1. The stored generated values 28 and 38 correspond to intended base values 27 and 37, but the persisted v values are 0 and 27.

The same corruption is visible when the source is wrapped in a CTE and when it feeds a prepared INSERT FIRST with two targets.

Expected behavior

The statement must persist:

(1,17,18), (2,27,28), (3,37,38)

Every stored generated value must be evaluated from the base value persisted in the same row.

Stability and controls

  • Reproducer: 6/6, alternating both CNs.
  • Direct non-prepared INSERT ... SELECT: correct in every run.
  • Prepared projection into a plain (id,v) table: correct in every run.
  • Removing the CTE does not remove the failure, proving this is the prepared generated-column write path rather than CTE evaluation.
  • The statement succeeds without an error, so applications can commit internally inconsistent stored rows.

Evidence

Local artifacts:

  • evidence/cte_prepared_multi_insert_generated_repro.py
  • evidence/cte_prepared_multi_insert_generated_repro.out

Representative output:

direct: consistent=((1, 17, 18), (2, 27, 28), (3, 37, 38))
prepared: inconsistent=((2, 0, 28), (3, 27, 38)) all=((1, 17, 18), (2, 0, 28), (3, 27, 38))
no_cte: inconsistent=((2, 0, 28), (3, 27, 38)) all=((1, 17, 18), (2, 0, 28), (3, 27, 38))
plain=((1, 17), (2, 27), (3, 37))

Code analysis

The problem is downstream of parsing and parameter binding because the same prepared source projection is correct for a plain target. The generated-column insert path is assembled by appendNodesForInsertStmt in pkg/sql/plan/bind_insert.go. It builds the base expressions and then inlines or stages generated expressions through inlineGeneratedColExpr / appendMaterializedExprProjections.

The evidence suggests that the generated expression is evaluated from the correct parameterized source value, while the base output vector written beside it is read with a shifted row position after the first row. The exact faulty projection/vector handoff still needs confirmation in the executor.

Regression coverage

After the fix, add a planner/executor regression covering prepared INSERT ... SELECT with:

  1. a parameter in the base-column expression;
  2. multiple source rows;
  3. a stored generated column depending on that base column;
  4. both CTE and non-CTE sources;
  5. ordinary and multi-table INSERT paths;
  6. a post-write assertion that the stored generated value equals recomputation from persisted base columns.

Related

Activity

  1. added this to the MO-202609 milestone on Sep 20, 2026
  2. added
    kind/bug
    on Sep 20, 2026
  3. added theissue type on Sep 20, 2026
  4. self-assigned this
    on Sep 20, 2026
  5. added a commit that references this issue on Sep 20, 2026
    b4da0fe
  6. slyunnn commented on Sep 23, 2026

    @slyunnn

    Regression and extended verification for #29146 (2026-09-23)

    Verification Environment

    • Verified against local origin/main at 66da3877e9e77f01083c4aac0cb9f94ab6e11fe6, feat(sql): support EXCEPT ALL multiset subtraction (#29228).
    • The running Proxy, CN1, CN2, TN, and Log service containers all used the same locally built image sha256:2f11e09a1d306d186281dd444b465d69ed9ebc674a548c6fabac2c85c714f104, built from that exact clean source worktree.
    • Topology: 1 Log service / 1 TN / 2 CN / 1 Proxy. Connectivity and real DDL/DML execution succeeded through Proxy 6001, CN1 16001, and CN2 16002.
    • The original server-side SQL PREPARE / EXECUTE path was exercised. The binary extension used Go database/sql with go-sql-driver/mysql, interpolateParams=false, and actual COM_STMT_PREPARE / COM_STMT_EXECUTE.
    • Related fix: 52224d6f3b12b31911db5f7b23cb92a5fd1b597b, fix: preserve prepared insert assignment type, merged by PR #29169, fix: preserve prepared INSERT SELECT assignment types. The fix retains the assignment cast when a same-type integer target expression depends on a prepared parameter, preserving the write vector's physical type.

    What Was Covered

    • OK — Original PREPARE p FROM 'INSERT INTO ... SELECT id, v + ? ...' / EXECUTE p USING scenario with a stored generated column and secondary index passed on Proxy 6001, CN1 16001, and CN2 16002; persisted rows were (1,17,18), (2,27,28), and (3,37,38), with g = v + 1 for every row.
    • OK — Binary prepared-statement coverage used database/sql + go-sql-driver/mysql with interpolateParams=false on all three endpoints; COM_STMT_PREPARE / COM_STMT_EXECUTE produced the same correct generated-column rows.
    • OK — Happy-path controls: direct INSERT ... SELECT into a generated-column table and binary prepared INSERT ... SELECT into a plain (id, v) target both returned the expected values.
    • OK — CTE compatibility: binary prepared WITH c AS (...) INSERT INTO ... SELECT ... into the generated-column target passed on Proxy, CN1, and CN2.
    • OK — Boundary coverage: a negative parameter with 2 source rows preserved (1,7,8) and (2,17,18); a 0-row predicate left the target empty.
    • OK — Unhappy-path coverage: a duplicate-key error from the binary prepared insert left the target unchanged, proving statement atomicity and generated-column consistency for the pre-existing row.
    • OK — The committed SQL BVT test/distributed/cases/prepare/issue_29146_generated_insert_select.sql was replayed twice through mo-tester via Proxy 6001; each run passed 22/22 statements with 0 failed, ignored, or abnormal results. It covers positive and negative parameters, generated-column recomputation, and ROLLBACK.
    • Not covered — The Snowflake-style multi-target INSERT FIRST variant was not directly rerun. The original single-target and CTE prepared write paths, which exercise the fixed assignment conversion boundary, were covered.
    • Not covered — NULL, overflow, and IGNORE parameter permutations were not added; they are outside the narrowly fixed same-type integer assignment contract and were also identified as residual scope in PR #29169.

    Findings

    The corruption is no longer reproducible. Prepared parameter specialization no longer causes the positional writer to consume a widened source vector as the target integer width: stored base values and stored generated values remain mutually consistent.

    The three endpoint protocol cases were run in parallel with separate databases (issue29146_cte_proxy, issue29146_cte_cn1, and issue29146_cte_cn2), so they had no shared catalog objects. The two mo-tester replays were intentionally serial because they exercise one self-cleaning BVT database and result comparison on the same instance.

    Large-data regression is not needed. The defect is a per-row prepared-assignment physical-type mismatch that stably reproduces with the minimum meaningful multi-row input (3 rows); it does not depend on row-count thresholds, block/batch boundaries, memory, spill, concurrency, skew, network transfer, or resource scale. Increasing the data volume would add CI cost without covering a new execution boundary.

    MOTR / BVT Coverage

    No MOTR branch, commit, or new test was needed: current main already contains the dedicated MatrixOne SQL BVT and product-side prepared generated-column integration regression added by PR #29169. The existing BVT was replayed twice successfully; no test source was modified during this verification.

    Final Conclusion

    Fixed. The original prepared INSERT ... SELECT stored-generated-column corruption and the covered binary prepared and CTE variants pass on Proxy 6001, CN1 16001, and CN2 16002 using the current main runtime. Large-data regression is not required for the reasons above. The multi-target INSERT FIRST and NULL/overflow/IGNORE permutations remain explicitly unverified rather than inferred.

  7. Ariznawlll commented on Sep 24, 2026

    @Ariznawlll
    CollaboratorAuthor

    测试版本

    • 分支:main
    • Commit:d7d940e93bd037e9aacdc0f1256b91e32df84642
    • 环境:本地 MatrixOne 单机

    原问题验证

    复测 prepared INSERT ... SELECT 写入包含 STORED generated column 和二级索引的目标表。参数化表达式分别使用正增量和负增量,写入后逐行比较 base column、stored generated value 与重新计算值。

    结果连续 3/3 通过:正增量得到 (1,17,18),(2,27,28),(3,37,38),负增量得到 (1,7,8),(2,17,18);generated value 均等于 v + 1,未再出现 base/generated 值损坏。

    正常场景覆盖

    • prepared INSERT SELECT + 参数化投影。
    • 多行写入、正负增量、目标表二级索引。
    • stored generated column 与表达式重算结果一致。

    异常与边界覆盖

    • 在显式事务中执行同一 prepared statement 后回滚,目标表行数恢复为 0。
    • 重复执行时先清空目标表,确认 prepared statement 可复用且结果稳定。

    白盒验证

    通过目标表中的 base value、stored generated value、重算值和一致性布尔值四列交叉校验,避免只检查行数导致错误数据漏检。

    回归测试

    测试证据

    • MOTR 结果:3/3 success,stmts=22 ok=22 fail=0(每轮)。
    • 事务回滚后 count(*) = 0。
    • 两组写入的 generated invariant 全部为 1。

    测试结论

    测试通过。

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

Metadata

Metadata

Assignees

Labels

kind/bug

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions