Skip to content

fix(proxy): preserve user variables across CN migration - #27180

Merged
mergify[bot] merged 29 commits into
matrixorigin:mainfrom
VioletQwQ-0:codex/issue-27054-user-var-migration
Aug 19, 2026
Merged

mergify[bot] merged 29 commits into
matrixorigin:mainfrom
VioletQwQ-0:codex/issue-27054-user-var-migration

Conversation

@VioletQwQ-0

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

Copy link
Copy Markdown
Collaborator

What type of PR is this?

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

Which issue(s) this PR fixes:

issue #27054

What this PR does / why we need it:

Proxy connection migration previously reconstructed user-defined variables by replaying their original SET statements. The replay ran before the target CN restored the source database, so scalar subqueries could fail, and volatile expressions such as NOW() or RAND() 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 SET history 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-cache ResetSession semantics are unchanged and continue to clear user variables between clients.

Compatibility matrix:

Effective protocol Behavior
v21 and below Existing complete raw SET replay; v21 remains reserved for lookup-only RIGHT DEDUP
v22 source and target Typed evaluated user-variable snapshot plus system-only replay
Typed payload received by a target below v22 Complete raw replay is used only when replayability metadata is true; otherwise migration fails closed before side effects

Investigation 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:

  • Base 09ecd8edd062...: the deterministic source-export migration regression fails because the evaluated variable is absent.
  • PR head 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.
  • Direct package compilation without the repository CGo wrapper remains blocked by pre-existing docfilter CGo symbols; the repository wrapper tests pass with an isolated docfilter overlay, while fresh Linux CI remains the environment gate.
  • No new full -race result is claimed for this head because the local CGo toolchain is blocked before test execution.
  • Source export, repeated value preservation, and MORPC transfer each pass 100 consecutive race-enabled runs.
  • v21-and-older legacy export/replay and fail-closed behavior for unproven replayability are covered; existing v21 RIGHT DEDUP planner/compile tests pass.
  • The CR follow-up adds exact regressions for v22→v22 replayability propagation, pre-v22 raw fallback, and v22 rejection of an oversized typed system snapshot; full pkg/frontend and pkg/proxy package tests pass through the repository CGo wrapper.
  • Typed round trips cover NULL, bool, signed/unsigned integers, floats, decimals, strings/binary metadata, enums, year, and supported arrays.
  • Cancellation, duplicate names, malformed values, unsupported types, oversize payloads, atomic decode, repeated migration, mixed user/system SET, ResetSession isolation, prepared statements, and ROW_COUNT() are covered.
  • git diff --check, semantic preflight, and self-review pass on exact head 96afcfa79d8...; direct build/vet remain gated by the same local CGo environment issue.
  • The previous-head pessimistic BVT failure was an unrelated multi-CN DROP ACCOUNT timeout followed by reconnect fallout; Utils Coverage was prerequisite fallout. The synchronized head has fresh CI pending.
  • Local macOS validation used an isolated header-resolution overlay because clean current main reproduces an unrelated docfilter CGo compile failure. Full pkg/frontend and pkg/proxy package 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 gouhongshen submitted at 2026-08-17T23:24:11Z:

  • Preserve Replayable=false when a later captured assignment overwrites a user variable previously written by an unobserved prepared or multi-statement SET.
  • Mark every ScopeBoth SET GLOBAL assignment unreplayable for legacy migration, including raw SET GLOBAL autocommit=0 and SET 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 doSetVar paths:

  • TestCapturedUserAssignmentAfterPreparedWriteRemainsUnreplayable
  • TestRawGlobalScopeBothAssignmentIsMarkedUnreplayable

Validation on this exact head:

  • Focused replayability tests: PASS
  • Full pkg/frontend: PASS
  • Full pkg/proxy: PASS
  • New focused tests: -race -count=100 PASS
  • pkg/frontend and pkg/proxy: -race -count=1 PASS
  • git diff --check: PASS
  • mo-self-review: PASS
  • mo-pr-preflight-review: PASS, clean diff hash 567de0de25aeb2e520974490f8043d23a9b3c34cc298747b6adbf99a2c2563fe
  • BVT: N/A — deterministic Proxy backend migration still requires a multi-CN dual-Proxy deployment; the existing QA validation boundary remains unchanged.

CR follow-up (exact head f1059459b29ed030fe3141841050412e93f8a51a)

Addressed the new blocking system-variable replayability finding from gouhongshen submitted at 2026-08-18T00:07:43Z:

  • doSetVar now snapshots replayability before applying a SET and preserves an earlier tracked unreplayable marker when a later captured assignment would otherwise mark it replayable.
  • Added 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: PASS
  • go test -mod=readonly -count=1 ./pkg/proxy: PASS
  • Focused migration tests with -race -count=100: PASS
  • go test -mod=readonly -race -count=1 ./pkg/frontend: PASS
  • go test -mod=readonly -race -count=1 ./pkg/proxy: PASS
  • git diff --check: PASS
  • mo-self-review: PASS
  • mo-pr-preflight-review: PASS, semantic=PASS exact-head=f1059459b29ed030fe3141841050412e93f8a51a diff-hash=e4781fb61f49be1b0a30119955324390f0d7bddccc3dce40886e275f9163b634
  • BVT: N/A — this is package-internal migration replay metadata; the production parser/doSetVar regression and owning-package migration tests exercise the reachable terminal gate.

CR follow-up (exact head e192fb5dd74c1634b07d939609263d70fec72e70)

Addressed the new blocking next-transaction replayability finding from gouhongshen submitted at 2026-08-18T01:08:02Z:

  • When a one-shot SET TRANSACTION ISOLATION LEVEL ... override is consumed by a successful application transaction, createTxnOpUnsafe now clears both the pending override and its migration replayability marker.
  • Added TestConsumedNextTransactionAssignmentBecomesReplayable, covering the production handleSetTransaction and transaction-admission paths.

Validation on this exact head:

  • Focused frontend migration regression: PASS
  • Focused race stress (-race -count=50): PASS
  • Full pkg/frontend and pkg/proxy: PASS
  • Full frontend/proxy race tests: PASS
  • Package list, build, and vet: PASS
  • git diff --check: PASS
  • mo-self-review: PASS
  • mo-pr-preflight-review: PASS, semantic=PASS exact-head=e192fb5dd74c1634b07d939609263d70fec72e70 diff-hash=e52dfb0c53465764bc0e49d035cc9395bf2851c0b178724506a8ac71d353e4cb
  • BVT: N/A — this is a package-internal transaction-admission marker; the production frontend regression and owning-package migration tests exercise the reachable terminal gate.

CR follow-up (exact head 5bac044368923ee3f1e2779be3ca12efef783c80)

Addressed the follow-up P1 finding from gouhongshen submitted at 2026-08-18T02:28:43Z:

  • When a session-scoped transaction-isolation assignment cancels a pending one-shot next-transaction override, SetSessionSysVar now clears the stale migrationNextTxnIsolationKey replayability marker.
  • Added TestCancelledNextTransactionIsolationRemainsReplayable, which parses both production SQL forms and verifies the migration response remains replayable for a legacy target.

Validation on this exact head:

  • Baseline exact-head regression failed with the stale marker; fixed focused regression: PASS
  • Focused transaction-isolation tests with -race -count=50: PASS
  • Full pkg/frontend and pkg/proxy: PASS
  • Full frontend/proxy race tests: PASS
  • Package list, build, and vet: PASS
  • git diff --check: PASS
  • mo-self-review: PASS
  • mo-pr-preflight-review: PASS, semantic=PASS exact-head=5bac044368923ee3f1e2779be3ca12efef783c80 diff-hash=e5f85324618db803409b2564e487eaebc34b65372cf901fee48fd90ff36a33bf
  • BVT: N/A — this is a package-internal migration marker; the production parser/transaction cancellation path and migration response terminal gate are directly exercised.

CR follow-up (exact head fd1299910e367d5a60db7aa448ad79e56b41a090)

Addressed the new blocking JSON user-variable migration finding from aptend submitted at 2026-08-19T06:24:48Z:

  • bytejson.ByteJson is now inferred as T_json for untyped user-variable paths.
  • Typed snapshots encode JSON through plan.Literal_Jsonval, and decode restores bytejson.ByteJson with strict literal-kind and JSON validation.
  • Added TestUserDefinedVarMigrationRoundTripsJSON, which enters through the production SELECT ... INTO user-variable collector and verifies snapshot/restore; malformed JSON representations are also rejected.

Validation on this exact head:

  • Focused JSON migration tests: PASS
  • Full pkg/frontend normal CGo tests: PASS
  • Controlled frontend build and vet with the repository CGo flags: PASS
  • git diff --check: PASS
  • mo-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
  • BVT: N/A — ordinary BVT cannot deterministically force a Proxy backend migration; the existing multi-CN dual-Proxy QA boundary remains unchanged.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

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

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 gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

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.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed the new P1 finding from @gouhongshen on exact head e192fb5dd74c1634b07d939609263d70fec72e70.

  • TxnHandler.createTxnOpUnsafe now clears the one-shot next-transaction isolation replayability marker when the pending override is successfully consumed.
  • Added TestConsumedNextTransactionAssignmentBecomesReplayable through the production handleSetTransaction and transaction-admission paths.
  • Focused, race-stress, full frontend/proxy, race frontend/proxy, list, build, vet, and git diff --check validations pass.
  • mo-self-review passes.
  • mo-pr-preflight-review passes: semantic=PASS exact-head=e192fb5dd74c1634b07d939609263d70fec72e70 diff-hash=e52dfb0c53465764bc0e49d035cc9395bf2851c0b178724506a8ac71d353e4cb.
  • BVT: N/A; this package-internal transaction-admission marker is covered by the production frontend regression and owning-package migration tests.

@gouhongshen Please re-review this exact head.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

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

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.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed the new P1 finding from @gouhongshen on exact head 5bac044368923ee3f1e2779be3ca12efef783c80.

  • Session.SetSessionSysVar now clears the stale migrationNextTxnIsolationKey replayability marker when a session-scoped transaction-isolation assignment cancels a pending one-shot override.
  • Added TestCancelledNextTransactionIsolationRemainsReplayable, covering both production SQL forms and the Routine.migrateConnectionFrom legacy-admission result.
  • Baseline exact-head regression failed with the stale marker; the fixed focused regression passes.
  • Focused race stress, full frontend/proxy normal and race tests, list, build, vet, and git diff --check pass.
  • mo-self-review passes.
  • mo-pr-preflight-review passes: semantic=PASS exact-head=5bac044368923ee3f1e2779be3ca12efef783c80 diff-hash=e5f85324618db803409b2564e487eaebc34b65372cf901fee48fd90ff36a33bf.
  • BVT: N/A; this package-internal migration marker is covered by the production parser/transaction cancellation path and migration response terminal gate.

@gouhongshen Please re-review this exact head.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

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.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Resolved the merge conflict by merging upstream/main at 621782d4634a36865bdb18c9fe3853bf70f43f1c into this PR.

The resolution preserves upstream typed user-variable planning and the PR's replayability contract. The migration snapshot now carries plan.Type, and the value codec covers DATE/TIME/DATETIME/TIMESTAMP plus the fixed UUID/TS/Rowid/Blockid representations. The focused round-trip matrix covers these concrete values.

Validation on exact head fa2acbc14febb94e6a1ad14206ae3476606a3c6b:

  • Semantic preflight: PASS (diff_hash=2fb9ad43ee9df25a45762e88b550cdf0f69a29111d6b0795057a8bf468c59805).
  • pkg/pb/query: PASS.
  • pkg/container/types: PASS.
  • Frontend package and race gates: blocked before test execution by the local CGo prerequisite (cgo/libmo.dylib); no local frontend pass is claimed.
  • BVT remains N/A because backend migration requires the existing multi-CN dual-Proxy QA environment.

Please review exact head fa2acbc14febb94e6a1ad14206ae3476606a3c6b.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

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

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.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed the JSON user-variable migration blocker on exact head fd1299910e367d5a60db7aa448ad79e56b41a090.

  • bytejson.ByteJson now infers to T_json for untyped user-variable paths.
  • Typed snapshots encode JSON through plan.Literal_Jsonval; decode restores bytejson.ByteJson and rejects wrong literal kinds or malformed JSON before installation.
  • Added TestUserDefinedVarMigrationRoundTripsJSON through the production SELECT ... INTO user-variable collector and snapshot/restore path.

Validation:

  • Focused JSON migration tests: PASS
  • Full pkg/frontend normal CGo tests: PASS
  • Controlled frontend build/vet with repository CGo flags: PASS
  • git diff --check: PASS
  • mo-self-review: PASS; no new concurrency/lifecycle path, so G-RACE-STRESS is not applicable.
  • mo-pr-preflight-review: PASS, semantic=PASS exact-head=fd1299910e367d5a60db7aa448ad79e56b41a090 diff-hash=e660c825343415699560920e0c4b5e1a09b7a830af3403c63dfff1a13071b504
  • BVT remains N/A because ordinary BVT cannot deterministically force a Proxy backend migration; the existing multi-CN dual-Proxy QA boundary is unchanged.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

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.

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

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.

Comment thread pkg/frontend/session.go Resolved
Comment thread pkg/frontend/user_var_migration.go Resolved
@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Implemented and pushed at faf8cd7f602.

  • Migration-internal PREPARE is now non-consuming for a restored one-shot transaction-isolation override; ordinary application PREPARE keeps the existing consuming behavior.
  • Typed ByteJson user variables now migrate through a T_json vector carrying the root type and raw data, with strict cardinality/representation validation and an owned decode copy. Legacy Literal_Jsonval payloads remain supported.

Validation on the current worktree:

  • TestSession_Migrate/typed_user_variables and TestUserDefinedVarMigrationPreservesJSONSubtypes pass, including the pre-fix reproductions and malformed-vector rejection.
  • Full pkg/frontend CGo tests, controlled CGo vet, focused adaptive race stress (-race -count=100), and full pkg/frontend race tests pass.
  • Semantic preflight: PASS semantic=PASS against upstream/main.

Please re-review current head faf8cd7f602.

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

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.

Comment thread pkg/frontend/txn.go Resolved
@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed the ordinary-PREPARE isolation lifecycle gap on exact head 1c3decaed667390cde4e3cce7da75d4447e10870.

statementConsumesNextTxnIsolation now treats PrepareStmt, PrepareString, and PrepareVar as implementation-only transaction admission. A client-issued PREPARE therefore uses the session isolation without consuming the pending one-shot override; the next application transaction still consumes it exactly once. The migration-internal PREPARE behavior remains covered by the existing migration regression.

Added TestPrepareDoesNotConsumeNextTransactionIsolation, covering parsed PrepareStmt, PrepareString, and PrepareVar, with the sequence SET TRANSACTION -> PREPARE -> application SELECT.

Validation on the final commit:

  • Focused frontend CGo test: PASS.
  • Focused -race -count=100: PASS.
  • Full pkg/frontend normal and race suites: PASS.
  • Controlled frontend build and vet: PASS.
  • git diff --check and semantic preflight: PASS.
  • BVT: N/A. This frontend transaction-admission lifecycle is not deterministically forceable through ordinary BVT; the production admission path is covered by the focused regression.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

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

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.

Comment thread pkg/frontend/txn.go Resolved
@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

CI note for the superseded head 1c3decaed667390cde4e3cce7da75d4447e10870: Matrixone CI / UT Test on Ubuntu/x86 failed only TestScoreTraversalWorkspaceExact in pkg/sql/colexec/table_function because the runner observed 13 allocations against a limit of 8.

This is unrelated to the transaction lifecycle diff. The same test passes on upstream/main with the shared CGo libraries and passes 20 consecutive times on the superseded PR head locally. I did not change the fulltext code or blindly rerun that obsolete head; fresh CI is queued for a1e45a3de8b.

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

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 gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

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.

@mergify

mergify Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-19 11:55 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-08-19 14:01 UTC · at a012f5d6973dcc58e73ac445871814b43353fe78 · squash

This pull request spent 2 hours 5 minutes 39 seconds in the queue, including 48 minutes 21 seconds running CI.

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

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/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.

5 participants