Repository navigation
fix(sequence): make concurrent NEXTVAL transactional - #28345
Conversation
Use the caller transaction for sequence metadata reads and writes so concurrent NEXTVAL calls serialize on the sequence row instead of conflicting nested transactions. Restore process-local sequence state across statement retries and reject canceled sequence statements before publishing metadata changes.\n\nAdd concurrency, rollback, lock-timeout, relation-kind, metadata-shape, cancellation, and distributed sequence coverage for matrixorigin#28246.
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? |
aptend
left a comment
There was a problem hiding this comment.
Deep review completed against exact head ce295385f3317ace59021b4652aebc21ca664cff (base 665a17da136fdd17b1cbc97e0b973b8ec54b67d6). I reviewed the linked issue, the full diff, transaction/retry/session-state and cleanup paths, all review/comment/thread history (there were no prior human reviews or threads), and the added UT/BVT coverage. The intended inter-transaction serialization and rollback behavior look sound, but same-transaction parallel evaluation still emits duplicate sequence values, so this is blocking.
Validation: the focused function/compile tests and the PR's embedded issue regression pass; plan/function passes race testing at count 3 and compile passes race testing at count 1. A review-only end-to-end regression for two parallel UNION branches fails deterministically twice with duplicate values and was removed afterward. CI is green, git diff --check is clean, and the exact head merges cleanly with the latest main tree.
| } | ||
| } | ||
| } | ||
| opts := executor.Options{}.WithTxn(proc.GetTxnOperator()). |
There was a problem hiding this comment.
[P1] Serialize sequence allocation across sibling workers in the same caller transaction. Passing proc.GetTxnOperator() here gives every parallel branch the same transaction identity: scan parallelization clones projections into sibling workers, and their child processes share that transaction. Consequently SELECT ... FOR UPDATE treats a sibling as the existing lock owner instead of making it wait, so both branches can read and write the same sequence value.
On this exact head, I created two one-row tables and ran select nextval('parallel_0') from seq_left union all select nextval('parallel_0') from seq_right on one connection. It returned [1,1] and persisted last_seq_num=1 rather than returning [1,2] and persisting 2; this reproduced twice. The existing two-row BVT evaluates one vector batch serially and does not exercise sibling pipelines. Parallel SELECTs and INSERT-default plans can therefore issue duplicate sequence values. Please provide a single allocation lane/coordinator that serializes calls across local DOP and cross-CN scopes (a CN-local mutex is insufficient), and add regressions with parallel branches and a multi-block/DOP scan.
|
Implemented and pushed as Root cause: same-transaction child scopes shared the transaction lock and unsynchronized sequence session state, so sibling NEXTVAL branches could both observe the same metadata value. Fix:
Validation completed locally: owning packages pass; full owning-package |
) ## What type of PR is this? - [x] BUG - [x] Improvement - [x] Test and CI ## Which issue(s) this PR fixes: Fixes #28208 ## What this PR does / why we need it: Restore the row-local FROM_BASE64 contract: valid input returns exactly the decoded bytes, invalid/NULL input produces only that row's NULL, and masked rows are not evaluated. The old implementation ignored Decode's written-byte count, returned from the entire batch on NULL/invalid input, and discarded result-append errors. - Preserve the standard decoder fast path; on failure only, compact MySQL whitespace into separate scratch storage and retry once. Input vectors are never mutated. The whitespace byte set matches MySQL 8.0's `include/base64.h` table (space, 0x09–0x0d, 0xa0), not Unicode whitespace. - Use call-local bounded scratch: a small stack buffer, reused decoded storage for larger rows, and lazy whitespace scratch. No global state, cache, synchronization, or cross-batch retention. - Propagate result-append errors and discard partial decoded prefixes on invalid input. - Extend existing UT/BVT instead of introducing a cluster fixture. Correct three existing BVT expectations that embedded the erroneous trailing NUL bytes. Add explicit cleanup of tables previously left behind by the case. - Test mixed valid/NULL/invalid rows, padding, empty input/batch, binary bytes, whitespace classes, malformed padding, constant input, masked rows, input immutability, and result reuse. Keep a focused benchmark; the temporary legacy comparison implementation is not delivered. MySQL source reference: https://github.com/mysql/mysql-server/blob/8.0/include/base64.h ## Validation - Pre-fix regression: FAIL, expected 15 rows but got 3; the first NULL prematurely ended the batch. - Native CPU owning-package test: PASS, `mo-cgo-test -count=1 -timeout=10m ./pkg/sql/plan/function`. - `make -j8 build`: PASS. - SQL/BVT on the reviewed final binary: `func_encode_decode.sql` passed 124/124 twice on the same standalone instance (0.380s and 1.645s), with zero residual fixture tables between runs. SQL and ISCP readiness were checked before execution. - Local same-machine benchmark, 128 rows/batch: initial paired comparison used three 200ms samples; final reviewed candidate used three 300ms samples. 1KiB payload without whitespace improves from approximately 94us to 71us; allocations fall from 129 to 2 and bytes allocated from 147552 to approximately 1248 per batch. Short 12-byte payload is approximately 4.6us vs 4.2us (~7–10% / roughly 3ns per row) with the same allocation count. This is a microbenchmark, not an end-to-end SQL throughput claim. Legacy whitespace timings are excluded because the old implementation exited on the first row instead of decoding the batch. ## Review scope R2 public scalar result contract with focused hot-path benchmarking. Ordinary bug fix: no design-document gate. No persisted/wire format, transaction, shared state, or topology contract changes; distributed/race/restart suites are not substitutes for scalar UT and public SQL evidence here. Reviewed all four delivery files, including textual inspection of the binary-marked result file. Unrelated encoding/vector functions remain unchanged. Full pre-PR review traced registration/evaluation -> function -> result append -> owned varlena storage. It found and fixed an all-masked-row gap: `FunctionSelectList.Contains` does not encode `AllNull`. The initial test derived its expectation from the same helper and therefore missed it. Replacing that oracle with explicit NULL expectations produced a deterministic failure; the implementation now honors `IgnoreAllRow` explicitly. The aliasing test crosses non-inline storage boundaries. Benchmarks validate every output before timing, preventing early termination/NULL output from masquerading as throughput. Reviewed delivery head: `34c5158f18b2432a5de1c10db11c6a6f3d8803fc`; base/merge-base: `df261604fe207e592f5d92b15d66167c38e97db6`. Main subsequently advanced only through #28345 (sequence code), without overlap with this closure. No unresolved in-scope review blockers. Local service logs also contain ISCP transaction-finish timeouts; those background warnings are not claimed resolved by this scalar-function PR. All selected public SQL checks completed successfully. CI has not been waited for. --------- Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
## What type of PR is this? - [ ] API-change - [ ] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [x] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Fixes #28245 ## What this PR does / why we need it: The production escaping fix is already present in `main` through #28345. This PR adds the missing end-to-end distributed BVT regression for the original legal sequence-name case; it intentionally makes no production-code or runtime-performance change. The test creates a sequence whose decoded name contains a backtick in an ordinary database, then exercises the supported public `NEXTVAL` and `SETVAL` forms. Returned values prove the initial allocation, SETVAL update, and subsequent increment. Each stateful call is an independent statement. Database identifiers containing a backtick are rejected by frontend name validation, and the extra database-argument overloads are internal rather than public SQL. Those unreachable input forms are not included. The helper-level unit test already verifies escaping of both database and relation components. ## Validation / test plan - `git diff --cached --check` — PASS. - Staged SQL/result consistency check: 3 stateful queries, 3 result headers, expected values `7, 21, 23` — PASS. - Source review confirms every sequence metadata SELECT/UPDATE uses `sequenceTableName`. - Local distributed BVT was not run: unrelated MatrixOne services are active, and this worktree lacks provenance-validated native CGo artifacts. No local runtime result is claimed. Please run `test/distributed/cases/sequence/issue_28245.sql` on the exact PR head. ## Risk / limitations This is regression coverage only; it does not add or alter the already-merged production fix. Exact-head BVT execution and result comparison remain required before closing the issue. The current change adds no production cost or concurrency/resource behavior.
) ## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: issue matrixorigin#28246 ## What this PR does / why we need it: ### Root cause `NEXTVAL`/`SETVAL` previously used a shared background SQL helper. It opened a separate transaction for the metadata read/update, so concurrent callers raced on the same sequence row and one caller could receive `context canceled` instead of a value. A failed statement could also leave process-local `CURRVAL`/`LASTVAL` state from the failed attempt when the outer compiler rebuilt a retry. ### Design - Execute sequence metadata `SELECT ... FOR UPDATE` and updates through the caller's existing transaction operator. The outer compiler remains the only owner of statement rollback/retry and cancellation cleanup. - Preserve the background/internal-write admission marker, account/database/session options, lock-wait timeout, and identifier escaping required by the internal executor. - Validate the relation kind before reading or writing sequence-shaped metadata, and fail closed on invalid metadata shape/type or NULL values. - Capture and restore process-local sequence state around statement retry transitions so rolled-back attempts cannot publish session-visible values. - Check the owning statement context before and after the internal SQL call, so cancellation racing a lock wait is propagated to the outer transaction. ### Scope and non-goals This fixes sequence transaction ownership and retry/cancellation behavior. It does not change sequence allocation semantics, cycle/overflow rules, or client-driver behavior when a client closes a socket during cancellation. ### Validation / test plan - Local native-CGo UT after rebasing `origin/main` at `e78ff09781`: - `go test -mod=readonly -count=1 ./pkg/sql/plan/function ./pkg/sql/compile` — PASS. - `go test -race -mod=readonly -count=1 ./pkg/sql/plan/function ./pkg/sql/compile` — PASS. - `go test -mod=readonly -count=1 -run '^TestIssue28246ConcurrentNextval$' -timeout=6m ./pkg/tests/issues` — PASS. - 55 machine (`10.222.1.55`) native-CGo integration, candidate service on the current implementation: `TestIssue28246ConcurrentNextval` — PASS in 21.365s. The test covers 2- and 4-session concurrent allocation (exact contiguous values), explicit rollback/read-your-own-writes, lock handoff, server-side lock-wait timeout with exact error text, waiter connection reuse, and no value consumption after timeout. - Distributed sequence BVT against the candidate service: the new matrixorigin#28246 case passed twice (25/25 each); the complete sequence group passed 447/447. - Unit coverage includes same-transaction/options propagation, result cleanup on malformed metadata, relation-kind rejection for ordinary tables, canceled-context short-circuit, and retry-state deep-copy restoration. ### QA notes Please run the new distributed case `test/distributed/cases/sequence/issue_28246.sql` and the existing sequence group. Verify concurrent `NEXTVAL` from independent sessions returns every value exactly once, rollback does not consume a value, lock timeout returns a typed timeout error, and the same connection remains usable afterward. ### Risk / limitations The change moves sequence metadata writes into the caller transaction, which is required for atomicity and may make lock conflicts visible to the outer statement retry path. No new goroutine, RPC wait, or unbounded cache is introduced. The 55-machine client-cancellation probe is intentionally not used as the public oracle because the MySQL driver may close the connection while the server is still finishing the canceled query; cancellation propagation is covered deterministically at the internal boundary and server-side lock-timeout path instead. --------- Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
…rixorigin#28360) ## What type of PR is this? - [x] BUG - [x] Improvement - [x] Test and CI ## Which issue(s) this PR fixes: Fixes matrixorigin#28208 ## What this PR does / why we need it: Restore the row-local FROM_BASE64 contract: valid input returns exactly the decoded bytes, invalid/NULL input produces only that row's NULL, and masked rows are not evaluated. The old implementation ignored Decode's written-byte count, returned from the entire batch on NULL/invalid input, and discarded result-append errors. - Preserve the standard decoder fast path; on failure only, compact MySQL whitespace into separate scratch storage and retry once. Input vectors are never mutated. The whitespace byte set matches MySQL 8.0's `include/base64.h` table (space, 0x09–0x0d, 0xa0), not Unicode whitespace. - Use call-local bounded scratch: a small stack buffer, reused decoded storage for larger rows, and lazy whitespace scratch. No global state, cache, synchronization, or cross-batch retention. - Propagate result-append errors and discard partial decoded prefixes on invalid input. - Extend existing UT/BVT instead of introducing a cluster fixture. Correct three existing BVT expectations that embedded the erroneous trailing NUL bytes. Add explicit cleanup of tables previously left behind by the case. - Test mixed valid/NULL/invalid rows, padding, empty input/batch, binary bytes, whitespace classes, malformed padding, constant input, masked rows, input immutability, and result reuse. Keep a focused benchmark; the temporary legacy comparison implementation is not delivered. MySQL source reference: https://github.com/mysql/mysql-server/blob/8.0/include/base64.h ## Validation - Pre-fix regression: FAIL, expected 15 rows but got 3; the first NULL prematurely ended the batch. - Native CPU owning-package test: PASS, `mo-cgo-test -count=1 -timeout=10m ./pkg/sql/plan/function`. - `make -j8 build`: PASS. - SQL/BVT on the reviewed final binary: `func_encode_decode.sql` passed 124/124 twice on the same standalone instance (0.380s and 1.645s), with zero residual fixture tables between runs. SQL and ISCP readiness were checked before execution. - Local same-machine benchmark, 128 rows/batch: initial paired comparison used three 200ms samples; final reviewed candidate used three 300ms samples. 1KiB payload without whitespace improves from approximately 94us to 71us; allocations fall from 129 to 2 and bytes allocated from 147552 to approximately 1248 per batch. Short 12-byte payload is approximately 4.6us vs 4.2us (~7–10% / roughly 3ns per row) with the same allocation count. This is a microbenchmark, not an end-to-end SQL throughput claim. Legacy whitespace timings are excluded because the old implementation exited on the first row instead of decoding the batch. ## Review scope R2 public scalar result contract with focused hot-path benchmarking. Ordinary bug fix: no design-document gate. No persisted/wire format, transaction, shared state, or topology contract changes; distributed/race/restart suites are not substitutes for scalar UT and public SQL evidence here. Reviewed all four delivery files, including textual inspection of the binary-marked result file. Unrelated encoding/vector functions remain unchanged. Full pre-PR review traced registration/evaluation -> function -> result append -> owned varlena storage. It found and fixed an all-masked-row gap: `FunctionSelectList.Contains` does not encode `AllNull`. The initial test derived its expectation from the same helper and therefore missed it. Replacing that oracle with explicit NULL expectations produced a deterministic failure; the implementation now honors `IgnoreAllRow` explicitly. The aliasing test crosses non-inline storage boundaries. Benchmarks validate every output before timing, preventing early termination/NULL output from masquerading as throughput. Reviewed delivery head: `34c5158f18b2432a5de1c10db11c6a6f3d8803fc`; base/merge-base: `df261604fe207e592f5d92b15d66167c38e97db6`. Main subsequently advanced only through matrixorigin#28345 (sequence code), without overlap with this closure. No unresolved in-scope review blockers. Local service logs also contain ISCP transaction-finish timeouts; those background warnings are not claimed resolved by this scalar-function PR. All selected public SQL checks completed successfully. CI has not been waited for. --------- Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
## What type of PR is this? - [ ] API-change - [ ] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [x] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Fixes matrixorigin#28245 ## What this PR does / why we need it: The production escaping fix is already present in `main` through matrixorigin#28345. This PR adds the missing end-to-end distributed BVT regression for the original legal sequence-name case; it intentionally makes no production-code or runtime-performance change. The test creates a sequence whose decoded name contains a backtick in an ordinary database, then exercises the supported public `NEXTVAL` and `SETVAL` forms. Returned values prove the initial allocation, SETVAL update, and subsequent increment. Each stateful call is an independent statement. Database identifiers containing a backtick are rejected by frontend name validation, and the extra database-argument overloads are internal rather than public SQL. Those unreachable input forms are not included. The helper-level unit test already verifies escaping of both database and relation components. ## Validation / test plan - `git diff --cached --check` — PASS. - Staged SQL/result consistency check: 3 stateful queries, 3 result headers, expected values `7, 21, 23` — PASS. - Source review confirms every sequence metadata SELECT/UPDATE uses `sequenceTableName`. - Local distributed BVT was not run: unrelated MatrixOne services are active, and this worktree lacks provenance-validated native CGo artifacts. No local runtime result is claimed. Please run `test/distributed/cases/sequence/issue_28245.sql` on the exact PR head. ## Risk / limitations This is regression coverage only; it does not add or alter the already-merged production fix. Exact-head BVT execution and result comparison remain required before closing the issue. The current change adds no production cost or concurrency/resource behavior.
) ## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: issue matrixorigin#28246 ## What this PR does / why we need it: ### Root cause `NEXTVAL`/`SETVAL` previously used a shared background SQL helper. It opened a separate transaction for the metadata read/update, so concurrent callers raced on the same sequence row and one caller could receive `context canceled` instead of a value. A failed statement could also leave process-local `CURRVAL`/`LASTVAL` state from the failed attempt when the outer compiler rebuilt a retry. ### Design - Execute sequence metadata `SELECT ... FOR UPDATE` and updates through the caller's existing transaction operator. The outer compiler remains the only owner of statement rollback/retry and cancellation cleanup. - Preserve the background/internal-write admission marker, account/database/session options, lock-wait timeout, and identifier escaping required by the internal executor. - Validate the relation kind before reading or writing sequence-shaped metadata, and fail closed on invalid metadata shape/type or NULL values. - Capture and restore process-local sequence state around statement retry transitions so rolled-back attempts cannot publish session-visible values. - Check the owning statement context before and after the internal SQL call, so cancellation racing a lock wait is propagated to the outer transaction. ### Scope and non-goals This fixes sequence transaction ownership and retry/cancellation behavior. It does not change sequence allocation semantics, cycle/overflow rules, or client-driver behavior when a client closes a socket during cancellation. ### Validation / test plan - Local native-CGo UT after rebasing `origin/main` at `e78ff09781`: - `go test -mod=readonly -count=1 ./pkg/sql/plan/function ./pkg/sql/compile` — PASS. - `go test -race -mod=readonly -count=1 ./pkg/sql/plan/function ./pkg/sql/compile` — PASS. - `go test -mod=readonly -count=1 -run '^TestIssue28246ConcurrentNextval$' -timeout=6m ./pkg/tests/issues` — PASS. - 55 machine (`10.222.1.55`) native-CGo integration, candidate service on the current implementation: `TestIssue28246ConcurrentNextval` — PASS in 21.365s. The test covers 2- and 4-session concurrent allocation (exact contiguous values), explicit rollback/read-your-own-writes, lock handoff, server-side lock-wait timeout with exact error text, waiter connection reuse, and no value consumption after timeout. - Distributed sequence BVT against the candidate service: the new matrixorigin#28246 case passed twice (25/25 each); the complete sequence group passed 447/447. - Unit coverage includes same-transaction/options propagation, result cleanup on malformed metadata, relation-kind rejection for ordinary tables, canceled-context short-circuit, and retry-state deep-copy restoration. ### QA notes Please run the new distributed case `test/distributed/cases/sequence/issue_28246.sql` and the existing sequence group. Verify concurrent `NEXTVAL` from independent sessions returns every value exactly once, rollback does not consume a value, lock timeout returns a typed timeout error, and the same connection remains usable afterward. ### Risk / limitations The change moves sequence metadata writes into the caller transaction, which is required for atomicity and may make lock conflicts visible to the outer statement retry path. No new goroutine, RPC wait, or unbounded cache is introduced. The 55-machine client-cancellation probe is intentionally not used as the public oracle because the MySQL driver may close the connection while the server is still finishing the canceled query; cancellation propagation is covered deterministically at the internal boundary and server-side lock-timeout path instead. --------- Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
What type of PR is this?
Which issue(s) this PR fixes:
issue #28246
What this PR does / why we need it:
Root cause
NEXTVAL/SETVALpreviously used a shared background SQL helper. It opened a separate transaction for the metadata read/update, so concurrent callers raced on the same sequence row and one caller could receivecontext canceledinstead of a value. A failed statement could also leave process-localCURRVAL/LASTVALstate from the failed attempt when the outer compiler rebuilt a retry.Design
SELECT ... FOR UPDATEand updates through the caller's existing transaction operator. The outer compiler remains the only owner of statement rollback/retry and cancellation cleanup.Scope and non-goals
This fixes sequence transaction ownership and retry/cancellation behavior. It does not change sequence allocation semantics, cycle/overflow rules, or client-driver behavior when a client closes a socket during cancellation.
Validation / test plan
origin/mainate78ff09781:go test -mod=readonly -count=1 ./pkg/sql/plan/function ./pkg/sql/compile— PASS.go test -race -mod=readonly -count=1 ./pkg/sql/plan/function ./pkg/sql/compile— PASS.go test -mod=readonly -count=1 -run '^TestIssue28246ConcurrentNextval$' -timeout=6m ./pkg/tests/issues— PASS.10.222.1.55) native-CGo integration, candidate service on the current implementation:TestIssue28246ConcurrentNextval— PASS in 21.365s. The test covers 2- and 4-session concurrent allocation (exact contiguous values), explicit rollback/read-your-own-writes, lock handoff, server-side lock-wait timeout with exact error text, waiter connection reuse, and no value consumption after timeout.QA notes
Please run the new distributed case
test/distributed/cases/sequence/issue_28246.sqland the existing sequence group. Verify concurrentNEXTVALfrom independent sessions returns every value exactly once, rollback does not consume a value, lock timeout returns a typed timeout error, and the same connection remains usable afterward.Risk / limitations
The change moves sequence metadata writes into the caller transaction, which is required for atomicity and may make lock conflicts visible to the outer statement retry path. No new goroutine, RPC wait, or unbounded cache is introduced. The 55-machine client-cancellation probe is intentionally not used as the public oracle because the MySQL driver may close the connection while the server is still finishing the canceled query; cancellation propagation is covered deterministically at the internal boundary and server-side lock-timeout path instead.