Skip to content

fix(insert): exclude fake primary key from LAST_INSERT_ID (#29903) [4.2-dev] - #30005

Merged
XuPeng-SH merged 7 commits into
matrixorigin:4.2-devfrom
cpegeric:bug_29903_4.2
Oct 16, 2026
Merged

XuPeng-SH merged 7 commits into
matrixorigin:4.2-devfrom
cpegeric:bug_29903_4.2

Conversation

@cpegeric

@cpegeric cpegeric commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #29903

What this PR does / why we need it:

Backport of #29903 to 4.2-dev (companion to #30004 on main).

A FULLTEXT index carries a hidden auto_increment fake primary key (__mo_fake_pk_col) on its index table. When an INSERT into the base table synchronously populates the index, the index table's PRE_INSERT generates that fake key and the preinsert operator published it into the session LAST_INSERT_ID, so LAST_INSERT_ID() returned a hidden index value instead of the base table's business key. On 4.2-dev the publish is unconditional (SetLastInsertID), so the index value simply overwrites the base key.

Fix. Port of the minimal core of main's design (main's own #29903 commit is a 12-line change that relies on three earlier main PRs not on 4.2-dev: #27315, #28528, #29669). Names and shape follow main so later backports apply cleanly.

  • Hidden-key ownership (pkg/incrservice): AutoColumn.isInternal marks the allocator-owned hidden fake primary key, from the table definition on create and from a hidden-column check against mo_columns on load. A user-visible column that happens to be named __mo_fake_pk_col still publishes. InsertValues reports the first generated value of a non-internal column.
  • Reset after DELETE-to-truncate: Reset reads allocator offsets from the old table but ownership from the replacement (autoColumnPolicyTableKey), since the truncate has already deleted the old table's mo_columns rows.
  • Statement insert id (Base.StatementLastInsertID): the OK-packet insert_id reports only the value the statement generated; LastInsertID keeps the session value for LAST_INSERT_ID(). Cleared before each statement, and on a compile retry, which also restores the LAST_INSERT_ID the statement started with. PRE_INSERT publishes only a generated (non-zero) value, so a hidden index table never clobbers the base table's value.
  • Parallel publication: the parallel PRE_INSERT scopes of one statement share the process state. They publish through SetStatementLastInsertIDIfLater, which writes StatementLastInsertID and LastInsertID together under one mutex and keeps the largest value since the per-statement reset, so the OK packet and the next statement's LAST_INSERT_ID() agree. On 4.2-dev the allocator reports each batch's last generated value, so the largest value is the statement's last generated id, the value a serial scope already reported.

Tests.

  • Client level: TestIssue29903InsertIDOkPacket (embedded cluster, database/sql): OK-packet insert_id and LAST_INSERT_ID() for an explicit id after a generated one, a fulltext-indexed table, and DELETE-to-truncate then explicit insert. TestIssue29903RetryKeepsEarlierStatementLastInsertID: another session holds an uncommitted delete of row 100, so the explicit-id insert into t2 values (100, …) of a multi-statement COM_QUERY waits on the row lock and is retried after the holder commits. The OK packets are [1, 0], and select last_insert_id() later in the same COM_QUERY returns the earlier statement's id (with the old restore it returns the value at the start of the COM_QUERY).
  • Unit: TestInsertValuesExcludesInternalFakePKFromLastInsertID, TestInsertValuesReportsFirstGeneratedUserColumn, TestResetResolvesFakePKOwnershipFromReplacementTable, TestSQLStoreGetColumnsMarksInternalFakePK, TestSQLStoreGetColumnsOwnershipFromReplacementTable, TestRetryRestoresStatementStartLastInsertID, TestSetStatementLastInsertIDIfLater, TestParallelScopesPublishOneLastInsertID (-race). The client, reset and retry regressions each fail with their fix reverted.
  • End to end: a 2M-row INSERT ... SELECT (parallel PRE_INSERT) followed by SELECT LAST_INSERT_ID() in one COM_QUERY returns max(id) for both the OK packet and the function, over three runs.
  • BVT: auto_increment/auto_increment.result expects 10 (the generated user value) where it expected the hidden key 12; auto_increment/last_insert_id_hidden_pk (adds the truncate-reset case), fulltext/fulltext_last_insert_id, and the auto_increment suite at 100%.

Out of scope.

🤖 Generated with Claude Code

@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 →

@XuPeng-SH

XuPeng-SH commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: d9f6c22da1f9b041010eb523dc9d840ad17e60c9

Assessment: request_changes

Reviewed all four changed files and their allocation/publication callers. The FULLTEXT overwrite is addressed, but the claimed exclusion of hidden primary keys remains incomplete for mixed-column tables.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-7dea-77c2-a565-38d45b5564e4 · slot 0 · generation 0

  • P2 pkg/sql/colexec/preinsert/preinsert.go:516: Create a table with a user AUTO_INCREMENT UNIQUE column and no explicit primary key; insert an explicit user value of 1000, then insert a row with that column omitted.
    Impact: The new guard accepts this table, but LAST_INSERT_ID() still receives its hidden primary key rather than the generated user ID. Applications retrieving the inserted row receive the wrong identifier. This is a preexisting variant left unresolved by the claimed exclusion, not a newly introduced allocator regression.
    Evidence: build_ddl.go appends the hidden auto-increment key after user columns. GetAutoColumnFromDef retains both, and table_cache.go:139-156 overwrites its return value for each column, leaving the hidden value. Lines 516-517 publish that scalar unchanged. For the supplied single-CN counterexample, the source path predicts user ID 1001 but LAST_INSERT_ID() 2. Existing auto_increment.result:27-38 also records hidden-sequence publication for this supported schema. The added mixed-column test checks only eligibility, not value ownership. Select the user column's generated value while retaining hidden-key allocation, and add an allocator-to-publication regression.

Validation:

  • Verified the exact HEAD, clean source checkout, frozen patch contents and passing git diff --check.

  • Traced DDL column ordering, allocator creation/reload, allocation, preinsert error/retry paths, operator lifecycle, session publication and the LAST_INSERT_ID builtin.

  • Reviewed all supplied comments; none contains a substantive unresolved review concern.

  • Reused frozen-head successful build, Ubuntu UT, coverage, arm64 static-analysis and PROXY/pessimistic BVT statuses. The author also reports 20/20 targeted BVT checks.

  • Saved the source-derived counterexample in attempt-1/mixed_auto_repro.sql and review evidence in attempt-1/review-audit.json.

  • The added scan is allocation-free and linear in table columns per auto-increment batch; no benchmark was performed.

Limitations:

  • The counterexample was not executed against a running database. Repository build/test prerequisites were inspected; native libraries are absent, so no local native tests were run.

  • Detailed CI logs and the linked issue body were not supplied; issue behavior was assessed from the frozen PR description and regression cases.

  • The explicitly excluded, preexisting multi-row first-versus-last-generated-ID behavior is not a finding.

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

mo-bot review · mo-bot-local · review

Commit: d9f6c22da1f9b041010eb523dc9d840ad17e60c9

Assessment: request_changes

Reviewed all four changed files and their allocation/publication callers. The FULLTEXT overwrite is addressed, but the claimed exclusion of hidden primary keys remains incomplete for mixed-column tables.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-7dea-77c2-a565-38d45b5564e4 · slot 0 · generation 0

  • P2 pkg/sql/colexec/preinsert/preinsert.go:516: Create a table with a user AUTO_INCREMENT UNIQUE column and no explicit primary key; insert an explicit user value of 1000, then insert a row with that column omitted.
    Impact: The new guard accepts this table, but LAST_INSERT_ID() still receives its hidden primary key rather than the generated user ID. Applications retrieving the inserted row receive the wrong identifier. This is a preexisting variant left unresolved by the claimed exclusion, not a newly introduced allocator regression.
    Evidence: build_ddl.go appends the hidden auto-increment key after user columns. GetAutoColumnFromDef retains both, and table_cache.go:139-156 overwrites its return value for each column, leaving the hidden value. Lines 516-517 publish that scalar unchanged. For the supplied single-CN counterexample, the source path predicts user ID 1001 but LAST_INSERT_ID() 2. Existing auto_increment.result:27-38 also records hidden-sequence publication for this supported schema. The added mixed-column test checks only eligibility, not value ownership. Select the user column's generated value while retaining hidden-key allocation, and add an allocator-to-publication regression.

Validation:

  • Verified the exact HEAD, clean source checkout, frozen patch contents and passing git diff --check.

  • Traced DDL column ordering, allocator creation/reload, allocation, preinsert error/retry paths, operator lifecycle, session publication and the LAST_INSERT_ID builtin.

  • Reviewed all supplied comments; none contains a substantive unresolved review concern.

  • Reused frozen-head successful build, Ubuntu UT, coverage, arm64 static-analysis and PROXY/pessimistic BVT statuses. The author also reports 20/20 targeted BVT checks.

  • Saved the source-derived counterexample in attempt-1/mixed_auto_repro.sql and review evidence in attempt-1/review-audit.json.

  • The added scan is allocation-free and linear in table columns per auto-increment batch; no benchmark was performed.

Limitations:

  • The counterexample was not executed against a running database. Repository build/test prerequisites were inspected; native libraries are absent, so no local native tests were run.

  • Detailed CI logs and the linked issue body were not supplied; issue behavior was assessed from the frozen PR description and regression cases.

  • The explicitly excluded, preexisting multi-row first-versus-last-generated-ID behavior is not a finding.

…INSERT_ID (matrixorigin#29903)

A table with no user primary key -- the hidden fulltext/vector index tables
among them -- gets an allocator-owned hidden __mo_fake_pk_col. Its generated
value must never surface through LAST_INSERT_ID; the reported id must be the
base table's user-visible auto_increment key.

The fix uses column-visibility ownership, not a column name:

- incrservice marks a column internal only when it is the hidden fake primary
  key in the table definition (AutoColumn.isInternal, set in
  getAutoColumnsFromDef and, on the catalog reload path, from an att_is_hidden
  subquery in GetColumns). A user-visible column that happens to be named
  __mo_fake_pk_col is NOT internal.
- insertAutoValues keeps only the first generated value of a user-visible
  column as the statement result; an internal-only table returns 0.
- preinsert publishes LAST_INSERT_ID only for a non-zero value, so a table
  that generated only the hidden key never clobbers the base key.

Covers the two review cases: a visible column named __mo_fake_pk_col still
surfaces, and a mixed table whose user auto column was given an explicit value
(only the hidden key generates) publishes nothing.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

fixed

@XuPeng-SH

XuPeng-SH commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 8bfc6b98e1d44adabfd94d20551ac199e95ddf6c

Review completed. Read the assessment.

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

mo-bot review · mo-bot-local · review

Commit: 8bfc6b98e1d44adabfd94d20551ac199e95ddf6c

Assessment: request_changes

Reviewed the complete 20-file delta and supplied review concerns. Allocator ownership, replacement-table metadata and retry restoration address the earlier defects. Separating statement and session IDs is appropriate, but their publication is not coherent under parallel execution. An existing SQL test also retains an obsolete expected result.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-8e48-7622-ad17-b605f08450ce · slot 1 · generation 0

  • P2 pkg/sql/colexec/preinsert/preinsert.go:519: Execute a parallel INSERT ... SELECT followed by SELECT LAST_INSERT_ID() within the same multi-statement COM_QUERY.
    Impact: Concurrent workers can leave LastInsertID and StatementLastInsertID holding different generated values. The INSERT response and persisted session use the latter, while the following statement reads the former. Publish the generated value through one authoritative state or a coherent transition, and cover parallel statement reuse.
    Evidence: The interleaving A.Last(x), B.Last(y), B.Statement(y), A.Statement(x) leaves divergent fields. A diagnostic calling the unchanged production genAutoIncrCol with shared child-process Base and stubbed allocator outputs reproduced session=2 versus statement=3 after all workers completed (publication-probe.log; receipt 1792005451979530790-2.json). A real one-CN, million-row INSERT confirmed four parallel PRE_INSERT pipelines (parallel-plan-large-probe.log; receipt 1792005626886994122-2.json). status_stmt.go:347 publishes StatementLastInsertID; the SQL builtin reads LastInsertID, which is not reconciled between statements.

  • P2 test/distributed/cases/auto_increment/auto_increment.result:37: Run the existing auto_increment02 sequence: generate ID 10, attempt duplicate explicit ID 10, insert explicit ID 100, then query LAST_INSERT_ID().
    Impact: The corrected implementation returns 10, but the existing golden still expects the hidden sequence value 12. Update this expectation and validate the existing case alongside the new regressions.
    Evidence: The exact SQL sequence executed through a real client returned 10 in legacy-probe.log (receipt 1792005383267067644-2.json). The frozen result file still contains 12 at line 37. optools/run_bvt_group.sh includes this directory in BVT group 0.

Validation:

  • Verified clean frozen HEAD, complete patch modulo its terminal newline, git diff --check, 170 native inputs and 147 native artifacts. Receipt: 1792005703500826579-2.json; log: source-reconciliation-v2.log.

  • Passed the supplied isolation preflight and built native prerequisites through repository Makefiles using assigned caches. Provenance is retained in native-inputs.json, native-artifacts.json and validation-env.sh.

  • Passed the full pkg/incrservice suite, TestIssue29903InsertIDOkPacket and TestRetryRestoresStatementStartLastInsertID. Corresponding receipts: 1792005127585211396-2.json, 1792005352214292571-2.json and 1792005376510725824-2.json.

  • Additional client checks passed for multi-statement clearing and prepared explicit INSERTs. The publication counterexample failed as described; the production parallel-plan check passed.

  • Commands, source fingerprints, exits, logs and diagnostic-only failures are reconciled in /home/xupeng/.local/state/mo-bot/jobs/e1175238d45cfd6bc834a115/attempt-1/review-audit.json. Frozen green CI statuses do not override the reproduced findings.

Limitations:

  • The publication mismatch was reproduced at production-function level with allocator outputs stubbed. Real SQL established parallel reachability; an end-to-end packet mismatch was not observed.

  • No full local BVT or race-instrumented suite was run. Detailed CI logs, linked issue body and retained author validation artifacts were not supplied.

  • Added costs are a process ID field, atomic publication and a catalog lookup on allocator load/reset; no quantitative performance benchmark was run.

  • Existing multi-row first-versus-last semantics, REPLACE/LOAD DATA response behavior and remote-CN ID propagation remain outside this fix.

…lel scopes (matrixorigin#29903)

Review of the backport (mo-bot, two P2):

- Parallel PRE_INSERT scopes of one statement share the process state and
  wrote LastInsertID and StatementLastInsertID as two independent stores, so
  an interleaving left the OK packet / session value and the LAST_INSERT_ID()
  seen by the next statement of the same COM_QUERY different. PRE_INSERT now
  publishes through SetStatementLastInsertIDIfLater, which writes both fields
  under one mutex and keeps the largest value since the per-statement reset.
  On 4.2 the allocator reports each batch's last generated value, so the
  largest value is the statement's last generated id, the value a serial
  scope already reported.
- auto_increment.result expected 12 (the hidden fake primary key) after the
  auto_increment02 sequence; the generated user value is 10.

Tests: TestSetStatementLastInsertIDIfLater, TestParallelScopesPublishOneLastInsertID
(-race). A 2M-row INSERT ... SELECT followed by SELECT LAST_INSERT_ID() in one
COM_QUERY returns max(id) for both the OK packet and the function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

fixed.

…T_ID through the frontend (matrixorigin#29903)

A real lock conflict makes the explicit-id INSERT of a multi-statement
COM_QUERY retry. Asserts the OK packets [id, 0] and the same-request
LAST_INSERT_ID(); the latter fails with the COM_QUERY-start restore.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

added test

…xorigin#29903 retry test fails

Roll back the holder right after BEGIN unless it committed, cancel and
drain the writer, and bound the DROP DATABASE cleanup with its own
timeout, so a failed assertion does not block teardown.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

fixed

@XuPeng-SH

XuPeng-SH commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 03f2cfa27ccfad0aee374866a26cb6f201406a08

Review completed. Read the assessment.

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

mo-bot review · mo-bot-local · review

Commit: 03f2cfa27ccfad0aee374866a26cb6f201406a08

Assessment: approve

Reviewed the complete 23-file delta and supplied concerns. Metadata-based key ownership, statement-scoped reporting, coherent parallel publication and retry restoration form a reasonable design within the existing owners. Earlier findings are resolved; no actionable defects remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1

Validation:

  • Verified clean frozen HEAD, complete patch and git diff --check. Reconciled commands, source fingerprints, exits and retained logs in /home/xupeng/.local/state/mo-bot/jobs/f4246595952e7677b620ce15/attempt-1/review-audit.json; audit receipt 1792096942904908675-3.json.

  • Isolation preflight passed. Verified 170 native inputs and 147 retained artifacts against current sources and successful repository build receipts.

  • Passed the full incrservice suite, full process suite under race detection, and 100 repetitions of each new publication test under race detection.

  • Passed both Issue29903 client tests and the focused compile retry test, including forced retry within a multi-statement query.

  • Additional client checks passed for cold metadata reload, visible fake-key names, hidden-only inserts, prepared statements, truncate and fulltext indexing.

  • A million-row parallel INSERT reported 1000000 consistently in its OK packet, the following statement within the same COM_QUERY and stored maximum ID.

  • The initial diagnostic assumed reload preserved unused prefetched IDs. Its corrected oracle compares returned and stored IDs; both diagnostic versions and outcomes are retained.

Limitations:

  • Full local BVT was not rerun. Frozen CI reports successful unit, coverage, static-analysis and BVT checks; detailed CI logs and the linked issue body were not supplied.

  • Existing 4.2 multi-row semantics, remote-CN ID propagation and REPLACE/LOAD DATA response behavior remain explicitly outside this fix.

  • No comparative performance benchmark was run. Added costs are fixed process state, publication locking per generated batch and metadata work on allocator load/reset.

This branch was previously deployed

1 inactive deployment
ci — ea4692e2 Deployed Oct 16, 2026 by XuPeng-SH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants