Skip to content

fix(sql): keep sequence ownership and state consistent across DML, DDL and branch merge - #31945

Merged
XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-30359-main-e86b7613
Oct 31, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-30359-main-e86b7613

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Oct 31, 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:

Related to #30359.
Related to #30360.
Related to #30679.
Related to #30896.

What this PR does / why we need it:

Problem and root causes

Every generated sequence value must come from the intended sequence's state. Four independent paths violated that contract:

  1. DATA BRANCH MERGE leaves the destination sequence behind. Merge applies branch rows through an explicit writable-column INSERT ... SELECT, materializing the branch's key values, so the destination table's DEFAULT nextval(...) never runs and its sequence never advances. The next ordinary INSERT then duplicates a merged key (ERROR 1062: Duplicate entry '2' for key 'id'). Root cause: no sequence reconciliation in the merge apply path.
  2. Qualified INSERT resolves the default sequence in the caller database. For INSERT INTO owner_db.t with another database current, a column default nextval('s') resolved and advanced the caller database's same-named sequence instead of the one owned by owner_db.t. Root cause: the table-default expression binder used the session database rather than the table owner database.
  3. ALTER SEQUENCE ... START WITH is lost across sessions. Only the called flag persisted; the restart/clamp decision was not committed and createsql was not replayable, so a fresh session observed stale state or reissued consumed values. Root cause: the ALTER path never persisted the new start-with state nor updated the stored definition.
  4. Rolled-back NEXTVAL values were reissued. Sequence advancement participated in the user transaction, so NEXTVAL inside a rolled-back transaction re-issued the same value later. Root cause: no obligation tracking of issued values across rollback.

What this PR does

  • Post-merge sequence reconciliation (new pkg/frontend/data_branch_sequence_reconcile.go): after a successful table merge, the destination table's owning sequence advances to just beyond the merged keys. The reconciliation is monotonic, increment-quantized, direction-aware (ascending and descending) and storage-domain-aware across all six integer domains; merged out-of-domain explicit keys do not corrupt the watermark; exhaustion of a NO CYCLE sequence fails the merge atomically. The reconcile commits as its own unit, so a later merge rollback consumes a gap but never reuses a value.
  • Owner-database default binding (pkg/sql/plan/build_util.go, bind_insert.go, bind_multi_insert.go, bind_replace.go, bind_update.go, build_load.go, build_constraint_util.go, iceberg DML paths, pkg/sql/plan/function/seqfunc.go): a column default nextval(name) on owner_db.t always resolves and advances the sequence in owner_db, for BIGINT and cast-wrapped column types; auto-commit and explicit transactions and multi-row inserts behave identically; a missing owner sequence raises sequence-not-found and the caller database's same-named sequence is never consulted.
  • Persisted ALTER state (pkg/sql/compile/ddl.go, sequence_state.go, pkg/sql/plan/build_ddl.go, ddl_expression_replay.go): ALTER SEQUENCE ... START WITH commits a direction-aware restart (strictly ahead of the current position/pending value restarts to exactly that value; at-or-behind clamps and the position continues), for called and never-issued sequences alike, with bounds validation and no partial change; the stored definition is updated so SHOW CREATE/catalog consumers see replayable metadata; a fresh session observes the same effective state and never reissues consumed values.
  • Rollback obligations + autonomous allocation machine (pkg/vm/process/sequence_obligation.go, sequence_retry.go, pkg/sql/plan/function/seqfunc_autonomous.go, sequence_retry_probe.go, pkg/frontend/sequence_commit.go): issued values that roll back are recorded and never reissued (gaps allowed); allocation runs in an autonomous transaction with a progress-renewed retry window bounded at min(statement deadline, 10 s), probe-first expiry arbitration (renew/retire/resolve-naming), bounded per-attempt contexts propagated into every engine metadata read, and an exactly-once named terminal error when contention shows no committed progress for a full renewal interval while the row stays held. ROLLBACK always succeeds; explicit-transaction writers get conflict errors without transparent retry.
  • Attempt-output lifecycle (pkg/vm/process/types.go, pkg/sql/compile/compile2.go, pkg/frontend/session.go, query_result.go, select_into_user_variables.go, status_stmt.go, mysql_cmd_executor.go, resp_client.go): before a transparent retry replays an unpublished auto-commit statement, every retained output consumer is discarded after producer quiescence — prepared-cursor staging, SELECT ... INTO @var capture (reset so a one-row retry assigns the retried row instead of ErrTooManyRows), and PERFORM saved-result blocks/accounting (statement metadata preserved). The discard callback returns cleanup errors: a failure aborts the retry instead of replaying over surviving output, and failed cleanups keep their owner so terminal statement cleanup still reaches the files.

Validation

BVT (mo-tester, isolated 2-CN cluster; all pass, failed: 0):

  • test/distributed/cases/git4data/branch/merge/merge_sequence_reconcile.sql (272 statements: unit/non-unit increments, signed/unsigned storage domains, merge-rollback gap semantics, duplicate-key retry, case sensitivity, transformed defaults, decimal-backed NEXTVAL defaults)
  • test/distributed/cases/sequence/alter_sequence_start_with.sql (139), qualified_insert_owner_db.sql (27), nextval_rollback.sql (58), sequence_txn_local.sql (164)
  • Existing alter_sequence*.result, clone_database_sequence.result, issue_28246.result updated for the intended persisted-ALTER semantics; all other sequence BVTs unchanged and green.

UT (Go, focused + full package, including -race; all green):

  • go test ./pkg/frontend/ ./pkg/sql/compile/ ./pkg/sql/plan/ ./pkg/sql/plan/function/ ./pkg/vm/process/ and the same under -race, zero data races.
  • New regressions: merge-reconcile ownership/barrier tests, owner-database binding tests, persisted-ALTER cross-session tests, obligation/rollback tests, autonomous-machine context-bounding and expiry-arbitration tests, Compile.Run retry regressions (discard invoked on transition, retained consumers reset, cleanup error prevents replay), select-into reset and PERFORM abort tests, deletion-failure owner-retention test. Each was shown failing on the pre-fix base and passing after the fix.

Live controls: 16-client two-CN storm issued exactly the unique values 1..16 (next 17); designed contention produced exactly-once named terminals (8/8); insertion throughput unchanged within noise.

Rebase validation (2026-10-31, head 2972d080d8 on main dd762803d1): conflict resolution adopted upstream #31488's maps.Clone consolidation in pkg/sql/compile/sequence_state.go (this change's arbitrateSequenceRetryAdmission and the CTAS obligation handoff kept) and carried the owner-database parameter into upstream #30316 float-default test call sites. go build and go vet clean for pkg/vm/process, pkg/sql/plan, pkg/sql/plan/function, pkg/sql/compile, pkg/frontend; full go test -count=1 suites green on all five packages (process 2.9s, plan/function 32.2s, plan 96.6s, compile 23.6s, frontend 37.3s), including the reconciled float-default tests.

SCA fix (2026-10-31, head e07dc8a214): the arm64 SCA job failed make err-check because this change introduced the raw fmt.Errorf/errors.New forms the Makefile gate forbids (pkg/vm/process/sequence_retry.go:37, sequence_retry.go:32, sequence_retry_probe.go:54, seqfunc_autonomous.go:55 and :472). The three sentinel errors are now moerr.NewInternalErrorNoCtx values; SeqProbeIdentityGoneError composes the identity detail through a small wrapper type whose Unwrap preserves the pinned errors.Is semantics (moerr Error.Is matches only context codes), and the exhaustion fallback cause uses moerr as well. No message contract changed: existing assertions key on errors.Is and the unchanged "allocation could not acquire" prefix. Local gates: make err-check clean; golangci-lint run -c .golangci.yml and molint check on pkg/vm/process, pkg/sql/plan, pkg/frontend, pkg/sql/compile both 0 issues; go build clean; go test -count=1 green: pkg/vm/process 2.6s, pkg/sql/plan/function 36.8s.

Residual risks / limitations

  • Gap-free issuance is not guaranteed across rollbacks, retries or merge resolutions; uniqueness and monotonicity beyond merged keys are the contract.
  • An aborted or rolled-back merge may consume a destination-sequence gap; merged rows are fully removed.
  • Reconcile applies to the table's default-referenced sequence; standalone sequences still need explicit setval/alter management.
  • Transparent statement retry applies only to auto-commit statements before any result delivery; explicit transactions keep conflict errors.
  • Pre-existing, unrelated: on a two-CN layout, objects of a freshly DATA BRANCH CREATE-d database are invisible to the second CN (ERROR 20405); reproduces identically on the base binary without this change and will be tracked separately.
  • Design record (independent review approved; revision v22 carries the approved v21 contract plus the v22 conformance correction): docs/design/sequence_ownership_state_consistency.md.

UT coverage re-pin (2026-10-31, head 17b58d0a87): the Matrixone UT Coverage execution / UT Coverage on Ubuntu/x86 job failed only pkg/tests/issues.TestIssue28246ConcurrentNextval (runs 41189758357 job 124504310648 and, identically, pre-SCA head bae81d4ee1 run 41182286055 job 124482041630). The upstream Go oracle still pinned the pre-fix semantics this change deliberately replaces (design doc §1 Defect D, §2 I4, §8 deliberate pin updates): 2_sessions/4_sessions asserted a rolled-back NEXTVAL releases its value (expected workers+1, observed workers+2), and controlled lock handoff/lock wait timeout required NEXTVAL to queue on the holder's sequence row lock and fail with Lock wait timeout exceeded — while autonomous allocation on a committed generation holds no caller-transaction lock at all. The Go oracle is re-pinned to the reviewed contract: a rolled-back allocation stays consumed with the persisted counter advanced; a waiter receives the next value while the holder's transaction is still open; lock_wait_timeout no longer gates NEXTVAL; a fresh session never re-issues a rolled-back value; connections remain usable. This mirrors the BVT issue_28246.result pin update already in this change, extended to the Go oracle the §8 inventory missed. Local: go test -count=1 -run TestIssue28246ConcurrentNextval -v ./pkg/tests/issues green (9.2s concurrent-nextval suite + 6.6s placement suite), go vet clean.

Post-PR review fix (2026-10-31, head 43b8c25057): the post-merge review confirmed one incomplete fix — merging DECIMAL-backed NEXTVAL defaults (DECIMAL(18,0), DECIMAL(18,2), DECIMAL(38,0) primary keys with DEFAULT nextval(...)) left the destination sequence behind, so the next default INSERT regenerated a merged key (ERROR 1062: Duplicate entry '2' / '2.00'; BIGINT control passed). Root cause: extractDataBranchSQLRowValue preserves typed Decimal64/128/256 apply-row values, while the merge watermark capture accepted only machine-integer types and numeric strings/bytes, so typed decimals were silently skipped. The capture now normalizes integral typed decimals by the destination column's scale (stored keys are unscaled key * 10^s; decimal128/256 divide through limb-wise divisors) and folds the integral quotient into the unchanged int64/uint64 domain arms; stored fractions and quotients at or above 2^64 stay skipped, like other foreign values. Design doc revised to v22 (DEC1; §4 B). Validation: pre-fix code pinned skipping typed decimals (temporary unit assertion, later removed) and the pre-fix build reproduced the reviewer's duplicate-key probe on an isolated cluster; post-fix go vet clean, the full pkg/frontend reconcile suites green (20 top-level test functions including the 16-case decimal truth table + monotonic accumulation), and the same live probe advances every decimal watermark 1→2 with post-merge default INSERTs allocating 3 (final counters 3; full merge_sequence_reconcile.sql executed live with only its two pinned expected errors).

@mergify mergify Bot added the kind/bug Something isn't working label Oct 31, 2026
@matrix-meow matrix-meow added the size/XXL Denotes a PR that changes 2000+ lines label Oct 31, 2026
@gouhongshen
gouhongshen force-pushed the agent/issue-30359-main-e86b7613 branch from bae81d4 to 2972d08 Compare October 31, 2026 08:45
@gouhongshen
gouhongshen force-pushed the agent/issue-30359-main-e86b7613 branch from 2972d08 to e07dc8a Compare October 31, 2026 09:42
…L and branch merge

Sequence values must always come from the intended sequence state, but four
independent paths violated that contract:

1. DATA BRANCH MERGE copies branch-local sequence-generated keys into the
   source table while the source sequence stays behind; the next ordinary
   INSERT with DEFAULT nextval(...) fails with a duplicate primary key.
2. A column default nextval('s') on owner_db.t resolves and advances the
   same-named sequence in the caller's current database instead of the table
   owner database when another database is current.
3. ALTER SEQUENCE ... START WITH is not persisted for later sessions and the
   stored definition is not replayable, so restart/start state is lost.
4. NEXTVAL issued inside a transaction that rolls back re-issues the same
   value afterward (sequence advancement was transactional).

This change closes all four paths and the attempt lifecycle around them:

- Reconcile sequence state after a successful table merge: the destination
  table's owning sequence advances to just beyond the merged keys
  (increment-quantized, direction- and storage-domain-aware, atomic with
  documented gap-not-reuse semantics).
- Bind table-default nextval in the table owner's database on every DML
  binding path (INSERT, multi-INSERT, REPLACE, UPDATE, LOAD, iceberg DML).
- Persist ALTER SEQUENCE restart/clamp state with replayable SHOW CREATE
  metadata; start-with is direction-aware for called and never-issued
  sequences.
- Record rollback obligations so rolled-back issued values are never
  reissued, and allocate via an autonomous transaction machine with a
  progress-renewed retry window, probe-first expiry decisions, bounded
  per-attempt contexts and an exactly-once named terminal error.
- Discard every retained output consumer (prepared-cursor staging,
  SELECT ... INTO capture, PERFORM saved result) after producer quiescence
  and before transparent retry replays a statement, and surface
  attempt-cleanup failures instead of replaying over surviving output.

Related to matrixorigin#30359. Related to matrixorigin#30360. Related to matrixorigin#30679. Related to matrixorigin#30896.
@XuPeng-SH

XuPeng-SH commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 17b58d0a87d34d0d537b7320d63c4cd46bcd4eaf

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: 17b58d0a87d34d0d537b7320d63c4cd46bcd4eaf

Assessment: request_changes

One confirmed incomplete fix remains: merging decimal-backed NEXTVAL defaults leaves the destination sequence behind and causes duplicate-key errors.

Model: gpt-6-astra / xhigh

Session: 01a1869d-999c-7481-b340-ae4a63e8cee4 · slot 1 · generation 2

  • P2 pkg/frontend/data_branch_sequence_reconcile.go:328: Use DECIMAL(18,0), DECIMAL(18,2), or DECIMAL(38,0) as a primary key with DEFAULT nextval('s'); insert on a database branch, then merge into the owner table.
    Impact: The merge succeeds without advancing the owner sequence. The next default INSERT regenerates the merged key and fails with error 1062. Normalize integral decimal values using the column scale before accumulating watermarks, and add maintained decimal regression coverage. This leaves the preexisting merge defect incompletely fixed.
    Evidence: extractDataBranchSQLRowValue preserves typed decimals, but sequenceWatermarkValueOf accepts only integer types and integer strings/bytes, so capture silently skips them. The public SQL probe observed watermark 1 instead of 2 and duplicate key 2/2.00 in all three decimal cases; the BIGINT control passed. See probe-report.md, public-numeric-insert-final.jsonl, and checks/1793451789041737148-2.json.

Validation:

  • Reviewed the complete delta, relevant consumers, linked issues, and discussion; saved review-plan.md and discussion-assessment.json.

  • Isolation preflight and native-artifact qualification passed. All 197 selected maintained tests passed across five affected packages, with no skips.

  • Public SQL counterexample confirmed three decimal failures with a passing BIGINT control.

  • validation-summary.json matches checks to retained logs; final audit confirmed the frozen HEAD and unchanged source.

Limitations:

  • Local execution used focused normal-mode tests. Full race, distributed BVT, performance, and restart/upgrade campaigns were not independently rerun; supplied CI summaries and author claims were assessed separately.

…scale (matrixorigin#30359)

Post-PR review follow-up: a DECIMAL(p,s) destination column backed by a
nextval default stores each issued key unscaled as key * 10^s, but the
merge watermark capture accepted only machine-integer types and numeric
strings/bytes, so typed Decimal64/128/256 apply-row values were silently
skipped. DATA BRANCH MERGE then left the owner sequence at its old
position and the first post-merge default INSERT regenerated an
already-merged key (ERROR 1062, "Duplicate entry '2'" / "'2.00'" for
DECIMAL(18,0)/(18,2)/(38,0); the BIGINT control passed).

Capture now receives the destination column's type and normalizes
integral typed decimals by its scale: magnitude and sign are extracted
(two's-complement negatives), the magnitude is divided by 10^scale
(decimal64 by the machine divisor, decimal128/256 by limb-wise
divisors), and only the integral quotient folds into the unchanged
int64/uint64 per-domain arms. Stored fractions and quotients at or
above 2^64 stay skipped, exactly like other foreign values.

Coverage: the capture truth table gains the decimal matrix (16 cases,
integral/fractional x sign x decimal64/128/256, divisor crossing 64
bits, quotient >= 2^64, six-domain arm truth table) plus a monotonic
accumulation subtest; merge_sequence_reconcile.sql gains the three live
decimal merge regressions. Design doc revised to v22 (DEC1; section 4 B
capture paragraph).
@gouhongshen

Copy link
Copy Markdown
Contributor Author

Addressed in 43b8c25057 (pushed with this reply).

P2 — decimal-backed NEXTVAL defaults leave the owner sequence behind: valid, fixed.

Validity was confirmed two ways before changing code:

  1. Code path: extractDataBranchSQLRowValue preserves typed Decimal64/Decimal128/Decimal256 values, while the pre-fix sequenceWatermarkValueOf switch accepted only machine-integer types and numeric strings/bytes — typed decimals fell through and capture silently skipped them.
  2. Live replication of the probe on an isolated cluster built from the pre-fix head: merging DECIMAL(18,0), DECIMAL(18,2) and DECIMAL(38,0) primary keys with DEFAULT nextval(...) left every owner sequence at watermark 1, and the next default INSERT failed with ERROR 1062: Duplicate entry '2' / '2.00' in all three decimal cases; the BIGINT control advanced to 2 and inserted cleanly.

Fix, per the review prescription (design doc revised to v22, DEC1, §4 B): sequenceWatermarkValueOf now receives the destination column's type and normalizes integral typed decimals by the column scale. A DECIMAL(p,s) column backed by a nextval default stores each issued key unscaled as key * 10^s, so capture extracts magnitude and sign, divides the magnitude by 10^scale (decimal64 by the machine divisor; decimal128/256 by limb-wise divisors built with 128-bit multiplies), and folds only the integral quotient into the unchanged int64/uint64 per-domain classification. A stored fraction can never name a sequence-issued integral key and stays skipped, and a quotient at or above 2^64 stays skipped like any foreign value — identical to the pre-existing treatment of out-of-domain keys.

Maintained regression coverage:

  • UT: TestSequenceWatermarkCaptureAccumulation/decimal_columns_normalize_integral_keys_by_scale — 16 cases over decimal64/128/256 × integral/fractional × sign, including the divisor-crossing-64-bits case (10^20), a quotient-at-2^64 skip, and the full six-domain arm truth table; plus decimal_accumulation_merges_monotonic_with_fractional_skips pinning monotonic accumulation across fractional captures.
  • BVT: test/distributed/cases/git4data/branch/merge/merge_sequence_reconcile.sql gains the three live decimal merge cases (watermark advances 1→2 at merge; the post-merge default INSERT allocates 3 instead of colliding; results inspected against live output).

Validation: a temporary unit pin on the pre-fix code asserted the old function skipped typed decimals (PASS, then removed); the pre-fix live probe reproduced the reviewer's duplicate-key failures exactly; post-fix, the same maintained UT passes and the same live probe advances every decimal watermark to 2 with all default inserts succeeding (final counters 3, BIGINT control unchanged). Focused go test ./pkg/frontend/ reconcile suites green; go vet/gofmt clean.

@XuPeng-SH

XuPeng-SH commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 43b8c25057285372205c9af2dc8621e616c0b66d

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: 43b8c25057285372205c9af2dc8621e616c0b66d

Assessment: approve

The prior decimal sequence-reconciliation finding is resolved. Qualified prior coverage and fresh validation close the assigned scope with no remaining actionable findings.

Model: gpt-6-astra / xhigh

Session: 01a1869d-820c-7212-9788-aecfb86a4141 · slot 0 · generation 2

Validation:

  • Qualified prior complete-review coverage and receipts for 197 passing tests.

  • Passed 16 maintained frontend tests and 12,174 independent arithmetic comparisons.

  • Passed six public SQL merge/allocation scenarios across two runs; the original decimal counterexamples now allocate key 3 successfully.

  • Completed discussion assessment and receipt/log audit; frozen source remains unchanged. Evidence is retained in validation-summary.json.

Limitations:

  • Fresh execution used focused normal-mode tests and a one-CN SQL fixture; broader race, distributed, performance and upgrade campaigns were not independently rerun.

  • An extra probe initially used unsupported decimal precision 76. It was corrected to precision 65, and the missing scenario passed separately.

@mergify mergify Bot added the queued label Oct 31, 2026
@mergify

mergify Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue

2 h 24 min in the queue, with no time running CI.

So far

  • ✅ Entered the queue Sat 31 Oct, 15:32 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 17:56 · 48e471e

Reason

Pull request #31945 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Merge conditions not met when it left the queue

  • any of · required by GitHub branch protection:
    • check-neutral = CI Required
    • check-skipped = CI Required
    • check-success = CI Required

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request
2 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection

Times in UTC · dashboard · how the merge queue works

This branch was previously deployed

1 inactive deployment
ci — 48e471ec Deployed Oct 31, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/bug Something isn't working size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants