Skip to content

fix(proxy): defer migration while prepared cursors are active - #29191

Merged
XuPeng-SH merged 20 commits into
matrixorigin:mainfrom
daviszhen:codex/issue-29182-cursor-migration
Sep 25, 2026
Merged

XuPeng-SH merged 20 commits into
matrixorigin:mainfrom
daviszhen:codex/issue-29182-cursor-migration

Conversation

@daviszhen

@daviszhen daviszhen commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

Fixes #29182

What this PR does / why we need it:

  • Refuse CN session export while a prepared statement owns an active server cursor. The retained result and fetch offset are CN-local and absent from the migration snapshot; even an empty cursor remains active until final FETCH or close.
  • Add PreparedStmtCursorsChecked to the migration response and require it in Proxy, failing closed for old CNs during rolling upgrades. Migration resumes after cursor disposal.
  • Track FETCH response boundaries before generic OK parsing. Binary rows cannot supply transaction status. Track MaxPayloadSize logical-response continuations so a short row fragment that looks like EOF cannot admit transfer before the real terminator.
  • Add deterministic regressions for active and empty cursors, old-CN attestation absence, request/export admission ordering, exactly-once cursor cleanup, and pending-transfer forwarding/replacement in both EOF modes, including a 16 MiB split row.

Validation

  • Current head 0b9628e, merged with upstream/main, is MERGEABLE.
  • Focused race: go test -race -p 2 ./pkg/proxy ./pkg/frontend -run TestFinalFetch(ForwardingBeforeBackendReplacement|ExactMaxPayloadNeedsEmptyContinuation)|TestMigrateConnectionFromWaitsForCursorCloseRequest -count=10 -timeout=180s passed (proxy 2.318s, frontend 2.710s).
  • Exact-production-tree two-CN Docker LOG/TN/CN1/CN2/Proxy validation: committed Java Connector/J 8.0.27 and raw MySQL wire probes under test/manual/issue29182. The raw probe runs legacy and CLIENT_DEPRECATE_EOF modes; each returned 5,000 ordered rows with no loss or duplication and reused the same connection after final FETCH. Proxy log for the last run showed active-cursor refusal followed by one successful CN2-to-CN1 transfer on connection 1306 (legacy) and 1307 (deprecated).
  • The Docker service binary was built from f27383d; the only subsequent commit 0b9628e adds the raw probe and README, with no production source changes. The raw probe itself was compiled and run from the current head. Latest CI is running.

@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 →

@daviszhen

Copy link
Copy Markdown
Contributor Author

Local two-CN Docker integration verification at head cc5279a (Connector/J 8.3.0): launched an isolated LOG/TN/CN1/CN2/Proxy cluster using the PR binary. With useServerPrepStmts=true, useCursorFetch=true, and defaultFetchSize=13, read 5,000 ordered rows through Proxy while draining CN2. Proxy attempted transfer every 5 seconds; all attempts during the active cursor returned OkExpectedNotSafeToStartTransfer. After the cursor was exhausted, migration from CN2 to CN1 succeeded, and SELECT COUNT(*) on the same JDBC connection still returned 5,000.

For this local run, I changed only generated, ignored CN configs to advertise container IPs as SQL addresses so they matched the Proxy backend addresses. Before that test-only adjustment, transfer stopped earlier at query-address resolution and did not exercise the cursor guard. No tracked PR files changed.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] Preserve the FETCH response boundary until its actual terminator.\n\nIn pkg/proxy/tunnel.go:835, generic OK parsing runs before the FETCH-specific branch. A valid first binary row containing BIGINT 528384 is decoded as status 0x0810, clearing inFlight and marking the pipe outside a transaction. With a pending transfer intent, migration can then run before the remaining rows/EOF are forwarded. The source CN may already have completed the final FETCH and closed its cursor, so the new attestation passes; replacing the backend discards the unread response and leaves the client waiting.\n\nHandle FETCH before generic OK parsing, prevent binary rows from supplying transaction status, and add a deterministic final-FETCH/migration regression for both EOF modes. The CN ownership guard and fail-closed compatibility field otherwise look sound.\n\nReviewed exact head: cc5279a

@daviszhen

Copy link
Copy Markdown
Contributor Author

Addressed at exact head acf52d9. FETCH response tracking now runs before generic OK parsing, and the independent transaction-status parser accepts status only from the actual legacy/deprecated EOF terminator, never from binary rows. Added a deterministic final-FETCH test with BIGINT 528384, another row, and pending migration; transfer remains blocked until EOF in both modes. Local verification: go test ./pkg/proxy -run 'TestFinalFetchKeepsTransferBlockedUntilTerminator|TestTunnelRequestBoundaryTracker' -count=10 passed in the native toolchain container. CI is still running.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed exact head acf52d9 against df41cc2.

The previous P1 is fixed: FETCH rows no longer reach generic OK completion or supply transaction status.

Requesting changes for the remaining validation gap. The new regression calls tracking helpers directly; it does not exercise response forwarding/backend replacement. The CN test likewise closes cursors sequentially.

Please add deterministic coverage for final-FETCH forwarding with pending migration in both EOF modes, and cursor close/export competition with exactly-once cleanup. Assert complete ordered delivery and successful migration afterward, provide focused race evidence, and refresh the two-CN cursor-drain validation on this head. Package race CI passes, but the old-head integration result does not validate the changed FETCH/pipe path.

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

Reviewed the complete change at exact head acf52d9. The CN-side cursor attestation, rolling-upgrade fail-closed field, and FETCH packet classification are internally coherent, and exact-head CI is green. One R3 protocol/migration validation blocker remains: the only end-to-end two-CN cursor-drain result is from cc5279a, before the current FETCH forwarding fix. The current unit test bypasses the forwarding and backend-replacement lifecycle, so it cannot establish the client-visible no-loss/no-duplication contract on this head.

Comment thread pkg/proxy/tunnel_test.go Resolved
@daviszhen

Copy link
Copy Markdown
Contributor Author

Investigated the failed UT Coverage run 35682947706 at head 0b9628e. The only failed test was TestIssue28012And28013AcceptedCommitDuringStandaloneShutdown in pkg/tests/issues/isolated: its 5s wait for the TN drain fault point expired while the earlier CN shutdown took about 11s under coverage. The Coverage merge check then failed because that UT producer did not publish a complete profile; it is downstream, not a second failing test. Latest upstream/main already fixes this exact test by starting its SQL deadline after cluster admission and allowing 30s for the drain fault point. Merged that main into this PR without conflicts and pushed head fc6b0b0. Focused local coverage-mode reruns of the failed test passed once in 15.969s and then -count=3 in 56.946s. Fresh CI is running; no claim of full-CI success yet.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Follow-up on head fc6b0b0: the new Matrixone UT Coverage execution / UT Coverage on Ubuntu/x86 job has completed SUCCESS (run 35688141745, job 106619336098). The previously failing TestIssue28012And28013AcceptedCommitDuringStandaloneShutdown no longer blocks coverage production. The Coverage merge job and the other long-running checks have not finished yet; no further CI success is claimed.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Investigated the remaining failing check on head fc6b0b0 (run 35688141745). UT, UT Coverage, SCA, Proxy BVT, and pessimistic multi-CN BVT all passed. Coverage merging itself succeeded, but the changed-code gate reported 39/185 = 21.08% against the >75% requirement. Its per-file report identified test/manual/issue29182/raw_cursor_probe.go at 0% because that interactive external-cluster probe is not run by CI; modified production files were 93.94%-100% covered. Commit b01151b moves that probe to raw_cursor_probe.go.txt and updates its README to copy it to a temporary .go path before running. The CI parser includes *.go, so the manual example is no longer misclassified as uncovered executable PR code. The copied example builds successfully; no production code or unit tests changed. New CI is pending.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

GPT-6 high review — REQUEST_CHANGES

本轮未确认新的实现缺陷;此前发现的 FETCH 二进制行误判、16 MiB continuation EOF、pending transfer 竞争测试缺口及 cursor close/export admission barrier 均已修复。

仍有 1 项 P2 验证门槛未闭合:当前 head 的完整双 CN cursor-drain 证据已过期。旧记录使用服务版本 f27383d,而当前协议已发生会影响迁移链路的变化:

  • cursor attestation 已从 protobuf field 18 移到 field 20;
  • 新增 LAST_INSERT_ID 的源端、Proxy、目标端握手。

请在当前服务版本下刷新 live probe,至少证明:

  1. 两种 EOF 模式下 active cursor 会拒绝 migration;
  2. 完整 FETCH 数据按顺序交付;
  3. cursor 释放后 migration 成功;
  4. 同连接复用正常。

当前 head CI、frontend/proxy race 和 BVT 均通过,但没有找到覆盖上述当前协议 cursor-drain 探针的记录;本地 focused race 因不匹配的 libmo.dylib 未能执行。该项是证据缺口,不是已复现的运行时 bug。

@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

Follow-up review at head 1ea06ce (delta from previously reviewed 11b70c5 is the merge commit bc5a792/1ea06ce41c plus commit b08e6c8; the merge's remerge-diff is empty, so no conflict-resolution delta beyond upstream main arriving).

My prior blocker — FIXED. In review 5269086924 at 11b70c5 I reported P1: a 16 MiB split FETCH row whose continuation fragment begins with fe 00 00 10 08 was accepted by legacyEOFPacketStatus and responseMayCarryTxnStatus, so the proxy could arm transfer and read a transaction status before the real terminator arrived. Commit b08e6c8 fixes this at the root: trackServerResponse (pkg/proxy/tunnel.go:775-800) now records responseContinuation/responseNextSequence before any EOF/OK/ERR interpretation, fails closed to ambiguous on a sequence mismatch, clears responseContinuation only when a fragment is shorter than frontend.MaxPayloadSize, and the len(msg) >= mysqlHeadLen guard makes an empty continuation safe; resetTrackedRequestLocked (pkg/proxy/tunnel.go:702-709) clears the new fields; responseMayCarryTxnStatus (pkg/proxy/tunnel.go:900-919) rejects continuation and full-size packets outright and restricts FETCH status extraction to a real terminator; kickoff gates checkTxnStatus on it (pkg/proxy/tunnel.go:1529-1537). Deterministic regressions cover the exact scenario: TestFinalFetchExactMaxPayloadNeedsEmptyContinuation (pkg/proxy/tunnel_test.go:1340) and TestFinalFetchForwardingBeforeBackendReplacement (pkg/proxy/tunnel_test.go:1381), which uses real pipes, a pending transfer intent, replacement strictly after the terminator, and both EOF modes with and without a split row.

Earlier blockers of mine — FIXED. FETCH binary-row misparse (OK-shaped row prefix completing the response or supplying txn status) is fixed by the dedicated COM_STMT_FETCH branch that only accepts legacyEOFPacketStatus/eofOKPacketStatus terminators (pkg/proxy/tunnel.go:862-871) plus the responseMayCarryTxnStatus gate. The pending-transfer-before-replacement test gap is closed by the real-pipe test above. The close/export admission race is closed by beginOperationWithContext waiting under mc.cond while an in-flight request owns the session (pkg/frontend/migrate.go:109-121), with the test-only operationWaitHook, and by the authoritative CN gate st.cursor != nil -> OkExpectedNotSafeToStartTransfer plus PreparedStmtCursorsChecked = true (pkg/frontend/routine.go:829-845), with proxy fail-closed on a missing attestation (pkg/proxy/conn_migration.go:65-69).

Merge-conflict resolution verified. The conflict in MigrateConnFromResponse was resolved by renumbering this PR's attestation from field 18 to field 20 (proto/query.proto:605-609); the generated code is wire-consistent — struct tag varint,20 (pkg/pb/query/query.pb.go:3917), marshal tag 0xa0 0x1 (pkg/pb/query/query.pb.go:9687), case 20 unmarshal (pkg/pb/query/query.pb.go:22093-22110), and ProtoSize accounting (pkg/pb/query/query.pb.go:12622) — and main's LastInsertID = 18 is preserved. The LAST_INSERT_ID handshake changes in the diff range arrived through merged main (#29192) and are not authored by this PR.

Other reviewers' findings (not re-raised). XuPeng-SH's review 5279957632 at this same head concludes all implementation defects are fixed and leaves one open P2: the two-CN live-probe evidence is stale (recorded at f27383d, before the attestation field moved 18->20 and before the LAST_INSERT_ID handshake), so it should be re-run at the current head. The author has not yet replied; that finding belongs to XuPeng-SH and is recorded here as status only. aptend's inline real-forwarding validation request and XuPeng-SH's earlier P1/P2s are fixed per their own subsequent reviews.

Also checked clean. Cursor-EXECUTE single-EOF early completion (SERVER_STATUS_CURSOR_EXISTS) matches CN behavior in respCursorColumnDefs/cursorExecuteStatus and migration remains gated by the CN's authoritative attestation; full-size packets can never be terminators; an unsolicited large response while not in-flight resolves to ambiguous, which blocks transfer via hasUntransferableClientState; the 255->0 sequence rotation check is independent of the new tracking; manual probes under test/ are excluded from the license check and coverage, and go-sql-driver/mysql v1.9.3 was already in go.mod.

Every blocker from my prior reviews is fixed and verified against code and tests, and I have no remaining blocking or non-blocking findings of my own, so the verdict is APPROVE.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

REQUEST_CHANGES — P2 exact-head live validation remains outstanding.

The current code and deterministic proxy/frontend tests close the earlier FETCH row misclassification, 16 MiB continuation, pending-transfer ordering, and cursor-close/export admission defects. However, the required two-CN cursor-drain probe was last recorded on an older production head, before the cursor-attestation field moved from 18 to 20 and the LAST_INSERT_ID handshake arrived. I found no subsequent probe result at this exact head (db630c32c11ed10f8b6687e540f3572449840dfa). Please refresh the two-CN probe for both EOF modes, proving active-cursor migration refusal, ordered complete FETCH delivery, migration after cursor disposal, and same-connection reuse. This is an evidence gap, not a newly reproduced runtime defect.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Re-ran the live two-CN + Proxy cursor-drain probe on the current PR head db630c32c11ed10f8b6687e540f3572449840dfa (image matrixorigin/matrixone:issue29182-db630, isolated issue29182-live cluster; no stale service image).

Command:

probe_dir=$(mktemp -d)
cp test/manual/issue29182/raw_cursor_probe.go.txt "$probe_dir/raw_cursor_probe.go"
go run "$probe_dir/raw_cursor_probe.go" \
  -proxy 127.0.0.1:6101 -cn1 127.0.0.1:16101 \
  -cn1-id dd1dccb4-4d3c-41f8-b482-5251dc7a41bf \
  -cn2-id dd2dccb4-4d3c-41f8-b482-5251dc7a41be

Results (both modes):

  • legacy EOF: 5,000/5,000 ordered rows, no loss/duplication; same-connection PING succeeded after cursor disposal.
  • deprecated EOF: 5,000/5,000 ordered rows, no loss/duplication; same-connection PING succeeded after cursor disposal.
  • The probe restored both CNs to Working and dropped both temporary tables.

The exact-head Proxy log also shows the intended lifecycle for both connections: while the cursor was active, migration attempts failed closed with OkExpectedNotSafeToStartTransfer; after the final FETCH/cursor disposal, the next retry logged connection migrate from server (CN2) → connection migrate to server (CN1) and transfer to a new CN server. This closes the stale-head validation gap for active-cursor refusal, complete ordered delivery, post-disposal migration, and same-connection reuse.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

GPT-6 High deep review at exact head 28883b9: APPROVE. Previous blockers around FETCH framing/continuations, pending-transfer forwarding, and cursor-close/export synchronization are resolved by the current implementation and deterministic regressions. The author reran the live two-CN + Proxy probe on db630c3 (current production code; 28883b9 only merges main): both legacy and deprecated EOF modes delivered 5,000 ordered rows, refused migration while the cursor was active, migrated after cursor disposal, and preserved same-connection usability. Exact-head CI is green. No remaining blocking findings.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

APPROVE — no remaining production blocker found at cd54e9bf21b3672540b59b2d3ebae7a743ddc9e4, reviewed against current main / merge-base f53be4ceb785d3f52b8dd22c2f5e89058084cee1. All 12 changed files were reviewed; the review worktree is clean. One non-blocking P3 concerns cleanup in the Java manual probe (inline).

The original #29182 contract is closed by the combined CN and Proxy guards: an active cursor, including an empty result, prevents export; after cursor disposal, Proxy still preserves the complete FETCH response before backend replacement. The change is a focused repair of the existing migration contract, not a feature or major refactor requiring a new design document.

Prior technical comments:

Concern Current result
BIGINT 528384 binary row mistaken for OK/status Fixed: FETCH classification precedes generic OK completion, and only an actual FETCH terminator supplies transaction status.
16 MiB continuation mistaken for EOF Fixed: logical-response continuation and sequence tracking precede packet interpretation; full-size, EOF-shaped and empty continuation cases are covered. Sequence mismatch fails closed.
Helper-only test missed pending transfer/forwarding/replacement Fixed: the real pipe test sets transferIntent, holds the terminator before forwarding, checks zero backend builds, then observes one replacement and same-connection PING. Both EOF modes and split rows are covered.
Cursor close/export test did not prove admission competition Fixed: the barrier runs at the actual controller admission wait, and the test checks the cursor reservation is released exactly once before export resumes.
Stale two-CN validation after field renumbering / LAST_INSERT_ID handshake Closed by the author's db630c32 live-probe record: both EOF modes delivered 5,000 ordered rows, refused transfer while active, transferred afterward, and reused the socket. I compared that revision with this head: cursor admission, migration response schema/codec, Proxy framing/replacement, and probe sources are unchanged. Later prepared-type/rewrite/warning changes do not alter this parameter-free cursor scenario.
Cursor attestation collides with field 18 Fixed: schema, getter, size, marshal and unmarshal use field 20; LAST_INSERT_ID retains field 18. Independently decoded the generated descriptor and verified that adding this boolean is its only difference from main.

The existing inline discussion is resolved, and no prior technical blocker remains open in the code or evidence.

Unhappy-path and engineering review:

Closure Result
Cursor ownership / Q1 Request and lifecycle admission serialize the cursor read/close; rejected export preserves source ownership. FETCH completion/error, reset/re-execute and statement/session close retain existing effective cleanup.
Wait termination / Q2 Export admission wakes on request completion, routine close or context cancellation; migration RPC is bounded. Transfer gates are released on failed admission/replacement, and network close remains independent of the packet-forwarding path.
Bounds / Q3 The new response state is one boolean and one byte per tunnel; existing cursor row/byte limits remain effective. No cursor buffering, worker, queue or retry mechanism is added.
Compatibility / performance Missing attestation refuses migration. Packet work is constant-size classification plus a short existing-state mutex acquisition; there is no added payload copy or scan. No throughput benchmark was run, so no quantified performance claim is made.

Evidence verified and reused at this exact head: Linux UT/race job, including the checkpoint command selecting frontend and proxy under -race and its terminal status 0; SCA, golangci-lint 2.6.2 / Go 1.26.4, 0 issues; coverage UT producer reports passed, exit 0, 486 packages and no package/test failure events; Proxy and pessimistic multi-CN BVT checks passed. The focused race/interleaving and two-CN cursor evidence above was reused after checking semantic freshness. I did not repeat the expensive full suite or launch another cluster.

The implementation is proportionate: about 100 non-generated production diff lines, with most of the total diff being focused tests, manual probes and generated protobuf data. No production overengineering blocker found.

}
}
} finally {
workState(admin, cn1, 1);

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.

[P3, non-blocking] Make manual-probe cleanup independent on failure. If restoring CN1 throws SQLException here, Java skips the CN2 restore and DROP TABLE, leaving the isolated test cluster drained/dirty for the next run. In addition, an insert failure in lines 51-57 occurs before this finally block is entered, so the already-created table is retained. Register table cleanup immediately after creation, include population in that scope, and attempt each restore/drop even when another cleanup action fails while preserving the original exception. This affects the manual diagnostic harness, not the production cursor-migration fix.

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/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Proxy CN draining migrates active JDBC cursor and breaks COM_STMT_FETCH

5 participants