Repository navigation
fix(sql): keep sequence ownership and state consistent across DML, DDL and branch merge - #31945
Conversation
bae81d4 to
2972d08
Compare
2972d08 to
e07dc8a
Compare
…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.
e07dc8a to
17b58d0
Compare
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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).
|
Addressed in P2 — decimal-backed NEXTVAL defaults leave the owner sequence behind: valid, fixed. Validity was confirmed two ways before changing code:
Fix, per the review prescription (design doc revised to v22, DEC1, §4 B): Maintained regression coverage:
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 |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
🚫 Left the queue2 h 24 min in the queue, with no time running CI. So far
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.
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. Merge conditions not met when it left the queue
Tick the box to put this pull request back in the merge queue (same as
2 merge conditions met
Times in UTC · dashboard · how the merge queue works |
What type of PR is this?
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:
INSERT ... SELECT, materializing the branch's key values, so the destination table'sDEFAULT nextval(...)never runs and its sequence never advances. The next ordinaryINSERTthen duplicates a merged key (ERROR 1062: Duplicate entry '2' for key 'id'). Root cause: no sequence reconciliation in the merge apply path.INSERT INTO owner_db.twith another database current, a column defaultnextval('s')resolved and advanced the caller database's same-named sequence instead of the one owned byowner_db.t. Root cause: the table-default expression binder used the session database rather than the table owner database.createsqlwas 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.NEXTVALinside a rolled-back transaction re-issued the same value later. Root cause: no obligation tracking of issued values across rollback.What this PR does
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.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 defaultnextval(name)onowner_db.talways resolves and advances the sequence inowner_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.pkg/sql/compile/ddl.go,sequence_state.go,pkg/sql/plan/build_ddl.go,ddl_expression_replay.go):ALTER SEQUENCE ... START WITHcommits 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.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.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 @varcapture (reset so a one-row retry assigns the retried row instead ofErrTooManyRows), 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)alter_sequence*.result,clone_database_sequence.result,issue_28246.resultupdated 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.Compile.Runretry 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
2972d080d8on maindd762803d1): conflict resolution adopted upstream #31488'smaps.Cloneconsolidation inpkg/sql/compile/sequence_state.go(this change'sarbitrateSequenceRetryAdmissionand the CTAS obligation handoff kept) and carried the owner-database parameter into upstream#30316float-default test call sites.go buildandgo vetclean forpkg/vm/process,pkg/sql/plan,pkg/sql/plan/function,pkg/sql/compile,pkg/frontend; fullgo test -count=1suites 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 failedmake err-checkbecause this change introduced the rawfmt.Errorf/errors.Newforms the Makefile gate forbids (pkg/vm/process/sequence_retry.go:37,sequence_retry.go:32,sequence_retry_probe.go:54,seqfunc_autonomous.go:55and:472). The three sentinel errors are nowmoerr.NewInternalErrorNoCtxvalues;SeqProbeIdentityGoneErrorcomposes the identity detail through a small wrapper type whoseUnwrappreserves the pinnederrors.Issemantics (moerrError.Ismatches only context codes), and the exhaustion fallback cause uses moerr as well. No message contract changed: existing assertions key onerrors.Isand the unchanged "allocation could not acquire" prefix. Local gates:make err-checkclean;golangci-lint run -c .golangci.ymlandmolint checkonpkg/vm/process,pkg/sql/plan,pkg/frontend,pkg/sql/compileboth 0 issues;go buildclean;go test -count=1green:pkg/vm/process2.6s,pkg/sql/plan/function36.8s.Residual risks / limitations
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.docs/design/sequence_ownership_state_consistency.md.UT coverage re-pin (2026-10-31, head
17b58d0a87): theMatrixone UT Coverage execution / UT Coverage on Ubuntu/x86job failed onlypkg/tests/issues.TestIssue28246ConcurrentNextval(runs 41189758357 job 124504310648 and, identically, pre-SCA headbae81d4ee1run 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_sessionsasserted a rolled-back NEXTVAL releases its value (expectedworkers+1, observedworkers+2), andcontrolled lock handoff/lock wait timeoutrequired NEXTVAL to queue on the holder's sequence row lock and fail withLock 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_timeoutno longer gates NEXTVAL; a fresh session never re-issues a rolled-back value; connections remain usable. This mirrors the BVTissue_28246.resultpin update already in this change, extended to the Go oracle the §8 inventory missed. Local:go test -count=1 -run TestIssue28246ConcurrentNextval -v ./pkg/tests/issuesgreen (9.2s concurrent-nextval suite + 6.6s placement suite),go vetclean.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 withDEFAULT 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:extractDataBranchSQLRowValuepreserves typedDecimal64/128/256apply-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 unscaledkey * 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-fixgo vetclean, the fullpkg/frontendreconcile 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; fullmerge_sequence_reconcile.sqlexecuted live with only its two pinned expected errors).