Skip to content

fix(morpc): avoid stream sequence gaps for skipped responses - #25811

Merged
mergify[bot] merged 4 commits into
matrixorigin:mainfrom
aptend:fix/morpc-stream-sequence-gap
Jul 16, 2026
Merged

mergify[bot] merged 4 commits into
matrixorigin:mainfrom
aptend:fix/morpc-stream-sequence-gap

Conversation

@aptend

@aptend aptend commented Jul 16, 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 #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 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

@aptend
aptend requested review from XuPeng-SH and aunjgr as code owners July 16, 2026 09:53
@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 added the kind/bug Something isn't working label Jul 16, 2026
@matrix-meow matrix-meow added the size/S Denotes a PR that changes [10,99] lines label Jul 16, 2026

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

  1. The write loop has already fetched a response batch. Producers refill cs.c; one more sender blocks on the full channel while still holding cs.mu.RLock.
  2. A concurrent session Close waits for cs.mu.Lock. Go RWMutex blocks new readers once that writer is waiting.
  3. The write loop reaches the fetched response and blocks in assignStreamSequence waiting for cs.mu.RLock.
  4. The write loop cannot finish the batch and drain cs.c; the sender cannot enqueue and release its old read lock; Close cannot 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.

@aptend

aptend commented Jul 16, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the queue-saturation deadlock on head 245e60673.

The write loop no longer acquires cs.mu. Sent-stream sequence membership and allocation are now owned by a small terminal sentStreamState; its private lock is held only for short map/state transitions and never across queue operations, network I/O, or Future waits.

Added TestAssignStreamSequenceProgressesWhileCloseWaitsOnFullQueue, which deterministically:

  1. fills cs.c and blocks an AsyncWrite while it holds cs.mu.RLock;
  2. starts Close and observes the pending writer via TryRLock;
  3. verifies sequence assignment still progresses;
  4. releases queue capacity and verifies both sender and Close terminate.

Validation passed: focused concurrency tests with -race -count=100, full pkg/common/morpc under -race, compile package tests and focused race tests, build, vet, and an independent concurrency review.

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

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.

@mergify mergify Bot added the queued label Jul 16, 2026
@mergify

mergify Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-16 13:00 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-07-16 13:00 UTC · at 26036f41b0c038ac5fa47c3cfb38d5044b181d8f · squash

This pull request spent 15 seconds in the queue, including 2 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • github-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • 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 Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • 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

@mergify
mergify Bot merged commit ee84742 into matrixorigin:main Jul 16, 2026
23 of 24 checks passed
@mergify mergify Bot removed the queued label Jul 16, 2026
XuPeng-SH added a commit that referenced this pull request Sep 7, 2026
## 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.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…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
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## 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.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…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
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## 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.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…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
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## 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.

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.

[Bug]: ErrStreamClosed / context canceled on WITH RECURSIVE + bkpf/bseg join (jinpan payment_details_tree)

3 participants