Skip to content

feat: support ALTER TABLE AUTO_INCREMENT - #26658

Merged
mergify[bot] merged 16 commits into
matrixorigin:mainfrom
VioletQwQ-0:codex/issue-23143-auto-increment-sql
Aug 7, 2026
Merged

mergify[bot] merged 16 commits into
matrixorigin:mainfrom
VioletQwQ-0:codex/issue-23143-auto-increment-sql

Conversation

@VioletQwQ-0

@VioletQwQ-0 VioletQwQ-0 commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

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

Which issue(s) this PR fixes:

issue #23143

What this PR does / why we need it:

Adds the final SQL planner/compiler entry point for ALTER TABLE ... AUTO_INCREMENT = N on top of the already merged transactional allocator reset, COPY/CLONE reconciliation, epoch fencing, and mixed-version capability gate.

Changes:

  • lowers the table option through a new additive plan action for INPLACE ALTER and through the copied table definition for COPY ALTER;
  • treats SQL value N as the next value and stores allocator offset N-1 without unsigned underflow;
  • reconciles the request with the committed table maximum and validates the effective offset against the AUTO_INCREMENT column type;
  • addresses allocator metadata by stable (table_id, col_index) identity so an INPLACE column rename cannot turn a later reset into a silent no-op;
  • locks and validates the target allocator metadata row, rejecting missing/duplicate/lost updates while accepting an unchanged no-op only after the locked pre-read proves the requested offset already exists;
  • fails closed before allocator mutation when the transaction's TN snapshot cannot enforce the epoch fence;
  • shares rollback/cancellation cleanup across INPLACE and COPY, and leaves catalog epoch assignment to disttae when the ALTER request is applied;
  • extends the canonical AUTO_INCREMENT BVT for INPLACE, below-MAX, quoted-identifier, COPY, and rename-reset-insert behavior.

Non-goals:

  • no new allocator, epoch, TN protocol, or recovery mechanism;
  • no relaxation of mixed-version fail-closed behavior;
  • no post-allocation relation-epoch refresh.

Validation:

  • GOWORK=off go list ./pkg/sql/plan ./pkg/sql/compile ./pkg/incrservice ./pkg/sql/colexec/table_clone ./pkg/vm/engine/disttae
  • GOWORK=off go build ./pkg/sql/plan ./pkg/sql/compile ./pkg/incrservice ./pkg/sql/colexec/table_clone ./pkg/vm/engine/disttae
  • GOWORK=off go vet ./pkg/sql/plan ./pkg/sql/compile ./pkg/incrservice ./pkg/sql/colexec/table_clone
  • GOWORK=off go test ./pkg/sql/plan ./pkg/sql/compile ./pkg/incrservice ./pkg/sql/colexec/table_clone ./pkg/vm/engine/disttae -count=1
  • go test ./pkg/incrservice ./pkg/sql/compile ./pkg/sql/colexec/table_clone ./pkg/vm/engine/test
  • GOWORK=off go test -race ./pkg/incrservice ./pkg/sql/compile -count=1
  • focused SQL-store tests for stable-index predicates, missing metadata, and zero-affected unchanged/lost-update branches
  • protobuf regeneration is clean with repository-pinned protoc 3.21.1 and gogofast 1.3.2
  • git diff --check
  • exact-head preflight: PASS review=PASS validation=PENDING on fe20c9ab2f8fc5fa2b59d9b6ae27835132230262
  • BVT: test/distributed/cases/auto_increment/auto_increment.sql, including RENAME COLUMN → reset → insert; current exact-head CI is pending
  • Prior head 00b4bf708599724afc48711e1b03fda9eda5141a: CI run 30844457239 passed both Proxy multi-CN job 91789323459 and Pessimistic standalone job 91789323542; this is historical evidence, not the current exact-head gate.
  • Base behavior: FAIL — the parser accepted the option, but planner/compiler did not produce or execute an allocator reset.
  • Current PR-head behavior: PASS in focused planner/compiler/incrservice/store/clone tests; required remote CI remains pending on exact head fe20c9ab2f8fc5fa2b59d9b6ae27835132230262.

QA required: yes — production SQL is covered by BVT, but the final restart, rolling-upgrade, old/new CN/TN, and multi-CN stale-cache acceptance matrix remains pending. The issue link must be changed to Fixes #23143 only after that closing gate is complete.

@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Aug 3, 2026
@mergify mergify Bot added the kind/feature label Aug 3, 2026
@VioletQwQ-0
VioletQwQ-0 marked this pull request as ready for review August 4, 2026 03:11
@VioletQwQ-0
VioletQwQ-0 requested a review from a user August 4, 2026 03:11
@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 →

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

Codex automated review

All prior blockers are fixed: stale allocator names and cache keys, combined rename/reset handling, CREATE and COPY epoch publication, CREATE AUTO_INCREMENT=0 sentinel preservation, and repeated owned-CREATE reset rollback/cache retirement. The latest repeated-reset explanation is consistent with the code and tests. One distinct COPY regression remains for newly added AUTO_INCREMENT columns.

P1 - [P1] Preserve the initial offset for newly added AUTO_INCREMENT columns (pkg/sql/plan/build_alter_table.go:133)

ALTER TABLE ... ADD COLUMN ... AUTO_INCREMENT is accepted by the planner and always uses COPY. This assignment clears the copied definition's offset, while the temporary CREATE still initializes a new auto column from the session auto_increment_offset. For a new column, mapCloneAutoIncrColumns has no source mapping, so on an empty source table copiedMax and sourceOffsets are zero; reconcileAlterCopyAutoIncrement then computes zero and force-resets the temporary allocator. For example, with auto_increment_offset=10, CREATE TABLE t(a INT), and ALTER TABLE t ADD COLUMN c INT AUTO_INCREMENT, the first insert into empty t starts c at 1 here, whereas the base implementation preserved offset 9 and started at 10. Preserve the correct fresh/session initialization for new columns without inheriting stale state from dropped or reused identities, and add a regression test.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed the fresh COPY-member initialization blocker in 5a32e6bf3bf6df21ff4074af52cdcc756aad1646.

Root cause: a newly added AUTO_INCREMENT member has no source mapping. For an empty source, COPY reconciliation interpreted the absent mapping plus MAX=0 as an ordinary reset and overwrote the temporary table's real CREATE/session initialization.

The fix now preserves that CREATE-owned allocator only for the exact tuple !explicitReset && newly-created/unmapped member && plan offset == 0 && copied MAX == 0. Retained members, fresh members with copied rows, and explicit resets still run SetOffset and publish the matching catalog epoch. If every member is preserved, reconciliation also avoids an empty AlterTable call.

Regression coverage:

  • exact empty fresh-member case; it failed before the patch on an unexpected SetOffset(..., 0) and now passes
  • fresh member with copied rows still advances to the copied maximum
  • retained + fresh members in the same replacement reconcile independently
  • explicit reset remains unchanged
  • production SQL BVT explicitly forces algorithm = copy, sets auto_increment_offset = 10, and asserts the first implicit INSERT receives 10

Validation on the exact pushed head:

  • focused compiler regressions: PASS
  • full go test ./pkg/sql/compile -count=1: PASS
  • related allocator rollback/retry/cancel regressions: PASS
  • git diff --check: PASS
  • schema-v6 semantic preflight: PASS (d29ea8bd4568bbca58fb5e5e4598d74b75755d02f39136b2fc9be8a663bc795e)

The distributed BVT was authored but not executed locally; the new exact-head CI run is in progress.

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

Codex automated review

All prior blockers—stable column identity, rename/cache consistency, transaction and COPY epoch fencing, CREATE=0, repeated-reset rollback, and fresh-column initialization—are fixed. No independent blocking or non-blocking finding remains.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed the old-head Proxy BVT failures and the main conflict on exact head 0c3c71255e252a31c009da3cd937e819fc004ff1.

  • Rebasing onto upstream/main@09e02eea38bfa87e4c4333ffb57b370091136bc8 resolved the generated plan.pb.go conflict; GitHub now reports the PR mergeable.
  • COPY ALTER no longer assumes the internal temporary CREATE inherited the client session. For an empty, newly added AUTO_INCREMENT column with no explicit reset, the outer compile lazily resolves auto_increment_offset, explicitly publishes SetOffset(9) for session value 10, and publishes the matching catalog epoch.
  • The mixed retained/new-column regression asserts ordered allocator updates (50, then 9) and two matching catalog epoch requests.
  • The clone BVT now asserts the stable SQL invariant (the generated value is greater than copied MAX(a)=1000) instead of assuming one allocator reservation width; Proxy multi-CN legitimately returned 10001 while single-node returned 1001.
  • The prior Coverage summary failure was downstream of the failed Proxy producer; there was no independent Coverage defect or LocalFS EXDEV in that run.

Fresh local validation on the rebased content:

  • focused and full pkg/sql/compile: PASS
  • pkg/incrservice, pkg/sql/plan, pkg/sql/colexec/table_clone: PASS
  • full pkg/incrservice and table_clone race runs: PASS
  • four allocator lifecycle tests: -race -count=100 PASS
  • affected-package list/build/vet and git diff --check: PASS
  • exact-content preflight: PASS semantic=PASS, head 0c3c71255, diff hash 2108e115...

The new exact-head CI is running. In particular, Proxy BVT and the aggregate Coverage check remain pending and are not claimed as passed yet. Please re-review this head.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Follow-up on exact head dba425b4a59dc7df308803048483cc93d568e47f:

The first 0c3c71255 CI attempt failed before BVT execution in both jobs:

  • Proxy job 92515195034
  • Pessimistic job 92515195036

Both stopped while compiling cmd/mo-service because pkg/frontend/table_dump.go was the one remaining production caller of the old SetOffset(tableID, colName, offset, txn) signature.

The table-dump restore now forwards the already resolved stable restore.column.ColIndex together with the current name and offset. Its success and SetOffset-failure tests assert the six-argument call.

Fresh validation:

  • focused and full pkg/frontend: PASS
  • exact CI build target make build-with-prebuilt-native: PASS
  • affected-package list/build/vet and git diff --check: PASS
  • exact-content preflight: PASS semantic=PASS, head dba425b4a, diff hash 892f1a56...

The failed BVT jobs were deterministic compile failures, not SQL failures, and were not rerun on the superseded head. Fresh CI is expected on dba425b4a; no exact-head BVT result is claimed yet.

@VioletQwQ-0

VioletQwQ-0 commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Fixed the exact-head Proxy BVT failure and rebased onto the latest main.

Root cause:

  • CopyTableDef retained hidden source columns that are omitted from the temporary CREATE TABLE SQL.
  • The newly added SQL-visible AUTO_INCREMENT column was at planner slice index 3 but at allocator catalog index 1 on the created replacement table.
  • Reconciliation passed index 3 to SetOffset, so Proxy failed with expected one auto-increment column at index 3 ... found 0 rows.

Fix:

  • Resolve allocator column indexes from newRel.GetTableDef() (the created replacement definition).
  • Fail closed if planned and created SQL-visible AUTO_INCREMENT column-name sets differ.
  • Extend the focused regression with the exact hidden-column layout mismatch (planner index 3, created index 1), asserting SetOffset(9) and the matching catalog epoch update.

Validation on exact local head b4192062d7b40c4fc49c18560b97ba73b7fd0d2e:

  • focused TestReconcileAlterCopyAutoIncrement: PASS
  • full pkg/sql/compile: PASS
  • full pkg/incrservice: PASS
  • full pkg/frontend: PASS
  • full pkg/sql/plan: PASS
  • full pkg/sql/colexec/table_clone: PASS
  • make build-with-prebuilt-native: PASS
  • git diff --check: PASS
  • complete self-review: PASS
  • exact-content preflight: PASS (2bb800af981e5d9beed05e8d7bfac8e8581a93c6b4e02aa515a7eb86cd66dfed)

The previous UT Coverage failures were also checked: the untouched toolfs allocator panic and TAE checkpoint panic both passed targeted local repeats and are separate from this PR.

Exact-head CI result:

There are no unresolved review threads. Re-review has been requested from XuPeng-SH, aunjgr, and heni02; the remaining merge blocker is the old formal CHANGES_REQUESTED review pending replacement by a current-head review.

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

Reviewed exact head b4192062d7b40c4fc49c18560b97ba73b7fd0d2e. The rename/stable-index blocker and the latest COPY hidden-column index mismatch are fixed; exact-head CI is green, and the full local incrservice, sql/compile, sql/plan, table_clone, and frontend suites pass. One blocking statement-lifecycle gap remains for partitioned tables.

AlterTable applies an ordinary ALTER to the logical table first through s.doAlterTable(c), then expands qry.RawSQL across the physical partition tables with repeated c.runSql(sql) calls. However, doAlterTable creates and finishes its own alterAutoIncrementResetCleanup. Therefore, after the logical-table reset (and after each earlier nested partition ALTER) returns successfully, its cleanup has already observed statementErr == nil and will never discard that transaction-private allocator reset. If a later partition ALTER fails, the outer ALTER returns an error and the workspace rolls back the SQL statement, but the logical-table/earlier-partition entries in incrservice.mu.private remain authoritative until the transaction closes. A subsequent INSERT in the same explicit transaction can allocate from the failed ALTER's offset even though its catalog/store changes were rolled back. The same leak repeats for every successful partition before the failing one.

Please make reset cleanup owned by the complete user-visible ALTER statement, not by each prematurely successful sub-ALTER. All reset table IDs installed by the logical table and nested partition executions must be registered with one outer failure boundary (or the allocator service must participate directly in statement rollback). Add a deterministic partitioned AUTO_INCREMENT regression with at least two partitions: inject failure on a later physical ALTER, roll back the failed statement while keeping the transaction open, then prove the logical table and every earlier partition discarded their private reset and the next implicit INSERT follows the pre-ALTER allocator state. Also cover cancellation at that same boundary.

This is not exercised by the current successful partition/BVT paths; it is the partial-success edge created by composing per-subcall cleanup with a multi-relation statement.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed XuPeng-SH's statement-boundary cleanup CR in a125cff078.

Changes:

  • Scope.AlterTable now owns one alterAutoIncrementResetCleanup for the complete user-visible ALTER statement.
  • The logical table and each successfully completed physical partition are tracked by that outer owner.
  • A failing physical partition remains covered by its nested ALTER cleanup; the outer owner discards the logical table and the successful partition prefix on later failure or cancellation.
  • Cleanup still uses context.WithoutCancel, so cancellation cannot suppress rollback.

Regression coverage:

  • TestAlterPartitionTablesKeepsAutoIncrementCleanupAtStatementBoundary
    • two physical partitions, failure on the second;
    • cancellation after the first succeeds;
    • asserts discard of the logical table and first partition, without incorrectly tracking the failed partition.
  • TestDiscardOffsetResetRestoresNextImplicitAllocation
    • exercises the production allocator and proves the next implicit allocation after discard is committedOffset + 1, not the failed reset value.
  • Extended test/distributed/cases/auto_increment/auto_increment.sql with the public partitioned ALTER/INSERT success terminal. Deterministic later-partition failure injection is package-level because ordinary SQL cannot select a physical sub-ALTER failure point.

Validation on the pushed content:

  • focused compile/incrservice regressions: PASS
  • adaptive race stress: both exact tests -race -count=100: PASS
  • full pkg/sql/compile and pkg/incrservice under -race: PASS
  • full pkg/sql/compile, pkg/incrservice, pkg/sql/plan, pkg/sql/colexec/table_clone, and pkg/frontend: PASS
  • make build-with-prebuilt-native: PASS
  • git diff --check: PASS
  • exact-content semantic preflight: PASS semantic=PASS

Local mo-tester/BVT runtime is unavailable, so the authored BVT execution remains gated by this exact head's CI.

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

Approved on exact head a125cff078ce3e7ea0b81d28bd22068d03614e84.

The latest change closes my previous partitioned-ALTER lifecycle blocker at the correct ownership boundary: one outer cleanup now spans the logical table plus all successful physical partition sub-alters. A later error or cancellation discards the complete successful prefix, while a failing nested sub-alter still cleans up its own reset. Cleanup uses a non-cancelled context, and the success path preserves the transaction-owned reset until commit.

I rechecked the ownership and failure/cancellation paths, including repeated reset/cache restoration behavior, and found no new correctness, performance, or unhappy-path blocker. Exact-head focused tests passed, as did 20 repetitions under the race detector for both the partition statement-boundary cleanup and real next-implicit-allocation restoration tests. Current CI is green.

@mergify

mergify Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-06 12:30 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🚫 Left the queue — 2026-08-06 12:36 UTC · at a125cff078ce3e7ea0b81d28bd22068d03614e84

This pull request spent 5 minutes 37 seconds in the queue, with no time running CI.

Reason

The pull request can't be updated

merge conflict between base and head

Hint

You should update or rebase your pull request manually. If you do, this pull request will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Requeued — the merge queue status continues in this comment ↓.

@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 the exact head, including stable allocator identity, epoch fencing, rollback and cancellation cleanup, COPY reconciliation, and the outer cleanup spanning logical and partition ALTERs. The previously reported partition atomicity gap is closed. I found no remaining blocking issue.

@mergify

mergify Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-07 04:21 UTC · Rule: main · triggered by @VioletQwQ-0 with the merge queue checkbox
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-08-07 05:05 UTC · at a96ab30a3e5e30588742538569878970190549e3 · squash

This pull request spent 43 minutes 48 seconds in the queue, including 43 minutes 24 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86

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.

5 participants