Repository navigation
fix(proxy): preserve user variables across CN migration - #27180
mergify[bot] merged 29 commits into
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
aptend
left a comment
There was a problem hiding this comment.
Blocking semantic regression in mixed SET statements:
makeSetVarEvent drops user-variable assignments from the SQL that is retained for target replay, while the source frontend evaluates and applies SET assignments sequentially. The target then installs the final user-variable snapshot before replaying this system-only fragment. That changes the value seen by a system assignment when a later assignment in the same original statement updates the referenced user variable.
For example:
SET @mode = 'ANSI_QUOTES';
SET @@session.sql_mode = @mode, @mode = 'PIPES_AS_CONCAT';On the source, the second statement leaves sql_mode = 'ANSI_QUOTES' and @mode = 'PIPES_AS_CONCAT'. The proxy retains only set sql_mode = @mode; after migration the target first installs final @mode = 'PIPES_AS_CONCAT' and then replays that fragment, so sql_mode becomes PIPES_AS_CONCAT. The migration no longer preserves session state.
Please preserve the source-evaluated system-variable state (or otherwise preserve the original assignment dependency/order) and add a regression where a system assignment reads a user variable that is changed by a later assignment in the same SET.
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
Independent v22 migration regressions remain. The existing unresolved aptend mixed-SET finding is intentionally not duplicated.
P1 - Typed migrations silently lose state on pre-v22 target CNs (pkg/proxy/conn_migration.go:94)
When the source marks UserDefinedVarsExported, the proxy skips legacy raw SET replay and sends only the system projection. A pre-v22 target ignores the new typed fields, and its pre-change Migrate path does not consume SetVarStmts, so migration can succeed while losing user and system variables instead of failing closed. Target capability must be negotiated before taking this branch.
P1 - SET NAMES is omitted from v22 migration (pkg/proxy/event.go:170)
The parser represents SET NAMES as SetNames=true and System=false, so this filter produces no systemStmt. Since v22 skips setVarStmts and the typed snapshot contains only user variables, the target never reapplies SET NAMES and session charset settings revert after migration. The legacy path replayed the raw statement.
P2 - Canonical replay changes @@transaction_isolation scope (pkg/proxy/event.go:176)
tree.String drops VarAssignmentExpr.TxnScope. SET @@transaction_isolation is parsed as TransactionScopeNext, but the generated statement becomes SET transaction_isolation = ..., which is session-scoped on the target. The source's next-transaction isolation behavior therefore changes across migration; raw replay preserved this distinction.
01b8b77 to
04a3a12
Compare
|
Addressed the new P1 finding from @gouhongshen on exact head
@gouhongshen Please re-review this exact head. |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
Earlier blockers around mixed SET ordering, typed snapshots, side effects, protocol/fallback handling, replayability propagation, and marker overwrites are fixed. The prior next-transaction isolation blocker is only partially fixed: successful consumption now clears the marker, but cancellation through a session-scoped isolation assignment still leaves stale unreplayability and remains blocking.
P1 - Clear next-isolation replayability when the pending override is cancelled (pkg/frontend/txn.go:363)
Author response: the new code clears migrationNextTxnIsolationKey after createTxnOpUnsafe successfully consumes a pending next-transaction isolation override, with a regression test for that path.
Why this remains blocking: setSessionTxnIsolation clears th.hasNextTxnIsolation when a later session-scoped assignment replaces/cancels the pending override, but it does not clear migrationNextTxnIsolationKey. For example, SET TRANSACTION ISOLATION LEVEL READ COMMITTED followed by captured SET @@session.transaction_isolation = 'REPEATABLE-READ' leaves no pending next-transaction state, yet hasUnreplayableMigrationSystemVars() remains true. The source then advertises SystemVariablesReplayable=false, and the proxy rejects migration to pre-v22 CNs before raw replay. Clear the marker atomically on every path that clears the pending override, or derive replayability from the actual pending state, and add a regression covering cancellation plus pre-v22 migration admission.
aptend
left a comment
There was a problem hiding this comment.
Deep re-review of exact head e192fb5dd74c1634b07d939609263d70fec72e70 with the complete replayability review history. The reported consumption path is fixed, but another transition clears the same pending state without clearing its marker.
[P1] Clear the next-transaction marker when a session isolation assignment supersedes it — pkg/frontend/txn.go:357-363.
setSessionTxnIsolation clears hasNextTxnIsolation, so a later SET SESSION transaction_isolation = ... cancels a pending one-shot SET TRANSACTION ISOLATION LEVEL .... The new fix clears migrationNextTxnIsolationKey only from createTxnOpUnsafe; this superseding path leaves the old false marker behind. The captured session assignment re-marks only the ordinary transaction_isolation key, so hasUnreplayableMigrationSystemVars() stays true even though the pending override no longer exists and the raw history is otherwise complete. A pre-v22 migration is then rejected at pkg/proxy/conn_migration.go:117-120, creating the same mixed-version availability regression after a different valid lifecycle transition.
I reproduced this through production paths: handleSetTransaction for standalone SET TRANSACTION ISOLATION LEVEL READ COMMITTED, followed by captured doSetVar for SET SESSION transaction_isolation = REPEATABLE-READ. The transaction handler no longer has pending next-transaction state, but the final assertion that migration system state is replayable fails deterministically. Please clear or derive the special marker whenever pending next-transaction state is superseded, and add this transition as a control beside the consumption regression.
git diff --check is clean; the newly added consumption regression passes under the controlled CGo test command, while the diagnostic supersession regression fails at the stale-marker assertion.
|
Addressed the new P1 finding from @gouhongshen on exact head
@gouhongshen Please re-review this exact head. |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
The prior blocker on cancelling a pending next-transaction isolation override is fixed at 5bac044: the session-scoped assignment now clears the stale replayability state, with a regression test confirming legacy migration admission. Earlier consumed-override, snapshot, side-effect, protocol, and fail-closed blockers were also resolved; no current finding remains. Focused local tests could not compile because xxhash.h and roaring.h are unavailable.
|
Resolved the merge conflict by merging The resolution preserves upstream typed user-variable planning and the PR's replayability contract. The migration snapshot now carries Validation on exact head
Please review exact head |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
The previous blocker around stale next-transaction isolation replayability is fixed in 5bac044, and the merge conflict resolution preserves the typed-variable and replayability changes. No prior blocking finding remains. One non-blocking interoperability gap is noted below; the current behavior fails closed rather than silently losing state.
P2 - Encode JSON values produced by SELECT INTO (pkg/frontend/user_var_migration.go:378)
The base branch's SELECT INTO path stores JSON results as bytejson.ByteJson with Type=T_json. During v22→v22 migration, snapshotUserDefinedVars reaches this default encoder case and returns an unsupported-type error; routine migration only tolerates size-limit errors, so a valid SELECT JSON_OBJECT() INTO @j aborts migration. Add an explicit JSON wire representation and round-trip regression. This is non-blocking because the current fail-closed behavior prevents silent state loss, and SELECT INTO is outside the PR's stated scalar-subquery scope.
aptend
left a comment
There was a problem hiding this comment.
Deep re-review of exact head fa2acbc14febb94e6a1ad14206ae3476606a3c6b with the complete history. The previous next-transaction cancellation blocker remains fixed and the merge preserves the newly typed user-variable state, but the integrated SELECT ... INTO @var path exposes one unsupported runtime representation.
[P1] Support JSON values in the typed user-variable snapshot — pkg/frontend/user_var_migration.go:307-378.
SELECT json_col INTO @j is now a valid producer of user-variable state. Its output path stores T_json as bytejson.ByteJson (pkg/frontend/output.go:65-67), and the collector installs that value unchanged with the exact JSON plan.Type. During connection export, snapshotUserDefinedVars passes the value to encodeUserDefinedVarValue, but this switch has no bytejson.ByteJson case and reaches the unsupported-type error. As a result, any otherwise valid connection holding a JSON variable created through SELECT INTO cannot migrate at all.
I reproduced this deterministically on the exact head with the same production state (Value: bytejson.ByteJson, Type: T_json): snapshotUserDefinedVars fails with internal error: unsupported user variable type bytejson.ByteJson in connection migration. Please add a lossless JSON codec on both encode and decode, and cover a JSON SELECT-INTO value through snapshot/protobuf/restore so the dynamic value and semantic type both survive.
The diagnostic test was removed. Existing focused frontend/proxy migration tests pass under the required CGo/thirdparties environment, and git diff --check is clean.
|
Addressed the JSON user-variable migration blocker on exact head
Validation:
|
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
The incremental range only adds JSON support and tests. It fixes Aptend’s missing ByteJson case for ordinary JSON; earlier protocol, replayability, overflow, side-effect, and cancellation blockers remain fixed. The earlier pending-isolation omission is fixed, but internal PREPARE replay still consumes the restored one-shot state. The new JSON codec also is not lossless for typed ByteJson subtypes, a distinct issue from the prior unsupported-ByteJson finding.
P1 - Preserve pending isolation across prepared-statement replay (pkg/frontend/session.go:2844)
When a typed snapshot contains NextTransaction, this restores the one-shot isolation override before the PrepareStmts loop at lines 2902-2909. Migrated PREPARE statements execute through doComQuery and executeStmtWithWorkspace, which starts a transaction even during migration. TxnHandler.createTxnOpUnsafe treats tree.PrepareStmt as consuming next-transaction isolation and clears hasNextTxnIsolation after the internal transaction succeeds. A source session with an existing prepared statement and an idle SET TRANSACTION ISOLATION LEVEL READ COMMITTED therefore migrates successfully, but its next real transaction silently uses the default/session isolation. This is distinct from the fixed omission and cancellation-marker issues. Preserve or reapply the override after PREPARE replay, or make migration-internal PREPARE non-consuming, with a regression covering both states.
P1 - Preserve typed JSON subtypes during migration (pkg/frontend/user_var_migration.go:359)
The new ByteJson case serializes through MarshalJSON, which is a presentation format, then decode reconstructs with ParseStringToByteJson. That loses supported internal subtypes: TpCodeDecimal 1.20 becomes a floating-point JSON number, DATE/TIME/DATETIME become ordinary strings, and Opaque/Bit values become base64 strings. These values are reachable through CAST(... AS JSON) followed by SELECT ... INTO @var; the collector preserves the original ByteJson subtype. After migration, JSON_TYPE(@var), comparisons, and casts can differ even though migration succeeds. Use a type-preserving JSON representation and add round-trip coverage for decimal, temporal, opaque, and bit subtypes; this is distinct from the prior missing ByteJson switch case.
…ser-var-migration
aptend
left a comment
There was a problem hiding this comment.
Deep re-review of the exact head and the full migration/replayability history. The prior JSON-unsupported failure is fixed for ordinary JSON, but two reachable state-preservation gaps remain.
|
Implemented and pushed at
Validation on the current worktree:
Please re-review current head |
aptend
left a comment
There was a problem hiding this comment.
Deep re-review of the exact head with the complete migration and transaction-isolation history. Both blockers from the prior round are fixed: the typed ByteJson representation preserves semantic subtypes, and migration-internal PREPARE replay no longer consumes the restored one-shot isolation. Full frontend/proxy tests and the query protobuf package check pass. A related source-side PREPARE lifecycle gap remains blocking.
|
Addressed the ordinary-PREPARE isolation lifecycle gap on exact head
Added Validation on the final commit:
|
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
My prior blocking topics (migration-internal PREPARE isolation consumption and ByteJson subtype loss) are fixed, as are the earlier protocol, replayability, side-effect, overflow, and marker issues. Aptend’s ordinary-PREPARE consumption finding is also addressed and is not duplicated here. A distinct autocommit=0 lifecycle regression remains in the new blanket PREPARE rule.
P1 - Do not pin autocommit-off PREPARE to the session isolation (pkg/frontend/txn.go:1044)
This is distinct from the addressed ordinary-PREPARE consumption finding: it is a transaction-lifecycle regression when autocommit is disabled. Client PREPARE still runs through executeStmtWithWorkspace, which passes autoCommit=false to TxnHandler.Create; Commit then skips commitUnsafe for OPTION_NOT_AUTOCOMMIT unless needToFinishTransactionAtStatementEnd matches. No Prepare variant matches that helper, so PREPARE leaves its txnOp active. With this new branch, the pending NEXT override is not applied, so PREPARE is created with the session isolation (for example RC); the following SELECT/EXECUTE reuses that active txn instead of creating one with the pending SI override, and the override remains pending. Reproduce with session RC: SET autocommit=0; SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; PREPARE s FROM SELECT ?; SELECT ... . The added test manually removes and rolls back the PREPARE operator and only exercises default autocommit, so it misses the real lifecycle. Either finish the implementation-only PREPARE transaction under autocommit=0, or treat it as the user transaction and apply/consume NEXT consistently, with full lifecycle coverage for all three variants.
aptend
left a comment
There was a problem hiding this comment.
Deep re-review of the exact head with the complete migration and isolation history. The ordinary-autocommit PREPARE case is fixed, but the blanket non-consuming rule breaks the autocommit-off lifecycle.
|
CI note for the superseded head This is unrelated to the transaction lifecycle diff. The same test passes on |
aptend
left a comment
There was a problem hiding this comment.
Deep re-review of exact head a1e45a3de8bc0f0d20055d24a77fa422b5de9974 after reading all 33 historical reviews, 27 issue comments, author replies, and all four resolved review threads. I checked the incremental diff since my previous reviewed head 1c3decaed667390cde4e3cce7da75d4447e10870 and re-audited the integrated migration/replayability diff. The autocommit-aware PREPARE admission rule now closes the prior lifecycle gap: autocommit PREPARE keeps the one-shot isolation pending for the next application transaction, while PREPARE under autocommit=0 consumes it into the retained user transaction; all three PREPARE AST variants are covered. The earlier protocol negotiation, typed state, JSON subtype, replay-completeness, and migration-internal PREPARE fixes remain intact. No blocking issue found.\n\nValidation on this exact head: git diff --check is clean; focused transaction-isolation/migration tests and full ./pkg/frontend ./pkg/proxy ./pkg/pb/query pass under the required CGo/thirdparties environment. Current GitHub UT, SCA, coverage, proxy BVT, and multi-CN BVT checks are green.
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
The prior autocommit-off PREPARE lifecycle blocker is fixed: NEXT isolation is consumed only when the retained user transaction is created, with coverage for all three PREPARE forms. Earlier protocol, replayability/overflow, mixed-SET/charset/isolation, side-effect, JSON, and migration-PREPARE blockers are also fixed; none remain blocking or require a non-blocking comment.
Merge Queue Status
This pull request spent 2 hours 5 minutes 39 seconds in the queue, including 48 minutes 21 seconds running CI. Required conditions to merge
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #27054
What this PR does / why we need it:
Proxy connection migration previously reconstructed user-defined variables by replaying their original
SETstatements. The replay ran before the target CN restored the source database, so scalar subqueries could fail, and volatile expressions such asNOW()orRAND()could produce a different value.This change introduces MORPC v22 typed user-variable snapshots. The source CN exports evaluated values under the migration lifecycle lease; the target CN decodes the complete snapshot into temporary state and installs it atomically before replaying system-variable assignments. The restore order is now database, typed user variables, system variables, prepared statements, and finally
ROW_COUNT().Proxy keeps the complete legacy
SEThistory for v21 and below, and additionally tracks a system-only AST projection for v22. Typed migration metadata now carries replayability proof across v22 hops. If a typed system snapshot exceeds the bounded wire budget, a pre-v22 target uses complete raw replay while a v22 target fails closed instead of consuming an unsafe system-only projection. Connection-cacheResetSessionsemantics are unchanged and continue to clear user variables between clients.Compatibility matrix:
SETreplay; v21 remains reserved for lookup-only RIGHT DEDUPInvestigation controls: the complete MOTR case passed 20/20 times on isolated single-CN deployments at both the issue's bad revision (
eee0ae09...) and the investigated main revision (f9af0064...), with 2020/2020 statements passing per run. This isolates the defect to multi-CN Proxy migration rather than TIMESTAMP scalar-subquery evaluation itself.Validation:
09ecd8edd062...: the deterministic source-export migration regression fails because the evaluated variable is absent.96afcfa79d8...: the prior regression remains covered; replayability metadata survives typed restore, and oversized system snapshots split safely between pre-v22 raw replay and v22 fail-closed admission.-raceresult is claimed for this head because the local CGo toolchain is blocked before test execution.pkg/frontendandpkg/proxypackage tests pass through the repository CGo wrapper.ROW_COUNT()are covered.git diff --check, semantic preflight, and self-review pass on exact head96afcfa79d8...; direct build/vet remain gated by the same local CGo environment issue.DROP ACCOUNTtimeout followed by reconnect fallout; Utils Coverage was prerequisite fallout. The synchronized head has fresh CI pending.pkg/frontendandpkg/proxypackage tests pass through the repository wrapper; fresh Linux CI remains the unmodified environment gate.QA required: yes
BVT: N/A. Ordinary BVT cannot deterministically force a Proxy backend migration. QA should validate this in a multi-CN, dual-Proxy deployment with forced migration and the issue's serial/parallel MOTR workload.
CR follow-up (exact head
4b9e9ce632aebc8cc318bcaae480863797fc1eec)Addressed the two new P1 findings from
gouhongshensubmitted at2026-08-17T23:24:11Z:Replayable=falsewhen a later captured assignment overwrites a user variable previously written by an unobserved prepared or multi-statement SET.ScopeBothSET GLOBALassignment unreplayable for legacy migration, including rawSET GLOBAL autocommit=0andSET GLOBAL sql_mode=...; the source session value is not changed by the global assignment and cannot be restored by raw replay.Regression coverage uses production
doSetVarpaths:TestCapturedUserAssignmentAfterPreparedWriteRemainsUnreplayableTestRawGlobalScopeBothAssignmentIsMarkedUnreplayableValidation on this exact head:
pkg/frontend: PASSpkg/proxy: PASS-race -count=100PASSpkg/frontendandpkg/proxy:-race -count=1PASSgit diff --check: PASSmo-self-review: PASSmo-pr-preflight-review: PASS, clean diff hash567de0de25aeb2e520974490f8043d23a9b3c34cc298747b6adbf99a2c2563feCR follow-up (exact head
f1059459b29ed030fe3141841050412e93f8a51a)Addressed the new blocking system-variable replayability finding from
gouhongshensubmitted at2026-08-18T00:07:43Z:doSetVarnow snapshots replayability before applying aSETand preserves an earlier tracked unreplayable marker when a later captured assignment would otherwise mark it replayable.TestCapturedSystemAssignmentAfterPreparedWriteRemainsUnreplayable, which parses the prepared and captured SQL through the production frontend path.Validation on this exact head:
go test -mod=readonly -count=1 ./pkg/frontend: PASSgo test -mod=readonly -count=1 ./pkg/proxy: PASS-race -count=100: PASSgo test -mod=readonly -race -count=1 ./pkg/frontend: PASSgo test -mod=readonly -race -count=1 ./pkg/proxy: PASSgit diff --check: PASSmo-self-review: PASSmo-pr-preflight-review: PASS,semantic=PASS exact-head=f1059459b29ed030fe3141841050412e93f8a51a diff-hash=e4781fb61f49be1b0a30119955324390f0d7bddccc3dce40886e275f9163b634CR follow-up (exact head
e192fb5dd74c1634b07d939609263d70fec72e70)Addressed the new blocking next-transaction replayability finding from
gouhongshensubmitted at2026-08-18T01:08:02Z:SET TRANSACTION ISOLATION LEVEL ...override is consumed by a successful application transaction,createTxnOpUnsafenow clears both the pending override and its migration replayability marker.TestConsumedNextTransactionAssignmentBecomesReplayable, covering the productionhandleSetTransactionand transaction-admission paths.Validation on this exact head:
-race -count=50): PASSpkg/frontendandpkg/proxy: PASSgit diff --check: PASSmo-self-review: PASSmo-pr-preflight-review: PASS,semantic=PASS exact-head=e192fb5dd74c1634b07d939609263d70fec72e70 diff-hash=e52dfb0c53465764bc0e49d035cc9395bf2851c0b178724506a8ac71d353e4cbCR follow-up (exact head
5bac044368923ee3f1e2779be3ca12efef783c80)Addressed the follow-up P1 finding from
gouhongshensubmitted at2026-08-18T02:28:43Z:SetSessionSysVarnow clears the stalemigrationNextTxnIsolationKeyreplayability marker.TestCancelledNextTransactionIsolationRemainsReplayable, which parses both production SQL forms and verifies the migration response remains replayable for a legacy target.Validation on this exact head:
-race -count=50: PASSpkg/frontendandpkg/proxy: PASSgit diff --check: PASSmo-self-review: PASSmo-pr-preflight-review: PASS,semantic=PASS exact-head=5bac044368923ee3f1e2779be3ca12efef783c80 diff-hash=e5f85324618db803409b2564e487eaebc34b65372cf901fee48fd90ff36a33bfCR follow-up (exact head
fd1299910e367d5a60db7aa448ad79e56b41a090)Addressed the new blocking JSON user-variable migration finding from
aptendsubmitted at2026-08-19T06:24:48Z:bytejson.ByteJsonis now inferred asT_jsonfor untyped user-variable paths.plan.Literal_Jsonval, and decode restoresbytejson.ByteJsonwith strict literal-kind and JSON validation.TestUserDefinedVarMigrationRoundTripsJSON, which enters through the productionSELECT ... INTOuser-variable collector and verifies snapshot/restore; malformed JSON representations are also rejected.Validation on this exact head:
pkg/frontendnormal CGo tests: PASSgit diff --check: PASSmo-self-review: PASS; G-RACE-STRESS is not applicable to this sequential codec-only change.mo-pr-preflight-review: PASS,semantic=PASS exact-head=fd1299910e367d5a60db7aa448ad79e56b41a090 diff-hash=e660c825343415699560920e0c4b5e1a09b7a830af3403c63dfff1a13071b504