Skip to content

proxy: reject backend greetings with a mismatched connection ID - #33423

Open
iamlinjunhong wants to merge 3 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/loom/33376-20261127T085112-main
Open

iamlinjunhong wants to merge 3 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/loom/33376-20261127T085112-main

Conversation

@iamlinjunhong

@iamlinjunhong iamlinjunhong commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG

Which issue(s) this PR fixes:

What this PR does / why we need it:

Nine paired field timeouts showed different connection IDs at the Proxy and CN. The Proxy previously accepted the CN greeting and forwarded the client login, so the failure surfaced later as a backend authentication timeout. The field logs do not establish why the CN missed the connection preface.

The Proxy now checks the greeting against the ID it sent on that physical connection. A mismatch closes that candidate before forwarding login and lets the router try another eligible CN. The existing greeting-stage diagnostic includes both IDs and classifies the failure as non-timeout. A candidate rejected during the handshake closes before acquiring manager entries, so the source remains visible in the routing and drain indexes even when a Unix socket path and URL select the same CN. Closing a superseded backend also preserves the current owner's connection-ID entry. Loss of that entry on source export failure after the candidate has registered is a separate migration issue.

The comparison runs once when opening a backend connection, before SQL execution.

Validation

  • A real MySQL driver logged in through Proxy and directly to a proxy-enabled CN. Both connections executed SELECT 1 and SELECT CONNECTION_ID().
  • The full pkg/proxy suite passed normally and under -race. Isolated backend tests cover zero and nonzero IDs, closure before login, retry on a healthy alternative, and registration ownership during migration.
  • Go vet, molint, and incremental golangci-lint passed for pkg/proxy.
  • After rebasing onto official main at 0c162526d4, both .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s ./pkg/proxy and .agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=240s ./pkg/proxy passed at 82c5211f65. Git range-diff confirmed both patches were unchanged. The driver smoke and standalone static checks above were run before the rebase.
  • At 9140c88d81, the full pkg/proxy suite passed normally and under -race with .agents/skills/mo-dev/scripts/mo-cgo-test. The handshake test passed 71 race runs and the cache rebind test passed 100. The new same-CN socket alias case reproduced the lost drain entry before the fix and checks the drain index, routing index and connection ID after rejection. Go vet, molint and incremental golangci-lint passed for pkg/proxy.
  • The new regression uses a fake CN peer to validate Proxy rejection before login. The real-driver smoke above is evidence from before this change. The real-CN preface timing diagnosis is recorded in [Bug]: v4.2.8-hotfix-20261114 偶发后端认证超时,Proxy 在 read-auth-response 阶段触发 10 秒超时 #33376.

4.2-dev backport: #33424

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

@mergify

mergify Bot commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request once it meets the queue conditions

@iamlinjunhong
iamlinjunhong force-pushed the codex/loom/33376-20261127T085112-main branch from ed8ea76 to 82c5211 Compare November 28, 2026 04:23

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

Please close ownership on the new rejection path before merging. The greeting stage is the right place for the ID check, and the existing retry policy gives a bounded path to another eligible CN. The check adds one comparison per backend handshake. A single eligible CN still yields a fast connection failure in the mismatch case.

I reproduced the ownership failure under -race on the 4.2-dev backport at 1e91864079 and traced the same transfer, close, and drain path in this head. The backport's full pkg/proxy race suite passed before the added counterexample. The main CI preflight stopped at a GitHub installation rate limit.

The probe also found a separate existing ownership gap on 4.2-dev. If a different CN passes the greeting and auth, router.connect overwrites the connection-ID entry before migration commits. If source export then fails, candidate close removes the entry while the source remains live. This also failed on the clean 4.2-dev base. Please scope the PR's claim about failed migrations to the transition actually protected, or make registration transfer follow the existing migration commit point.

The two existing regression cases cover rejection before login, then retry and health accounting. Extend the ownership case to assert the drain and routing indexes as well as the ID entry. The issue's real-CN diagnostics establish the preface timing failure, and the PR's fake peer covers Proxy rejection. Keep those claims distinct.

Comment thread pkg/proxy/conn_manager.go
}
delete(m.connIDServers, cn.connID)
// A migration can have multiple backend connections with the same ID.
if m.connIDServers[cn.connID] == cn {

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 — A failed candidate can unregister the live tunnel from draining and routing. The migration exclusion compares the raw RemoteAddr().String() with the advertised SQL address, so /path/backend.sock and unix:///path/backend.sock can select the same CN UUID again. When the new mismatch path closes this unregistered candidate, disconnect still removes (CN UUID, tunnel) from both tunnel indexes. The ID guard preserves the old pointer, but both tunnel counts fall from 1 to 0. scaling.doScaling then misses the live tunnel. Make candidate cleanup release only its own resources and admission. Exercise the same-UUID address-alias case with the existing fixture and assert the source remains visible to draining.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 9140c88d81f88d9fdfe846904f39e08e380226c2. The connection tracks manager ownership only after the router registers it. On greeting rejection it closes the candidate and the router releases the selection reservation. The same-CN Unix path/URL fixture reproduced the missing drain entry before the fix. It now verifies that the live tunnel remains in both indexes, the connection ID still maps to its source, and the candidate closes before login. The focused and full Proxy race tests passed.

Comment thread pkg/proxy/server_conn.go Outdated
connID uint32
// expectedConnID is the ID in the ExtraInfo sent on this connection.
expectedConnID uint32
sentExtraInfo bool

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.

CNServer.connectContext returns a backend transport only after the ExtraInfo write succeeds. Every production serverConn comes through this constructor and always sets this flag. Its false branch exists for direct test construction. Enforce equality unconditionally at the backend greeting boundary and use the request-owned connection ID already carried by CNServer. The route updates that input only after handshake success. This keeps parser tests independent of test-only handshake state.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 9140c88d81f88d9fdfe846904f39e08e380226c2. The parser returns the decoded ID without connection state. The greeting handler always compares it with the request-owned CNServer ID written in ExtraInfo before sending login. The parser tests and zero- and nonzero-ID handshake cases passed.

@XuPeng-SH

XuPeng-SH commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · failed

Commit: 9140c88d81f88d9fdfe846904f39e08e380226c2

discussion-assessment.json is required before a review decision

@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

I reviewed the full diff of head 9140c88 versus origin/main (6 files, +248/-57) together with the existing review from XuPeng-SH, his inline threads, and the issue comments; the PR head and review history were re-checked and are unchanged. Both of his requests are addressed at this head and hold under static verification: parseConnID is now a stateless function returning the decoded ID, and readInitialHandshake compares the CN greeting against the CNServer connection ID carried in the ExtraInfo preface before any login bytes are forwarded. The new tunnelOwner.registered gate makes a rejected candidate close before it owns manager entries, so a same-UUID Unix socket/URL alias candidate preserves the live tunnel in the routing and drain indexes; the regression added in the final commit asserts the drain index, routing index and conn-ID entry survive rejection, and that closing a superseded backend preserves the current owner's conn-ID entry. The pointer-equality guard on the connIDServers delete stays equivalent to main across normal, cached-connection and temp-connection lifetimes: cache Push leaves a backend registered so Pop rebinding still updates the manager as on main, and post-registration migration failure keeps main's pre-existing entry-loss behavior that the PR description documents as a separate migration issue, which I did not re-raise. A greeting mismatch surfaces as a retryable non-timeout connect error; the clientConn retry loop excludes each failed CN by address, bounded by the candidate count, and leaves the CN health breaker untouched, matching the stated design. The CN echoes the ExtraInfo connection ID whenever it decodes the preface (receiveExtraInfo, present since April 2024), which is exactly the contract being enforced, so supported-release version skew is acceptable. Test limitation: the documented wrapper .agents/skills/mo-dev/scripts/mo-cgo-test exited 1 before compiling because this worktree lacks built cgo/libmo.dylib and thirdparties/install, and it refuses the primary worktree's prebuilt library since origin/main's native inputs diverged from this head; plain go vet ./pkg/proxy likewise exited 1 compiling cgo dependencies on missing headers (roaring.h, xxhash.h, usearch.h, jemalloc.h). Building those prerequisites was out of scope for this review, so the conclusions rest on static inspection, and the author's passing full pkg/proxy runs (normal and -race at this head) remain unverified by me. The go list -deps -test snapshot for ./pkg/proxy decoded cleanly with zero package and dependency errors across its 21 cgo packages, and gofmt is clean on the changed files. One non-blocking hardening finding is filed below; since it is the only finding, this review is a comment rather than a blocking request.

P2 - registerTunnel does not enforce the tunnelOwner closed/registered invariant (pkg/proxy/server_conn.go:426)

registerTunnel (pkg/proxy/server_conn.go:426) publishes the backend to connManager and sets tunnelOwner.registered=true while holding tunnelOwner, but it ignores tunnelOwner.closed and any prior registered value. closeTunnelOwnership is terminal, and RawConn's closeFn combined with the closeOnce wrapper means closeTunnelOwnership runs at most once, so a registration that happens after Close would create a manager entry with no remaining owner able to remove it: connManager.connect writes the connIDServers entry even when the tunnel argument is nil, and the guarded delete in connManager.disconnect only fires from closeTunnelOwnership, which has already executed. Today both call sites (router.go:487 test path and router.go:531 post-handshake) run while router.connect exclusively owns the serverConn, before any Close or RawConn handoff, and the handshake cancellation path deliberately closes only the raw transport, so a post-close registration is unreachable. The type's own contract, however, states a backend must have exactly one manager/tunnel owner at every instant, and sibling methods rebindTunnel and waitCacheReuseReady each defend explicitly against losing a race with Close. If a future caller registers a closed candidate (for example a retry path reusing a rejected serverConn), the leaked connection-ID entry would steer SelectByConnID-based admin traffic toward a dead connection until restart. Suggested hardening: make registerTunnel a no-op or return an error when tunnelOwner.closed is true or registered is already true. Non-blocking because the current call graph cannot reach the bad interleaving.

XuPeng-SH pushed a commit that referenced this pull request Nov 30, 2026
…n ID (#33424)

## What type of PR is this?

- [x] BUG

## Which issue(s) this PR fixes:

- #33376

## What this PR does / why we need it:

Nine paired field timeouts showed different connection IDs at the Proxy
and CN. The Proxy previously accepted the CN greeting and forwarded the
client login, so the failure surfaced later as a backend authentication
timeout. The field logs do not establish why the CN missed the
connection preface.

The Proxy now checks the greeting against the ID it sent on that
physical connection. A mismatch closes that candidate before forwarding
login and lets the router try another eligible CN. The existing
greeting-stage diagnostic includes both IDs and classifies the failure
as non-timeout. Its structured `connection_id` is the request ID sent in
ExtraInfo, including when the greeting is rejected. A candidate rejected
during the greeting has no connection-manager registration to remove.
Its cleanup preserves the live tunnel in the routing, drain, and
connection-ID indexes, including when a Unix socket address alias
selects the same CN. Closing a superseded backend also preserves the
replacement's connection-ID entry. A separate pre-existing case remains
when a candidate registers after a successful handshake and destination
migration then fails.

The comparison runs once when opening a backend connection, before SQL
execution.

### Validation

- A real MySQL driver logged in through Proxy and directly to a
proxy-enabled CN. Both connections executed `SELECT 1` and `SELECT
CONNECTION_ID()`.
- The full `pkg/proxy` suite passed normally and under `-race`. Isolated
backend tests cover zero and nonzero IDs, closure before login, retry on
a healthy alternative, and registration ownership during migration.
- Go vet, molint, and incremental golangci-lint passed for `pkg/proxy`.

After rebasing onto official `4.2-dev` (`57cd85573c`), both original
patches matched in `git range-diff`. On `1e91864079` (Go 1.26.4, Darwin
arm64), `mo-cgo-test -v -count=1 -timeout=180s ./pkg/proxy`,
`mo-cgo-test -race -v -count=1 -timeout=240s ./pkg/proxy`, and `go vet
-mod=readonly ./pkg/proxy` passed. The MySQL driver smoke test and lint
results above are from the original validation.

The review fix at `cfbd93c894` was tested on official `4.2-dev`
(`2bdc8daf52`) with Go 1.26.4 on Darwin arm64. `mo-cgo-test -count=1
-timeout=180s ./pkg/proxy` and `mo-cgo-test -race -count=1 -timeout=240s
./pkg/proxy` passed. Focused race runs passed 54 iterations for backend
greeting ownership and 100 for cached backend rebinding. `go vet
-mod=readonly ./pkg/proxy`, molint, and incremental golangci-lint
passed. The fake CN verifies Proxy rejection and index ownership. The
real-CN timing and MySQL driver observations above come from the earlier
validation.

The CI refresh at `19b151353a` rebases the three unchanged Proxy patches
onto official `4.2-dev` (`70bb7b3515`), which includes the catalog DDL
and focused restore test updates from #33458. On Darwin arm64 with Go
1.26.4, `mo-cgo-test -short -race -tags matrixone_test -p 1 -count=3`
passed both `TestDropAccountWithMinimumRowLockCount` and
`TestAlterPublicationExplicitTargetLockScope`. The complete `pkg/proxy`
suite passed in the same mode with `-count=1`. The earlier [Linux x86
run](https://github.com/matrixorigin/matrixone/actions/runs/46284766742)
passed Proxy but failed in the isolated catalog package, with a restore
race and an unlock fatal during CN startup. The [Linux x86 UT and CI
Required
checks](https://github.com/matrixorigin/matrixone/actions/runs/46342788817/attempts/2)
passed on `19b151353a`.

The [handshake diagnostic
follow-up](#33424 (review))
at `3e4969685b90` was validated on Darwin arm64 with Go 1.26.4. Before
the fix, two assertions reproduced a structured ID mismatch for request
IDs 0 and 42. After the fix, `TestRouter_BackendHandshakeConnectionID`
passed 20 repetitions under `-race -tags matrixone_test`. The full
`pkg/proxy` suite passed normally and under `-race -tags
matrixone_test`. Go vet, molint, and incremental golangci-lint passed.
Linux CI for this follow-up will run after push.

Main PR: #33423

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

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/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants