Repository navigation
fix(auto-increment): honor session and ordered insert semantics - #28349
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
No prior human reviews, inline review comments, or issue comments exist on this PR (only a paused qodo bot notice), so there is nothing to reconcile, withdraw, or deduplicate.
I verified the design against MySQL 8 sources and the surrounding code and could not break it:
- The ordered INSERT IGNORE arbiter reproduces MySQL accepted-row ordering. The candidate stream is FIFO (an accepted generated row appends its own candidate then pops the oldest), retained candidates come only from rows rejected by a secondary unique key, and
discardThrough/lowerBoundplus theblockedcheck inpopAutoIncrementCandidateprevent duplicate primary keys across batches and after explicit keys. Negative explicit keys take part in dedup without advancing the sequence, matching the(1,-1,2)contract documented in MySQLhandler::update_auto_increment. - Plan wiring is self-consistent:
visibleWidthequalslen(preInsert.Attrs)built at pkg/sql/compile/operator.go:863, PRE_INSERT appends the provenance vector at exactly that physical index (compPk/clusterBy/old-update are all excluded by the guard),AutoIncrementKeyIndex = 0is the real PK becauseappendInsertIgnoreMultiDeduppushes the PK key first, andmarkerSelectPos == baseWidth-1is hard-validated.insertIgnoreAutoIncrementReorderablecorrectly excludes fake/composite keys, generated-column, CHECK, FK and unique-index dependencies, and skipped unique keys. ranges.nextFor/nextValueInRangesolve the residue congruence correctly (period = lcm(step, increment)) with overflow-safe modular arithmetic.allocateLockedWithOptionssetscol.allocatingonly after every early return, so no allocating state leaks.applyAutoValuesholdscol.Lock()for the whole row loop, so the 8-allocation guard cannot be starved by a concurrent session on the same CN. MORPCVersion56 gating only tightens the remote path when provenance or non-default session options are actually present; default-session remote inserts still need only v26.NormalizeAutoIncrementOptionsclampingoffset > incrementto 1 is MySQL-correct:compute_next_insert_idtakes theauto_increment_increment == 1shortcut and never reads the offset (sql/handler.cc:3763), and InnoDB applies the offset only underif (increment > 1 && ...)inha_innobase::get_auto_increment.
That last point is what makes the single blocking finding unavoidable rather than a taste issue: the new behavior is right, but git diff origin/main...HEAD -- test/ is empty while three checked-in BVT expectations still assert the removed DDL-time offset behavior, so the change set is incomplete and the Standalone BVT regression will diff on merge. I swept the whole BVT suite for the reorder-enabled shape (auto_increment single-column real PK plus an active secondary unique key); only test/distributed/cases/dml/returning/returning.sql:6 qualifies, and its single INSERT IGNORE row is accepted, so no other golden file is affected by the reorder path.
One non-blocking inconsistency remains: the ALTER TABLE COPY add-column path still bakes the session offset into the durable table allocator, so CREATE and ALTER now disagree and #28239 is only partly closed.
P0 - Session auto_increment_offset fix leaves three stale BVT expectations that now diff (test/distributed/cases/auto_increment/auto_increment.result:680)
git diff origin/main...HEAD -- test/ is empty, but this PR changes what set auto_increment_offset = N; create table ...(col int auto_increment); insert; select returns.
Prior behavior: buildCreateTable called getAutoIncrementOffsetFromVariables and stored offset - 1 in TableDef.AutoIncrOffset. That flows into AutoColumn.Offset (pkg/incrservice/types.go:290) and is persisted as the offset column of mo_increment_columns (pkg/incrservice/store_sql.go:42). With auto_increment_offset = 10 the allocator row was created with offset 9, so the first generated value was 10.
New behavior: this PR deletes that call and the helper from pkg/sql/plan/build_ddl.go, so AutoIncrOffset stays 0 and the allocator row is created with offset 0. The session value is instead consumed at DML time in pkg/sql/colexec/preinsert/preinsert.go:601 through NormalizeAutoIncrementOptions(1, 10), which clamps the offset to 1 because offset > increment (pkg/incrservice/types.go:56). The generated value is therefore 1.
That result is correct: MySQL's compute_next_insert_id takes the auto_increment_increment == 1 shortcut and never reads auto_increment_offset (sql/handler.cc:3763), and InnoDB applies the offset only under if (increment > 1 && ...) in ha_innobase::get_auto_increment. It also matches #28239, whose t_cross example expects a default session to get id 1 from a table created under offset 2 / increment 3. So the fix should stay; the recorded expectations must be regenerated.
Three expectations still assert the old values and will diff:
- line 680:
set auto_increment_offset = 10thencreate table auto_increment17(col1 int auto_increment)records10, now1. - line 686:
create table auto_increment17(col1 int auto_increment) auto_increment = 0in the same session records10, now1(auto_increment = 0takes theopt.Value != 0branch at pkg/sql/plan/build_ddl.go:2381 and leaves the offset unset). - line 693:
set auto_increment_offset = 100records100, now1.
These are the only golden expectations in the repo tied to the removed DDL behavior: rg -l auto_increment_offset test/ returns only this case plus test/distributed/cases/system_variable/system_variables.sql, which just does set/show variables and creates no AUTO_INCREMENT table afterwards.
Required change: regenerate test/distributed/cases/auto_increment/auto_increment.result for those three cases, and fix the neighbouring comment in test/distributed/cases/auto_increment/auto_increment.sql:441, which labels the block -- system variable: auto_increment_increment while it exercises the offset. While regenerating, add the end-to-end cases the PR body only validated by hand — session series 3/2 producing 2,5,8, ordered INSERT IGNORE reuse after a secondary-unique rejection, and REPLACE publishing LAST_INSERT_ID(). The new Go unit tests are good but do not cover the frontend wiring this PR adds (refreshStatementScopedSessionInfo per statement, resolvePositiveSessionUint64, and the new case *tree.Replace in pkg/frontend/status_stmt.go:393), and the repo convention for MySQL-compatibility fixes is a checked-in BVT case (see the existing annotated cases in this same file).
P2 - ALTER TABLE COPY add-column path still persists the session offset, contradicting the new CREATE semantics (pkg/sql/compile/alter.go:1787)
This PR removes session-offset persistence from CREATE TABLE but leaves the equivalent logic in the ALTER COPY path. pkg/sql/compile/alter.go:1787 resolves auto_increment_offset from the outer compile's process and, for a newly added AUTO_INCREMENT column with no copied rows, sets copiedMax = offset - 1, which becomes effectiveOffset at pkg/sql/compile/alter.go:1816 and is durably written to mo_increment_columns via svc.SetOffset. The comment there states the branch exists to reapply the session offset because the temporary CREATE no longer inherits it — i.e. it was written specifically to preserve the CREATE TABLE behavior this PR deletes.
Consequence: after this PR the two DDL paths disagree. set auto_increment_offset = 10; create table t(id int auto_increment primary key); insert now yields 1, while set auto_increment_offset = 10; create table t(v int); alter table t add column id bigint auto_increment, algorithm = copy; insert still yields 10 and pins every later session to that offset (test/distributed/cases/auto_increment/auto_increment.result:750 records 1 10). That residual cross-session leak is exactly what #28239 asks to remove ("a table created under one session must not force that session's offset on other sessions"), so the issue is only partly closed even though the PR says Closes #28239.
Why this is not blocking: alter.go is untouched by this PR, no existing expectation regresses because of it, and the statement-scoped session-series and ordered INSERT IGNORE semantics introduced here are unaffected — the ALTER path only seeds the allocator's durable high-water, which the new DML logic then reads as an ordinary starting point. Either drop the session-offset reapply in alter.go and regenerate that single expectation so CREATE and ALTER agree, or state explicitly in the PR description that ALTER COPY is deliberately out of scope for #28239 and track it separately, so the two paths are not left silently inconsistent.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Module-level deep review — changes needed before merge
Reviewed head: a669b5819c04d2f1273b188de6219336e910da07
PR base and merge-base: 0b195e4f5a23c06a40552a8db3e7fdf182979a3a (main).
This review covers the allocator, statement/session state, ordered IGNORE arbitration, synchronous index consumers, protocol boundaries, and cleanup—not only the latest index-maintenance delta. I found one new merge-blocking resource defect, one measured optimization opportunity, and an independently reproduced pre-existing semantic gap. The older approval was for a different head.
This is a COMMENT, not an approval: the authenticated account is the PR author and cannot submit a self-approval or self-request-changes review.
1. [P1, introduced by this PR] Account and bound the retained final-PK set
In preinsertunique.go:393–396, acceptedAutoIncrementValues is an ordinary Go map. Every accepted generated or explicit PK is retained until statement cleanup. The ordered branch stops inserting this PK into the existing accounted acceptedIters, so the new representation removes the capacity check for this growing state. INSERT IGNORE also does not activate the ODKU allocation-account lifecycle.
A concrete reachable shape is:
CREATE TABLE source_rows(uk INT, v INT);
INSERT INTO source_rows SELECT NULL, result FROM generate_series(1,20000) g;
CREATE TABLE target_rows(id BIGINT AUTO_INCREMENT PRIMARY KEY, uk INT UNIQUE, v INT);
INSERT IGNORE INTO target_rows(uk,v) SELECT uk,v FROM source_rows;The source UK is a column, not a statically skipped NULL literal. The planner enables ordered arbitration; all NULL secondary keys are valid and need no growing secondary-key set. I verified the nullable-column plan and ran the 20,000-row SQL case successfully.
At the production arbitration owner, a 1 MiB mpool with 512 batches of 1,024 distinct generated PKs accepted 524,288 keys. The map's key payload alone is at least 4,194,304 bytes, excluding map overhead, while mp.CurrNB() remained 65,536 bytes from the first batch to the last. An otherwise equivalent non-reordering control hit the existing capacity error after 8,192 accepted rows. Both probes also ran under -race.
This is an input-sized, unaccounted accumulation that can push a CN into process OOM instead of the normal query-capacity error. It is not a claim of a post-statement leak: Reset/Free do drop the map, and I did not deliberately exhaust the host.
Fix: retain final PK identity in an accounted/budgeted set, charging capacity before growth and releasing it on all terminal paths. Reusing the established hash owner is possible only if it stores final keys, not the original candidates. Add multi-batch nullable-UK tests that hit the budget, return an error, clean up, and successfully reuse the operator for a following statement. Compressing rejected-candidate runs does not bound this accepted-key set.
2. [Measured optimization opportunity] Avoid per-accepted-row heap objects and duplicate PK construction
The all-accepted path still creates map[int]*autoIncrementCandidate per batch, allocates a candidate object for every generated row, copies the provisional PK through buf.Union, then allocates/rebuilds that PK column and frees the copied one (assignment, output construction).
I compared the ordered and legacy branches of the same production owner with identical 32,768-row, all-accepted input, 1,024 rows/batch, and both NULL and distinct secondary UKs:
| Branch | Go heap allocated / statement | Allocations / statement |
|---|---|---|
| Legacy, distinct UK | approximately 804 KB | 277 |
| Ordered, distinct UK | approximately 9.10 MB | 34,694 |
| Legacy, NULL UK | approximately 804 KB | 271–272 |
| Ordered, NULL UK | approximately 9.10 MB | 34,688 |
Three repeated measurements retained these allocation counts. These are Go heap allocations, not total/native memory. Wall times were noisy on this shared host and overlapped between branches; I am not claiming a proved throughput slowdown or extrapolating to TPCC. This item is not independently merge-blocking on timing evidence.
Recommendation: use a reusable bounded value buffer indexed by selected/input ordinal, return candidates by value, and build the final PK once. Benchmark all-accepted, duplicate-heavy, mixed explicit/generated, and multi-batch cases while preserving first-generated-ID and final-PK dedup semantics. The allocator requests/row benchmark in the PR does not measure this downstream cost.
3. [Pre-existing module defect, NOT a new regression] Eager allocation can fail before accepted-row arbitration
I ran the following on the exact base, this head, and an isolated MySQL 8.0.44 instance:
CREATE TABLE t(id TINYINT AUTO_INCREMENT PRIMARY KEY, uk INT UNIQUE, v INT);
INSERT INTO t(uk,v) VALUES(10,0);
INSERT IGNORE INTO t(id,uk,v)
VALUES(NULL,20,1),(127,10,2),(NULL,30,3);
SELECT id,uk,v FROM t ORDER BY v;- MySQL succeeds:
(1,10,0), (2,20,1), (3,30,3). - Both MatrixOne base and head fail with
Error 1690: data type tinyint, value 128; only the seed row remains.
With BIGINT and explicit 100 instead of 127, both MO revisions accept the rows but assign the last row 101, whereas MySQL assigns 3. This is not a demand for globally gapless allocation: a discarded explicit key changes a later accepted row inside the same statement, and the bounded type turns it into statement failure.
The closure is PRE_INSERT -> insertAutoValues -> applyAutoValues -> PRE_INSERT_UK. The allocator first scans the whole vector's explicit positives, advances its range/high watermark, and then calls skipped.updateTo on each explicit row before knowing whether that row survives. It also materializes/range-checks all provisional generated values before the arbiter runs. The arbiter cannot recover a lower candidate already discarded upstream, or repair an error returned before arbitration.
The same upstream owner has another existing boundary defect: on an empty BIGINT table, INSERT INTO t VALUES(-1,1),(NULL,2),(100,3),(NULL,4) gives MO IDs -1,101,100,102, versus MySQL -1,1,100,101. The explicit-negative callback casts -1 to uint64 before advancing the skipped-range cursor. The new arbiter's correct negative-key handling does not repair that upstream behavior. MySQL's statement-cursor restoration also explains why a rejected explicit row must be distinguished from table-wide reservation.
Systematic direction: separate globally owned, non-rollbackable reservations from the statement's accepted-row cursor. Final ID assignment/validation must have enough acceptance information to avoid a rejected explicit row advancing that cursor or causing premature exhaustion. Preserve conflict locking and the one-final-row-image contract; do not roll back the shared allocator, swallow overflow, or merely add more cases to the downstream candidate queue.
These defects are inherited and are not being mislabeled as PR regressions. If deferred from this PR, record these exact executable limitations and a follow-up explicitly; the current tests establish a useful subset of ordered semantics, not general closure of the module.
Design assessment and unhappy-path closure
The principal directions are sound:
- Statement-scoped increment/offset should select from disjoint table-owned ranges, not become persistent DDL state. Existing minimum-span amortization avoids per-small-write allocator I/O.
- Base rows, regular indexes, FULLTEXT/MASTER and IVF should consume the same accepted row image. Moving the existing sharing boundary is preferable to evaluating the source/allocator again. The current public test verifies hidden postings/entry identities as well as base rows.
- Sender/receiver protocol gating, explicit provenance metadata, and retaining the candidate type/lower bound across buffer exhaustion are appropriate.
- Dependent CHECK/FK/generated/index expressions remain a documented eligibility boundary. I did not flag an impossible generated-column-on-AUTO_INCREMENT counterexample: DDL already rejects that dependency.
| Audit | Result |
|---|---|
| Q1 ownership / cleanup | Followed PRE_INSERT and arbiter Prepare/Call/Reset/Free, cache retirement and statement state. No additional confirmed leak/double cleanup in the reviewed paths. |
| Q2 cancellation / waits | Followed column allocation callbacks, service generations and shared SINK fanout. No new reproducible deadlock found; current bounded race/reset and real multi-batch tests complete. This is not a universal no-hang guarantee. |
| Q3 retained growth | Fails for the new final-PK Go map. Candidate-run compression and SINK backpressure do not cover it. |
| Functional closure | Final index consumers now agree in the tested cases; eager pre-arbitration allocation still leaves the inherited counterexamples above. |
The recurring design risk is splitting one observable row decision across eager candidate allocation and later acceptance, then testing those owners separately. Similarly, measuring allocator requests or compressed rejected runs misses the accepted-row state and heap cost. Future regressions should cover the whole path from input/session through final base/index identity and error cleanup.
Executed verification
All on the reviewed head unless explicitly labeled base:
- Fresh Darwin/arm64 CGo build using the repository build/test wrapper; no CGO-disabled workaround.
- Full normal packages: incrservice, preinsert, preinsertunique, plan, process.
- Full race packages: incrservice, preinsert, preinsertunique.
TestColumnCacheConcurrentSessionSeries: race measurement T=0.03s; B=30s gives capped N=100. All 100 repetitions in one process passed.- Focused compile/frontend checks: remote AUTO_INCREMENT protocol, ALTER COPY reconciliation, statement-scoped session refresh.
TestIssue28349AutoIncrementPublicPaths: passed, including explicit CN0/CN1, synchronous indexes, prepared reuse, rollback/error controls, and 40,000 input / 20,000 accepted rows.- Focused dispatch/connector/materialized-SINK Reset race checks passed.
- Added diagnostic SQL probes on exact base and head, real MySQL control, nullable-source plan/public SQL, budget control, and repeated allocation microbenchmarks. Probe completion is not being described as semantic success for the mismatching SQL.
git diff --checkpassed.
I did not rerun full compose BVT, a retained-data restart matrix, mixed-binary-version topology, or TPCC; CI was not awaited. No production code was changed for this review.
| return vm.CancelResult, moerr.NewInvalidInput(proc.Ctx, "INSERT IGNORE auto-increment provenance is not boolean") | ||
| } | ||
| if preInsertUnique.ctr.acceptedAutoIncrementValues == nil { | ||
| preInsertUnique.ctr.acceptedAutoIncrementValues = make(map[uint64]struct{}) |
There was a problem hiding this comment.
[P1] Keep final accepted PKs in an accounted, bounded owner
The ordered branch replaces the accounted PK hash state with this Go map, which retains every accepted PK for the whole statement without a capacity check. A nullable source-column UK keeps this path enabled while all NULL secondary keys avoid growing the other key set.
At this production owner, a 1 MiB mpool accepted 512 x 1,024 distinct generated PKs: at least 4 MiB of key payload was retained while mp.CurrNB() stayed at 64 KiB. The equivalent legacy branch failed at the existing pool limit after 8,192 rows. Typed-plan and real 20,000-row SQL probes confirmed the nullable-column shape is reachable; the capacity probes also passed under -race.
Please account/bound final-key growth before insertion and release it through Reset/Free/error cleanup, with a budget-exhaustion plus following-statement regression. Reusing the old hash state is valid only if it records final assigned IDs rather than provisional candidates. The arithmetic-run optimization bounds rejected-candidate storage, not this accepted-key state. This is an OOM-budget bypass, not a post-statement leak claim.
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
Revalidated at the new head 04460a0. It is a merge-only commit: parents 0254156 (the head I just reviewed) and eb7912a (main), and git show --remerge-diff HEAD is empty, so there is no conflict-resolution delta and nothing in the incremental range is authored by this PR (upstream #28362 fileservice hidden paths, #28345 sequence NEXTVAL, morpc, geo/wkb, disttae, function/* all arrived through the merge and are not review findings).
Merge safety verified rather than assumed:
- New merge-base is eb7912a and the PR's authored file set (
git diff --name-only eb7912a2a8..HEAD) is identical to the set at 0254156, so no PR file was dropped or rewritten by the merge. - Four files are touched by both this PR and upstream: pkg/frontend/mysql_cmd_executor_test.go, pkg/sql/compile/compile.go, pkg/sql/plan/build_test.go, pkg/vm/process/types.go. Comparing
git diff 0b195e4f5a..0254156e80 -- <file>withgit diff eb7912a2a8..HEAD -- <file>shows the PR's own hunks are byte-identical modulo blob hashes and hunk line offsets. - The overlapping edits are semantically disjoint: the PR adds
SessionInfo.AutoIncrementIncrement/AutoIncrementOffset(pkg/vm/process/types.go:138) andsupportsRemoteAutoIncrementSessionOptions(pkg/sql/compile/compile.go:7345), while upstream addsBaseProcess.sequenceGateandsequenceExecType/validateSequenceScopePlacement. The new upstream validation returns nil unlessplan2.QueryContainsSequenceFunction(qry), and this PR introduces no sequence function, so it cannot reject the PR's INSERT IGNORE arbitration/SINK-sharing plans. Upstream's other plan-package edits (applyLockTableFallback/estimateFullTableUpdateRows, a QueryBuilder field, ReadDir) do not touch the arbitration or remap helpers this PR relies on. - Rebuilt at the new head with a real CGo build (donor thirdparties headers/libs): pkg/incrservice, pkg/sql/colexec/preinsertunique, pkg/sql/colexec/preinsert, pkg/sql/plan, pkg/sql/compile, pkg/vm/process, pkg/frontend all compile clean. Re-ran focused tests at the new head:
./pkg/incrservice/...ok,./pkg/sql/colexec/preinsertunique/...ok,./pkg/sql/plan/ -run 'Irregular|InsertIgnore|AutoIncrement|Ignore|Sink'ok. - PR discussion is unchanged since my last load (no new reviews, issue comments, or inline replies), so no disposition changes for discussion reasons.
Disposition of my own prior blockers (all closed, none re-opened by the merge):
- P0 "three stale BVT goldens" (CHANGES_REQUESTED @eeeaf39b): FIXED. test/distributed/cases/auto_increment/auto_increment.result encodes session-scoped first values, and the cases added afterwards are internally consistent and MySQL-8-plausible (signed manual sequence -1,1,100,101 with LAST_INSERT_ID()=1; ordered candidate reuse giving ids 1,2 with
force index(uk_ab)/force index(uk_c)resolving to the accepted base row; fulltext/master probes matching only accepted rows). - P2 "ALTER COPY persists the creator session offset": FIXED in pkg/sql/compile/alter.go, unchanged since.
- P2 non-blocking "test named after PR number": ADDRESSED by the alternative I offered — pkg/tests/issues/issue_28349_test.go:31 documents that the name refers to the PR and lists the covered issues #28237/#28238/#28239.
Other reviewer's items, recorded as disposition only and deliberately not re-raised as findings: XuPeng-SH's P1 "unaccounted retained final-PK Go map" (@a669b581; one unresolved, now-outdated inline thread) is fixed by 0254156 and independently verified by me — the PK identity set is a hashtable.Int64HashMap created in Prepare via InitWithAllocation(proc.Mp(), hashAllocation) (pkg/sql/colexec/preinsertunique/preinsertunique.go:100), so growth passes ResizeOnDemand → admission and off-heap MakeSlice, bounded by the account when attached and by mp.Cap()/GlobalCap() otherwise (pkg/common/mpool/mpool.go:1063 enforces capacity only for off-heap allocations, which these are). auto_increment_budget_test.go:31 asserts ErrMPoolCapacity on an input-sized final-key set plus Reset/Prepare reuse of the same keys and mp.CurrNB()==0; auto_increment_budget_test.go:82 asserts an incomplete output batch never escapes. His per-row allocation item is addressed (final PK built once in accepted-row order at preinsertunique.go:507, no per-batch candidate map, reusable off-heap output vectors, amortized run growth). His inherited eager-allocation defect is documented exactly as he requested at docs/design/20260908-auto-increment-boundaries.md:305 with repro, MySQL 8.0.44 control and follow-up direction; it is pre-existing, not a PR regression, and not a finding.
Correctness evidence I re-confirmed against the code at this head (carried over from the 0254156 pass, all in the unchanged PR surface):
autoIncrementKeyIdentity(xor-shift 33, odd multiply, xor-shift 33) is invertible mod 2^64, so hash equality is value equality with no false dedup positives; it maps only 0→0, and the separateacceptedAutoIncrementZeroflag is required becauseInsertBatch/FindBatchtreathashes[0]==0as "hash raw keys" and would dereference the nilkeysPtr(pkg/container/hashtable/int64_hash_map.go:189 and :407).group[0] <= beforedetects duplicate insertion sinceMapped == elemCnt.- No nil-map path exists: Prepare rejects reorder unless insertIgnore and
0 <= AutoIncrementKeyIndex < len(KeyColumns)(preinsertunique.go:76), allocates the map for that index, and both dedup loops skip that index for the intentionally-nilacceptedIters; every Prepare failure path callsfreeAcceptedState, which frees the map and the candidate runs. - Candidate stream:
discardThroughin-place filtering is alias-safe (write index ≤ read index, andrangecopies the element before the append);skip >= run.count-1equals the oldskip+1 >= countwithout the +1 overflow, withcount==0filtered first socount-1cannot underflow.compactAutoIncrementCandidatesno longer resets the stream, so the explicit-key fence and type contract survive exhaustion across batches.MakeSlice/FreeSlicepairing preserves the base pointer through every truncation and growth, so accounted bytes are released exactly once at Reset/Free. IsNullreplacingGetNulls().Contains(preinsertunique.go:445, :454) is a genuine fix:IsNullhonorsIsConstNullwhile a const-NULL vector's bitmap is empty, so folded NULL unique keys previously reachedFind/GetFixedAtNoTypeCheck.- Allocator: the
step == 1fast path in nextValueInRange is algebraically identical to the general solver (g=1, inverse(1)=1, k=rhs, period=increment) with increment ≥ 1 guaranteed;vs[i] > 0in insertAutoValues stops a negative explicit ID from discarding skipped ranges, matching MySQL; droppingoptions.isDefault()in allocateLocked still reserves ≥ rows residue values because allocationCount = rows*increment, so the 8-allocations-per-row guard cannot starve. - Planner:
AutoIncrementOutputColumn == AutoIncrementColumn(pkg/sql/plan/bind_insert.go:2412), so the in-loop final-PK write plus positional copy of the other columns preserves the pre-existing output contract (origin/main already producedbuf.Union(inputBat, sels)over the leadingOutputColumnsinput columns andExecProjectionis a passthrough); remapAllColRefsForConsumer remaps the output position and fails loudly if pruned (pkg/sql/plan/query_builder.go:3567) while Key/Conflict/AutoIncrement/Generated input positions are remapped through the child. Narrowing the early sharing branch toNode_FAILand adding post-arbitration IGNORE sharing (bind_insert.go:2829 and :3698) cannot lose a RETURNING materialization because INSERT IGNORE + RETURNING is rejected in validateReturningSyntax (pkg/sql/plan/returning.go:83) beforereturningRequestedis set.firstGeneratedbatch-min publication is equivalent to the previous per-candidate calls becauseSetStatementLastInsertIDIfEarlierdocuments and implements zero as a no-op (pkg/vm/process/types.go:786).
No blocking or non-blocking findings remain at head 04460a0.
Summary
Fix the three related AUTO_INCREMENT compatibility bugs tracked by #28239, #28238, and #28237:
auto_increment_increment/auto_increment_offsetwere accepted but not applied by DML allocation;INSERT IGNOREattached pre-arbitration AUTO_INCREMENT candidates to rows that were later discarded;REPLACEcould insert a new generated ID without publishing it throughLAST_INSERT_ID().Closes #28239
Closes #28238
Closes #28237
Latest follow-up: budget, correctness and allocation cost
Commit: 0254156e80.
Design, Q1–Q3 audit, benchmark details and open limitation.
Completed validation for this follow-up
SCA follow-up verification (2026-09-08)
The full local SCA gate completed successfully on
0254156e80d190a2b7036b99f101ff816629cb60, with exit status 0:CGO_ENABLED=1,GOWORK=off, and the verified worktree's native header/library paths. Local resource controls wereGOMAXPROCS=2andGOFLAGS=-p=2.molint, full license header and dependency checks, and all 12 analyzers selected by the unchanged.golangci.yml. This was not the cache-warming target or a changed-package-only scan.golangci-lint: 0 issues after the repository's existing filters, exit 0; elapsed 11m36.98s for that phase. No new exclusions, suppressions, disabled checks, or source edits were used to obtain this result.molintreturned 0 while emitting 58 non-fatal diagnostic entries, all outside the files changed by this PR. This records the actual gate outcome; it is not a claim that the entire repository is warning-free.GOENV=offto avoid the machine's persisted Go flags linking the tools themselves to an unrelatedlibmo.dylib; no global Go configuration or other MatrixOne instance was changed.This supersedes the earlier “full SCA not run” statements for this head. The linked design document and earlier revision-specific QA entries retain the evidence available when those revisions were published.
Still open: rejected positive explicit IDs can affect eager allocation
This inherited module defect is not fixed by this patch and must not be confused with the negative-ID correction:
The exact main base and reviewed head returned error 1690 (tinyint 128), while the MySQL 8.0.44 control accepted IDs 2 and 3. BIGINT/100 gives the last row ID 101 instead of 3. Eager allocation/range checking runs before knowing that the explicit row loses on UK.
The next change needs a statement acceptance cursor coordinated with globally owned reservations, PK/UK ownership, final-key checking/locking and the shared final row image. The design record lists the counterexamples and required concurrency/performance checks. Simply generating replacement IDs after dedup would bypass the existing PK probes/locks; rolling back a shared allocator or swallowing overflow is not an acceptable fix. This follow-up addresses the new memory blocker and independently verified corrections, not complete closure of every AUTO_INCREMENT semantic case.
Root cause
The allocator only consumed the table-owned unit-step range and had no statement-scoped session-series state. The DDL path also persisted the creating session's offset, making a session variable affect unrelated writers.
The ordered
INSERT IGNOREpath generated IDs before secondary-unique-key arbitration. Once an input row was ignored, its candidate stayed attached to the original input position, so a later accepted row received a positional gap. The previousREPLACEresponse path did not publish the generated value from its shared pre-insert pipeline.Design and implementation
Process.SessionInfoand the pipeline protocol. Non-default options reserve on demand using the larger of the checked required span and the existing configured unit-span minimum and select values matching the requested residue without mutating shared range metadata.COM_QUERY.INSERT IGNOREhandling to the safe shape: a real single-column AUTO_INCREMENT primary key plus an active secondary unique key, with dependent generated/check/foreign-key/index expressions left on the established path.PRE_INSERT_UKbatches, and rewrite the output key while preserving row order.LAST_INSERT_ID()only for generated values that survive arbitration; publish the generated value forREPLACEas well. Reset/free/error paths clear transient candidate state.Correctness and unhappy paths
The implementation validates session values, arithmetic/allocation overflow, malformed plan metadata, unsupported key types, and impossible allocation progress. Candidate storage uses arithmetic runs rather than one entry per rejected row, and the ordered optimization is bypassed when constraint/index dependencies make post-arbitration key rewriting unsafe.
The follow-up also fixes the signed-negative manual-ID cursor bug in ordinary INSERT. General acceptance-aware handling of rejected positive explicit IDs remains an inherited limitation, documented above; it is not claimed fixed.
Original-head validation
git diff --checkmake cgo && make build3/2produces2,5,8;INSERT IGNORE, including a high explicit key, preserve accepted-row ordering and the next generated key;__mo_auto_increment_generateddoes not collide with the internal provenance metadata;-1followed by a generated row produces-1,1, and the next generated value is2.CI was not awaited by design. The local macOS linker emitted only existing optional
libpqxxsearch-path/duplicate-rpath warnings. No cybersecurity request or path was modified.Review follow-up: design, correctness, performance
Design and validation record: AUTO_INCREMENT boundaries.
QA test plan and completed evidence
pkg/sql/plan,pkg/incrservice,pkg/sql/colexec/preinsertuniquepassed using.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=240s.-race;TestColumnCacheConcurrentSessionSeriesalso passed 100 repetitions in one race-detector process. Covers mixed concurrent writers, disjoint IDs, per-writer series, and vector cleanup.TestIssue28349AutoIncrementPublicPathspassed with real SQL and explicit CN0/CN1 endpoints: composite/prefix UK, CHECK, duplicates, base rows and indexed lookups, UPDATE, prepared reuse, creator/writer session isolation, REPLACE/LAST_INSERT_ID.system_variable/system_variables.sql177/177;auto_increment/auto_increment.sql473/473. Includes forced composite/prefix index lookups and post-case table cleanup assertions. Local BVT connections use CN0; the public Go test independently exercises CN1. Full compose CI was not rerun locally.-n -g -o -p <case> -s <resources>; run the public test with-run '^TestIssue28349AutoIncrementPublicPaths$' ./pkg/tests/issues.-run '^$' -bench '^BenchmarkColumnCacheStatementSeries$' -benchtime=300ms -count=3 ./pkg/incrservice. With a 10,000-value unit-span minimum, allocator requests/row changed from 1 to ~0.000306 for increment 3 and 1 to ~0.00655 for increment 64. Default increment remains ~0.000099. This is an allocator microbenchmark with an in-memory store, not a TPCC or production-latency claim.No full SCA or CI wait for this follow-up. No production debug logging or local-only harness is included in the commit.
Follow-up: one accepted row image for all synchronous indexes
Commit: a669b58.
The follow-up review reproduced a correctness regression, not just legal ID gaps: FULLTEXT/MASTER maintenance read pre-dedup rows and provisional PKs while the base table used accepted rows with final PKs. A rejected token could consequently match another accepted row.
QA test plan / completed evidence at a669b58
Using the repository CGo wrapper on darwin/arm64:
./pkg/sql/plan: passed (4.17s), including structural placement, connected SINK consumers, auxiliary-column pruning, and existing ordinary INSERT/ODKU/RETURNING tests.-run '^TestIssue28349AutoIncrementPublicPaths$' -count=1 -timeout=180s ./pkg/tests/issues: passed (13.77s package). Covers FULLTEXT + MASTER, composite UK/CHECK, raw postings, all-rejected/empty input, prepared rebind, rollback, failed INSERT, subsequent UPDATE/DELETE, manual and hidden-PK controls. IVF hidden-entry PKs and vector values match base rows.auto_increment.sql498/498 each;system_variables.sql177/177 each. Post-case table cleanup asserted; no golden regeneration.-race -run '^Test(DispatchReset|ConnectorReset|MaterializedSinkScanReset)' -count=1 -timeout=120sin dispatch, connector and merge: passed. These existing lifecycle tests cover terminal/full-channel error handling and reader cleanup.git diff --checkand formatting checks passed. Local-only probes/harnesses were removed; no production debug logs are included.Earlier allocator/arbiter race and microbenchmark results remain applicable because those implementations were not changed in this follow-up. CI/full SCA/TPCC were not awaited or rerun.