Repository navigation
fix(morpc): avoid stream sequence gaps for skipped responses - #25811
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? |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Request changes on current head cb05aff850b3fee9fa4b7a68aa1cba1e7c75af86. Moving sequence assignment after the skip/timeout checks fixes the reported gap, but the new cs.mu.RLock() in the write loop introduces a queue-saturation close deadlock.
[P1] Avoid the send / Close / write-loop RWMutex cycle
clientSession.send holds cs.mu.RLock() while it may block sending to the bounded 1024-entry cs.c (server.go:715-740). Close needs cs.mu.Lock() (server.go:620-623). This PR makes the write loop call assignStreamSequence, which also needs cs.mu.RLock() (server.go:418, server.go:749-763).
The following schedule forms a closed wait cycle:
- The write loop has already fetched a response batch. Producers refill
cs.c; one more sender blocks on the full channel while still holdingcs.mu.RLock. - A concurrent session
Closewaits forcs.mu.Lock. GoRWMutexblocks new readers once that writer is waiting. - The write loop reaches the fetched response and blocks in
assignStreamSequencewaiting forcs.mu.RLock. - The write loop cannot finish the batch and drain
cs.c; the sender cannot enqueue and release its old read lock;Closecannot acquire the write lock.
There is no guaranteed timeout escape: AsyncWrite calls send with context.Background(), and ClientSession.Write also accepts contexts without deadlines. This can permanently hang response writers and session cleanup under a slow connection / response burst plus concurrent close.
Please remove this lock cycle rather than adding a timeout. In particular, the write loop must not need a lock that Close waits for while send can hold that lock across a blocking queue operation. Add a deterministic regression that models an already-fetched response, refills cs.c, blocks another background-context sender, starts Close, and verifies sequence assignment/write progress and close both terminate.
Local checks: the PR's two focused race tests pass at -count=100, and the full pkg/common/morpc suite passes; neither currently exercises this saturated-queue schedule.
|
Addressed the queue-saturation deadlock on head The write loop no longer acquires Added
Validation passed: focused concurrency tests with |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Re-reviewed current head 26036f41b0c038ac5fa47c3cfb38d5044b181d8f. The previous P1 queue-saturation deadlock is fixed.
The write loop no longer acquires cs.mu; sent-stream membership/allocation now lives behind the independent sentStreamState lock, which is held only for bounded map transitions. The old cycle (send blocked on full queue while holding cs.mu.RLock -> Close waiting for cs.mu.Lock -> write loop waiting for a new cs.mu.RLock) is therefore broken. Close permanently seals and clears sequence state, and later start/next calls cannot resurrect it. Normal FinishStream retirement and session-close cleanup remain symmetric, while sequence assignment occurs only after filter/context/timeout checks.
The typed RemoteDispatchNotRegistered retry still preserves its wire code and terminal timeout; NoReportContext only suppresses expected retry log noise.
Local verification passed: saturated-queue/canceled-response race tests at -count=100, full pkg/common/morpc under -race, focused compile tests and race tests, plus build/vet for the changed packages. No blocking findings remain. GitHub CI for the latest merge is still running.
Merge Queue Status
This pull request spent 15 seconds in the queue, including 2 seconds running CI. Required conditions to merge
|
## Problem Client MORPC streams consumed request sequences before queued messages passed the write-loop filter and context checks. Skipping a canceled request could make the next control frame arrive as sequence 3 after sequence 1, causing the server to close the connection. The existing two-CN `TestIssue28313EmptyRemoteDispatch` reproduced this gap and `rpc stream closed` locally. Related: #28313, #25811 (the analogous server-response fix). The placement-probing INFO message cited in #28313 is not sufficient evidence of the cause. The local reproduction establishes this failure mechanism; it does not independently establish the exact trigger of the original deployment incident. ## Change - Assign request sequences in the single backend writer after skip checks. Keep stream ownership on the pooled Future and clear it on initialization/reset. - Use a separate sequence lock so assignment does not depend on the lifecycle lock held by a sender waiting for queue admission. - Seal sequence assignment on both explicit Close and transport termination. Old queued stream requests are rejected before writing to a replacement connection. - Treat encoding/transport Write and Flush failures as terminal for the backend. Fail the current batch, retire active streams, fail waiting responses, and drain queued Futures through the existing writer cleanup. Do not flush a batch after a Write failure. - Restore the output-buffer boundary and payload when custom-header encoding fails. - Broadcast terminal admission shutdown before acquiring stream lifecycle locks on both Write and Flush failure; share an idempotent stop notification with Close. ## Failure policy and review corrections Review identified two omissions in the initial implementation: the codec rechecks deadlines after sequence assignment, and connection-reset termination did not seal send-sequence state. Both are now covered at their production boundaries. Follow-up review found a shutdown wait cycle: a real Stream.Send can hold the stream read lock while waiting for space in the backend queue, while fatal writer cleanup waits for that stream's exclusive lock before draining the queue. Stream cancellation alone does not wake queue admission. The failure paths now close the admission stop signal first, releasing senders before stream termination. A sync.Once shares this terminal broadcast with concurrent/repeated Close; the writer does not call Close or join itself. Deterministic tests force a full queue and a real blocked Stream.Send for both Write and Flush failure, then assert sender completion, receiver termination, queued Future completion, writer exit, and repeated Close without caller cancellation. An encoding failure is not always reversible: payload encoding can already have written bytes directly to the socket. The backend therefore closes rather than rolling back a sequence and reusing potentially corrupted framing. This also fails other in-flight requests on that connection, including unary traffic. Recovery uses the existing backend replacement mechanism; this change adds no automatic request retry. Failures detected before entering transport encoding remain ordinary skipped requests and leave sequence continuity intact. ## Performance and compatibility Wire format is unchanged. Normal stream frames incur one short sequence-lock operation; unary frames do not acquire it. No new queues, goroutines, timers, per-row work, or logging are introduced. Failure cleanup is proportional to the outstanding batch/requests. No throughput benchmark was run; normal-path performance claims are based on the code changes, not a measured zero-regression guarantee. ## Validation Base: `fdc1e0ca8f9696ada9668408e8caffc1d3b7c924`. Deterministic tests cover skipped/canceled requests, explicit close, blocked send admission, old queued writes after transport termination, and batch cleanup on Write/Flush failure. The encoding test advances the deadline after sequence assignment and invokes the real codec; it verifies that later requests are not written and the failed batch is not flushed. The header test verifies buffer/payload restoration. - New review regression tests: each individually `-race -count=100`, passed. - Full-queue admission shutdown regression (Write and Flush): `-race -count=100`, passed after the follow-up correction. - Full MORPC package: normal and race, passed. - Full compile package and the original two-CN SQL case (10 repetitions): passed. - Dependent build, vet, and `git diff --check`: passed. The earlier 50-repeat SQL run predates these review corrections and is retained only as historical evidence. Local validation uses darwin/arm64 with the repository CGo wrapper; Linux CI remains separate evidence.
…rigin#25811) MORPC previously assigned stream response sequence numbers when responses entered the server send queue. If a queued response expired or was canceled before the write loop processed it, that response was skipped after already consuming its sequence number. The next valid response then reached the client with a gap, causing `sequence out of order` followed by `rpc stream closed`. This PR: - assigns stream sequence numbers in the single server write loop after filter, context, and timeout checks; - synchronizes write-time assignment with session close so retired sequence state cannot be missed or resurrected; - adds regression coverage for canceled responses and the close/assignment boundary; - suppresses automatic ERROR reporting for the expected, typed `RemoteDispatchNotRegistered` retry response while preserving its wire code and terminal timeout behavior. Validation: - `go test -race -count=100 -run "TestCanceledStreamResponseDoesNotCreateSequenceGap|TestAssignStreamSequenceRejectsClosedSession" ./pkg/common/morpc` - `go test -race -count=1 ./pkg/common/morpc` - `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 ./pkg/sql/compile` - focused compile race tests - `go build ./pkg/common/morpc ./pkg/sql/compile` - `go vet ./pkg/common/morpc ./pkg/sql/compile` Approved by: @XuPeng-SH
## Problem Client MORPC streams consumed request sequences before queued messages passed the write-loop filter and context checks. Skipping a canceled request could make the next control frame arrive as sequence 3 after sequence 1, causing the server to close the connection. The existing two-CN `TestIssue28313EmptyRemoteDispatch` reproduced this gap and `rpc stream closed` locally. Related: matrixorigin#28313, matrixorigin#25811 (the analogous server-response fix). The placement-probing INFO message cited in matrixorigin#28313 is not sufficient evidence of the cause. The local reproduction establishes this failure mechanism; it does not independently establish the exact trigger of the original deployment incident. ## Change - Assign request sequences in the single backend writer after skip checks. Keep stream ownership on the pooled Future and clear it on initialization/reset. - Use a separate sequence lock so assignment does not depend on the lifecycle lock held by a sender waiting for queue admission. - Seal sequence assignment on both explicit Close and transport termination. Old queued stream requests are rejected before writing to a replacement connection. - Treat encoding/transport Write and Flush failures as terminal for the backend. Fail the current batch, retire active streams, fail waiting responses, and drain queued Futures through the existing writer cleanup. Do not flush a batch after a Write failure. - Restore the output-buffer boundary and payload when custom-header encoding fails. - Broadcast terminal admission shutdown before acquiring stream lifecycle locks on both Write and Flush failure; share an idempotent stop notification with Close. ## Failure policy and review corrections Review identified two omissions in the initial implementation: the codec rechecks deadlines after sequence assignment, and connection-reset termination did not seal send-sequence state. Both are now covered at their production boundaries. Follow-up review found a shutdown wait cycle: a real Stream.Send can hold the stream read lock while waiting for space in the backend queue, while fatal writer cleanup waits for that stream's exclusive lock before draining the queue. Stream cancellation alone does not wake queue admission. The failure paths now close the admission stop signal first, releasing senders before stream termination. A sync.Once shares this terminal broadcast with concurrent/repeated Close; the writer does not call Close or join itself. Deterministic tests force a full queue and a real blocked Stream.Send for both Write and Flush failure, then assert sender completion, receiver termination, queued Future completion, writer exit, and repeated Close without caller cancellation. An encoding failure is not always reversible: payload encoding can already have written bytes directly to the socket. The backend therefore closes rather than rolling back a sequence and reusing potentially corrupted framing. This also fails other in-flight requests on that connection, including unary traffic. Recovery uses the existing backend replacement mechanism; this change adds no automatic request retry. Failures detected before entering transport encoding remain ordinary skipped requests and leave sequence continuity intact. ## Performance and compatibility Wire format is unchanged. Normal stream frames incur one short sequence-lock operation; unary frames do not acquire it. No new queues, goroutines, timers, per-row work, or logging are introduced. Failure cleanup is proportional to the outstanding batch/requests. No throughput benchmark was run; normal-path performance claims are based on the code changes, not a measured zero-regression guarantee. ## Validation Base: `fdc1e0ca8f9696ada9668408e8caffc1d3b7c924`. Deterministic tests cover skipped/canceled requests, explicit close, blocked send admission, old queued writes after transport termination, and batch cleanup on Write/Flush failure. The encoding test advances the deadline after sequence assignment and invokes the real codec; it verifies that later requests are not written and the failed batch is not flushed. The header test verifies buffer/payload restoration. - New review regression tests: each individually `-race -count=100`, passed. - Full-queue admission shutdown regression (Write and Flush): `-race -count=100`, passed after the follow-up correction. - Full MORPC package: normal and race, passed. - Full compile package and the original two-CN SQL case (10 repetitions): passed. - Dependent build, vet, and `git diff --check`: passed. The earlier 50-repeat SQL run predates these review corrections and is retained only as historical evidence. Local validation uses darwin/arm64 with the repository CGo wrapper; Linux CI remains separate evidence.
…rigin#25811) MORPC previously assigned stream response sequence numbers when responses entered the server send queue. If a queued response expired or was canceled before the write loop processed it, that response was skipped after already consuming its sequence number. The next valid response then reached the client with a gap, causing `sequence out of order` followed by `rpc stream closed`. This PR: - assigns stream sequence numbers in the single server write loop after filter, context, and timeout checks; - synchronizes write-time assignment with session close so retired sequence state cannot be missed or resurrected; - adds regression coverage for canceled responses and the close/assignment boundary; - suppresses automatic ERROR reporting for the expected, typed `RemoteDispatchNotRegistered` retry response while preserving its wire code and terminal timeout behavior. Validation: - `go test -race -count=100 -run "TestCanceledStreamResponseDoesNotCreateSequenceGap|TestAssignStreamSequenceRejectsClosedSession" ./pkg/common/morpc` - `go test -race -count=1 ./pkg/common/morpc` - `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 ./pkg/sql/compile` - focused compile race tests - `go build ./pkg/common/morpc ./pkg/sql/compile` - `go vet ./pkg/common/morpc ./pkg/sql/compile` Approved by: @XuPeng-SH
## Problem Client MORPC streams consumed request sequences before queued messages passed the write-loop filter and context checks. Skipping a canceled request could make the next control frame arrive as sequence 3 after sequence 1, causing the server to close the connection. The existing two-CN `TestIssue28313EmptyRemoteDispatch` reproduced this gap and `rpc stream closed` locally. Related: matrixorigin#28313, matrixorigin#25811 (the analogous server-response fix). The placement-probing INFO message cited in matrixorigin#28313 is not sufficient evidence of the cause. The local reproduction establishes this failure mechanism; it does not independently establish the exact trigger of the original deployment incident. ## Change - Assign request sequences in the single backend writer after skip checks. Keep stream ownership on the pooled Future and clear it on initialization/reset. - Use a separate sequence lock so assignment does not depend on the lifecycle lock held by a sender waiting for queue admission. - Seal sequence assignment on both explicit Close and transport termination. Old queued stream requests are rejected before writing to a replacement connection. - Treat encoding/transport Write and Flush failures as terminal for the backend. Fail the current batch, retire active streams, fail waiting responses, and drain queued Futures through the existing writer cleanup. Do not flush a batch after a Write failure. - Restore the output-buffer boundary and payload when custom-header encoding fails. - Broadcast terminal admission shutdown before acquiring stream lifecycle locks on both Write and Flush failure; share an idempotent stop notification with Close. ## Failure policy and review corrections Review identified two omissions in the initial implementation: the codec rechecks deadlines after sequence assignment, and connection-reset termination did not seal send-sequence state. Both are now covered at their production boundaries. Follow-up review found a shutdown wait cycle: a real Stream.Send can hold the stream read lock while waiting for space in the backend queue, while fatal writer cleanup waits for that stream's exclusive lock before draining the queue. Stream cancellation alone does not wake queue admission. The failure paths now close the admission stop signal first, releasing senders before stream termination. A sync.Once shares this terminal broadcast with concurrent/repeated Close; the writer does not call Close or join itself. Deterministic tests force a full queue and a real blocked Stream.Send for both Write and Flush failure, then assert sender completion, receiver termination, queued Future completion, writer exit, and repeated Close without caller cancellation. An encoding failure is not always reversible: payload encoding can already have written bytes directly to the socket. The backend therefore closes rather than rolling back a sequence and reusing potentially corrupted framing. This also fails other in-flight requests on that connection, including unary traffic. Recovery uses the existing backend replacement mechanism; this change adds no automatic request retry. Failures detected before entering transport encoding remain ordinary skipped requests and leave sequence continuity intact. ## Performance and compatibility Wire format is unchanged. Normal stream frames incur one short sequence-lock operation; unary frames do not acquire it. No new queues, goroutines, timers, per-row work, or logging are introduced. Failure cleanup is proportional to the outstanding batch/requests. No throughput benchmark was run; normal-path performance claims are based on the code changes, not a measured zero-regression guarantee. ## Validation Base: `fdc1e0ca8f9696ada9668408e8caffc1d3b7c924`. Deterministic tests cover skipped/canceled requests, explicit close, blocked send admission, old queued writes after transport termination, and batch cleanup on Write/Flush failure. The encoding test advances the deadline after sequence assignment and invokes the real codec; it verifies that later requests are not written and the failed batch is not flushed. The header test verifies buffer/payload restoration. - New review regression tests: each individually `-race -count=100`, passed. - Full-queue admission shutdown regression (Write and Flush): `-race -count=100`, passed after the follow-up correction. - Full MORPC package: normal and race, passed. - Full compile package and the original two-CN SQL case (10 repetitions): passed. - Dependent build, vet, and `git diff --check`: passed. The earlier 50-repeat SQL run predates these review corrections and is retained only as historical evidence. Local validation uses darwin/arm64 with the repository CGo wrapper; Linux CI remains separate evidence.
…rigin#25811) MORPC previously assigned stream response sequence numbers when responses entered the server send queue. If a queued response expired or was canceled before the write loop processed it, that response was skipped after already consuming its sequence number. The next valid response then reached the client with a gap, causing `sequence out of order` followed by `rpc stream closed`. This PR: - assigns stream sequence numbers in the single server write loop after filter, context, and timeout checks; - synchronizes write-time assignment with session close so retired sequence state cannot be missed or resurrected; - adds regression coverage for canceled responses and the close/assignment boundary; - suppresses automatic ERROR reporting for the expected, typed `RemoteDispatchNotRegistered` retry response while preserving its wire code and terminal timeout behavior. Validation: - `go test -race -count=100 -run "TestCanceledStreamResponseDoesNotCreateSequenceGap|TestAssignStreamSequenceRejectsClosedSession" ./pkg/common/morpc` - `go test -race -count=1 ./pkg/common/morpc` - `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 ./pkg/sql/compile` - focused compile race tests - `go build ./pkg/common/morpc ./pkg/sql/compile` - `go vet ./pkg/common/morpc ./pkg/sql/compile` Approved by: @XuPeng-SH
## Problem Client MORPC streams consumed request sequences before queued messages passed the write-loop filter and context checks. Skipping a canceled request could make the next control frame arrive as sequence 3 after sequence 1, causing the server to close the connection. The existing two-CN `TestIssue28313EmptyRemoteDispatch` reproduced this gap and `rpc stream closed` locally. Related: matrixorigin#28313, matrixorigin#25811 (the analogous server-response fix). The placement-probing INFO message cited in matrixorigin#28313 is not sufficient evidence of the cause. The local reproduction establishes this failure mechanism; it does not independently establish the exact trigger of the original deployment incident. ## Change - Assign request sequences in the single backend writer after skip checks. Keep stream ownership on the pooled Future and clear it on initialization/reset. - Use a separate sequence lock so assignment does not depend on the lifecycle lock held by a sender waiting for queue admission. - Seal sequence assignment on both explicit Close and transport termination. Old queued stream requests are rejected before writing to a replacement connection. - Treat encoding/transport Write and Flush failures as terminal for the backend. Fail the current batch, retire active streams, fail waiting responses, and drain queued Futures through the existing writer cleanup. Do not flush a batch after a Write failure. - Restore the output-buffer boundary and payload when custom-header encoding fails. - Broadcast terminal admission shutdown before acquiring stream lifecycle locks on both Write and Flush failure; share an idempotent stop notification with Close. ## Failure policy and review corrections Review identified two omissions in the initial implementation: the codec rechecks deadlines after sequence assignment, and connection-reset termination did not seal send-sequence state. Both are now covered at their production boundaries. Follow-up review found a shutdown wait cycle: a real Stream.Send can hold the stream read lock while waiting for space in the backend queue, while fatal writer cleanup waits for that stream's exclusive lock before draining the queue. Stream cancellation alone does not wake queue admission. The failure paths now close the admission stop signal first, releasing senders before stream termination. A sync.Once shares this terminal broadcast with concurrent/repeated Close; the writer does not call Close or join itself. Deterministic tests force a full queue and a real blocked Stream.Send for both Write and Flush failure, then assert sender completion, receiver termination, queued Future completion, writer exit, and repeated Close without caller cancellation. An encoding failure is not always reversible: payload encoding can already have written bytes directly to the socket. The backend therefore closes rather than rolling back a sequence and reusing potentially corrupted framing. This also fails other in-flight requests on that connection, including unary traffic. Recovery uses the existing backend replacement mechanism; this change adds no automatic request retry. Failures detected before entering transport encoding remain ordinary skipped requests and leave sequence continuity intact. ## Performance and compatibility Wire format is unchanged. Normal stream frames incur one short sequence-lock operation; unary frames do not acquire it. No new queues, goroutines, timers, per-row work, or logging are introduced. Failure cleanup is proportional to the outstanding batch/requests. No throughput benchmark was run; normal-path performance claims are based on the code changes, not a measured zero-regression guarantee. ## Validation Base: `fdc1e0ca8f9696ada9668408e8caffc1d3b7c924`. Deterministic tests cover skipped/canceled requests, explicit close, blocked send admission, old queued writes after transport termination, and batch cleanup on Write/Flush failure. The encoding test advances the deadline after sequence assignment and invokes the real codec; it verifies that later requests are not written and the failed batch is not flushed. The header test verifies buffer/payload restoration. - New review regression tests: each individually `-race -count=100`, passed. - Full-queue admission shutdown regression (Write and Flush): `-race -count=100`, passed after the follow-up correction. - Full MORPC package: normal and race, passed. - Full compile package and the original two-CN SQL case (10 repetitions): passed. - Dependent build, vet, and `git diff --check`: passed. The earlier 50-repeat SQL run predates these review corrections and is retained only as historical evidence. Local validation uses darwin/arm64 with the repository CGo wrapper; Linux CI remains separate evidence.
What type of PR is this?
Which issue(s) this PR fixes:
Fixes #25803
What this PR does / why we need it:
MORPC previously assigned stream response sequence numbers when responses entered the server send queue. If a queued response expired or was canceled before the write loop processed it, that response was skipped after already consuming its sequence number. The next valid response then reached the client with a gap, causing
sequence out of orderfollowed byrpc stream closed.This PR:
RemoteDispatchNotRegisteredretry response while preserving its wire code and terminal timeout behavior.Validation:
go test -race -count=100 -run "TestCanceledStreamResponseDoesNotCreateSequenceGap|TestAssignStreamSequenceRejectsClosedSession" ./pkg/common/morpcgo test -race -count=1 ./pkg/common/morpc.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 ./pkg/sql/compilego build ./pkg/common/morpc ./pkg/sql/compilego vet ./pkg/common/morpc ./pkg/sql/compile