Skip to content

fix(morpc): avoid client stream sequence gaps - #28358

Merged
XuPeng-SH merged 5 commits into
mainfrom
codex/fix-28313-remote-dispatch-flake
Sep 7, 2026
Merged

XuPeng-SH merged 5 commits into
mainfrom
codex/fix-28313-remote-dispatch-flake

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

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.

@XuPeng-SH
XuPeng-SH requested a review from aptend as a code owner September 7, 2026 18:10
@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 →

@XuPeng-SH XuPeng-SH left a comment

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.

Deep review of 5e1b2f4 against fdc1e0c. Changes are required: one P1 liveness defect remains in the new fatal-write cleanup path. The previous encoding-failure and reset-send-sealing findings are addressed, but termination now waits on stream lifecycle locks before waking blocked admission. Reviewed the complete diff and the send, encode, queue, reset, termination, Future completion and pool-reuse paths. A temporary controlled test using the real Stream.Send -> doSend -> waitWrite and changeToStopping -> cancelActiveStreams paths reproduced the blocked dependency under race; explicit caller cancellation released it. The diagnostic test was removed afterward, and production code was not modified during this review. Existing normal/race/SQL validation was reused; current UT, SCA and BVT checks pass, which does not cover the missing full-queue/registered-stream combination. Submitting COMMENT because the authenticated account is the PR author; this is not an approval.

// Encoding may have written a partial frame (including directly
// to the socket). Never flush or reuse this connection after it.
rb.changeToStopping()
rb.cancelActiveStreams()

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.

[P1] Wake blocked admission before waiting for stream termination

With writeC full, Stream.Send holds s.mu.RLock while doSend waits in waitWrite on waitWriteC, stopWriteC, or the caller context. The new fatal Write path calls changeToStopping and then cancelActiveStreams; terminate cancels s.ctx, but the admission wait uses the caller context, and terminate then blocks acquiring s.mu.Lock. changeToStopping does not signal either admission channel. The sole writer can therefore no longer drain writeC or reach the defer that closes waitWriteC. The same ordering exists in the Flush-error branch at lines 669-670. Failure completion and connection teardown now depend on the caller deadline or an external Close.

Controlled reproduction: fill writeC, place a registered stream's real Send in waitWrite, then execute this termination sequence. It remains blocked; explicitly canceling the caller releases both Send and termination. The focused diagnostic passed under race by asserting this dependency.

Please seal admission and broadcast a terminal wakeup before cancelActiveStreams, using an idempotent shutdown signal shared with Close so subsequent Close cannot double-close the channel. Do not call synchronous rb.Close from its own write goroutine, since that can join itself. Preserve completion of fetched, queued, and already-sent Futures. Add a barrier-based full write-loop test with an actual registered stream and a sender already blocked on a full queue; both Write and Flush failure must release sender, receiver, and writer without canceling the caller. TestBackendWriteFailureRetiresBatch currently never populates activeStreams and has no blocked admission, so it cannot exercise this wait cycle.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Fixed the P1 shutdown wait cycle from review 5135126354 in commit 7ae28c2.

Both fatal Write and Flush paths now broadcast the admission stop signal before terminating active streams. This releases a real Stream.Send blocked on the full queue so it can drop its lifecycle read lock. A shared sync.Once makes this notification safe with repeated/concurrent Close; the writer never calls Close or joins itself.

The new deterministic regression drives the real backend writer and Stream.Send with a full queue, separately injects Write and Flush failure, and checks sender exit, stream termination, queued Future completion, writer exit, and repeated Close without relying on caller cancellation.

Validation on darwin/arm64 using the repository CGo wrapper:

  • New regression: race, 100 repetitions, passed.
  • Full MORPC package: normal and race, passed.
  • Full compile package: passed.
  • Original two-CN TestIssue28313EmptyRemoteDispatch: 10 repetitions, passed.
  • MORPC vet and git diff --check: passed.

The added stop broadcast runs only on failure/Close, not the normal send path. No new logging, goroutines, or retry behavior. PR body updated with the failure mechanism and correction. This is a fix follow-up, not an independent approval; CI for the new commit remains separate validation.

@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Sep 7, 2026
@XuPeng-SH
XuPeng-SH merged commit 040356c into main Sep 7, 2026
20 of 23 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/fix-28313-remote-dispatch-flake branch September 7, 2026 22:28
XuPeng-SH added a commit that referenced this pull request Sep 9, 2026
## Summary

HAKeeper can report a failed MORPC transport generation as
`ErrBackendClosed` instead of EOF. The managed client previously reset
that generation but returned the error directly, so a transient
control-plane disconnect escaped as a SQL failure during
`TestIssue26640CrossAccountRestoreRebindsPrivileges`.

This change:

- retries the transport-generation errors (`ErrBackendClosed`,
connect/admission failures, connection reset) through the caller's
existing deadline;
- makes `managedHAKeeperClient.Close` terminal, prevents late failures
from recreating a transport, and makes concurrent `Close` calls join the
same cleanup result;
- consolidates the retry regressions into deterministic table-driven
tests, including deadline, business-error, in-flight-close, and
concurrent-close cases.

The retry is bounded by every public HAKeeper request context. An
allocation whose response is lost may consume an ID range, as the
existing EOF retry already did, but the server's monotonic allocator
prevents duplicate IDs from being returned.

## Root cause and scope

- #28443 failed before its restore/privilege assertions. The embedded
LogService first reported checker/raft timing pressure, then MORPC
returned `backend connection closed` while allocating an ID. The failure
was a downstream control-plane transport error; the deeper first
scheduler/WAL/IO fault is not proven by that job.
- #28447 is a separate MORPC stream-sequence-gap failure. It was already
fixed by merged #28358, which is in this branch's base. The exact
regression test passes repeatedly on current main, so this PR
intentionally does not duplicate that dispatch implementation.

Fixes #28452

Related: #28443, #28447, #28313, #28358

## Validation

- `TestIssue26640CrossAccountRestoreRebindsPrivileges`: `-count=3`,
passed.
- `TestIssue28313EmptyRemoteDispatch`: `-count=5`, passed.
- HAKeeper retry/close focused tests: normal and `-race -count=100`,
passed.
- `pkg/logservice`: normal and race package runs passed with the known
unrelated flaky `TestNewServiceClosesStoreOnReplicaStartFailure`
excluded; that test still fails independently with listener address
collisions/store-close leakage.
- `go vet ./pkg/logservice` with the repository CGo flags and `git diff
--check`, passed.

## CI triage for run 34300098985

The source changes in this PR are limited to pkg/logservice. In the
exact-head CI run:

- Shared build, SCA, normal UT, Compose BVT, and Standalone BVT passed.
- The UT coverage producer failed only at the unrelated existing test
pkg/sql/compile/TestIssue27261StopSendingDuringParallelReaderBuildStaysGraceful,
which returned context canceled; the producer report recorded no build
failures and two failed events in pkg/sql/compile.
- The downstream coverage merge failed because the required UT producer
artifact was incomplete (prerequisites_ready=false); it did not
calculate a coverage verdict.
- The same TestIssue27261 test passed locally 10 times, and the PR
retry/close focused tests passed locally 20 times normally and 100 times
under -race; go vet and git diff --check passed.

No unrelated compile/pipeline change is included to mask this flaky
coverage-only failure. This PR was not rebased and the existing PR base
was not changed.
XuPeng-SH pushed a commit that referenced this pull request Sep 14, 2026
## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue #28378

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

Add regression coverage for queued stream cancellation, shuffle receiver
retirement, and distributed IVF query cleanup. Production fixes are
already present through #28358, the relevant dispatch/remote pipeline
changes in #28364, and #28539; this PR changes tests only and does not
establish their individual causal contribution to the original TKE
incident.

- Observe serialized MORPC sequence numbers after a queued message is
canceled. The identical test compiles on the #28358 parent and fails
with expected sequence 2 versus actual 3.
- Cover first, middle, last, and consecutive shuffle receiver
retirement, checking both subsequent sends and one-time notification.
Exercise query/connection cancellation during real receiver credit
waiting through the CN handler, preserving the terminal error and
releasing lifecycle registration.
- Add a two-CN IVF test with 256 128-dimensional vectors. The
representative L2 case exercises eight concurrent sessions with one
simultaneous query per session; cosine, normalized L2, and raw-vector
IP/normalized-query retain their per-distance lifecycle and result
checks. The test covers exact full-probe comparison, approximate-result
validity, empty results, and subsequent queries. Test preparation
failure uses the actual phase runner, transaction rollback, worker exit,
and database cleanup. Preparation and query budgets are cumulative but
separate; cleanup gets its own context. SQL pre-cancellation is not
presented as proof of active remote cancellation. The fixture provides
16 vectors per IVF list on average; Vector Index Scan selects Multi-CN
without a 65,536-row threshold, so the 256-row fixture preserves the
lifecycle and result oracles while bounding the owning package's race
cost.
- Extend test/distributed/cases/vector/vector_ivf_multicn_search.sql and
.result with cosine, raw-vector IP/normalized-query, empty-result, and
follow-up checks. The GROUP_CONCAT metadata expectation uses the
existing server TEXT mapping and Connector/J 8.0.15 metadata; results
were not regenerated blindly.

Validation (final file contents include the follow-up assertion, SCA,
coverage-budget, fixture-size, and concurrency-budget fixes; exact head
323daee; upstream base
07b2596; product base
2a6fe7f):

- macOS arm64, Go 1.26.4, repository CGo wrapper, GOMAXPROCS=4, test
package parallelism 1.
- New mechanism tests: ordinary 100 iterations and race 20 iterations
passed. MORPC, dispatch, and compile packages passed ordinary/race
checks; unchanged evidence was reused.
- Follow-up P2 validation:
TestRemoteNotifyCancellationReleasesCreditWaitAndRegistration passed
ordinary 100 iterations and race 20 iterations after asserting that
connection cancellation closes proc.Ctx, records a non-nil
ErrStreamClosed cause, and preserves it through repeated terminal
cleanup.
- After the follow-up edit, the complete owning ./pkg/sql/compile
package passed once under the race detector; no race report was emitted.
- Exact prior-head fixture validation: GOWORK=off go test -mod=readonly
-count=1 -timeout=15m -run '^TestIssue28378IVFFlatRemoteLifecycle$'
./pkg/tests/issues passed in 14.855s; the same exact test with -race and
a 20m timeout passed in 34.817s. After the first fixture-size change,
the 1,024-row test passed ordinary in 16.675s and race in 33.739s; after
the final 256-row/one-iteration change, it passed ordinary in 16.591s
and race in 24.467s.
- The MORPC parent counterexample validates the sequence mechanism. The
IVF integration test is regression coverage, not a deterministic
reproduction of the historical incident.
- Reviewer P2 response: the fixture was reduced from 65,536 to 256 rows
and the concurrent repeat count from two to one in 323daee. XuPeng-SH
measured the prior 65,536-row test at 573.55s in the exclusive -p 1
-race UT stage on parent head 7944a5b; the focused runs above measure
the latest local fixture at 16.591s ordinary and 24.467s race. These are
different environments and modes, so the numbers are reported as bounded
before/after evidence rather than a CI performance claim. The exact-head
CI run below provides the Linux cost measurement.
- Exact current-head CI run 34756863153 for f7cb131 passed Ubuntu UT,
SCA, UT Coverage, shared build, Proxy/Pessimistic BVT, and CI Required.
The subsequent exact-head run 34799486791 for 323daee passed on
attempt 2: Ubuntu UT, SCA, UT Coverage, shared build, Proxy/Pessimistic
BVT, Coverage, and CI Required are green. Its first attempt failed only
in the unrelated optools TestUTHeartbeatStopsCleanly with `WaitDelay
expired before I/O complete`; the failed Coverage chain passed on rerun
without code changes.
- Formal BVT: CN1 and CN2 JDBC entry points each passed 36/36
comparisons with full metadata checking. go vet, gofmt, and diff checks
passed.

Deployment evidence for the already-fixed product base, independently of
this new test commit:

- Old baseline run
https://github.com/matrixorigin/mo-nightly-regression/actions/runs/34352473993:
HNSW/L2/cosine/normalize errors were 0/1702/1266/588.
- Fixed-product run
https://github.com/matrixorigin/mo-nightly-regression/actions/runs/34464342049:
all four original million-vector SIFT128 cases completed with 100
terminals, five-minute measurements, and zero client errors. The five
data hashes match the failed baseline. Acceptance was checked from
artifact counters and error files, not only workflow success.

QA required: yes — distributed timing and deployed-workload acceptance.
Automated terminal coverage includes completed SQL assertions,
cancellation waiter exit, preserved terminal errors, registration
removal, and cleanup. QA should review the target release's inclusion of
the existing production fixes and the attached run evidence. First-error
query/stream/peer correlation and unique root-cause attribution remain
unavailable; this PR must not auto-close #28378.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
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
…gin#28453)

## Summary

HAKeeper can report a failed MORPC transport generation as
`ErrBackendClosed` instead of EOF. The managed client previously reset
that generation but returned the error directly, so a transient
control-plane disconnect escaped as a SQL failure during
`TestIssue26640CrossAccountRestoreRebindsPrivileges`.

This change:

- retries the transport-generation errors (`ErrBackendClosed`,
connect/admission failures, connection reset) through the caller's
existing deadline;
- makes `managedHAKeeperClient.Close` terminal, prevents late failures
from recreating a transport, and makes concurrent `Close` calls join the
same cleanup result;
- consolidates the retry regressions into deterministic table-driven
tests, including deadline, business-error, in-flight-close, and
concurrent-close cases.

The retry is bounded by every public HAKeeper request context. An
allocation whose response is lost may consume an ID range, as the
existing EOF retry already did, but the server's monotonic allocator
prevents duplicate IDs from being returned.

## Root cause and scope

- matrixorigin#28443 failed before its restore/privilege assertions. The embedded
LogService first reported checker/raft timing pressure, then MORPC
returned `backend connection closed` while allocating an ID. The failure
was a downstream control-plane transport error; the deeper first
scheduler/WAL/IO fault is not proven by that job.
- matrixorigin#28447 is a separate MORPC stream-sequence-gap failure. It was already
fixed by merged matrixorigin#28358, which is in this branch's base. The exact
regression test passes repeatedly on current main, so this PR
intentionally does not duplicate that dispatch implementation.

Fixes matrixorigin#28452

Related: matrixorigin#28443, matrixorigin#28447, matrixorigin#28313, matrixorigin#28358

## Validation

- `TestIssue26640CrossAccountRestoreRebindsPrivileges`: `-count=3`,
passed.
- `TestIssue28313EmptyRemoteDispatch`: `-count=5`, passed.
- HAKeeper retry/close focused tests: normal and `-race -count=100`,
passed.
- `pkg/logservice`: normal and race package runs passed with the known
unrelated flaky `TestNewServiceClosesStoreOnReplicaStartFailure`
excluded; that test still fails independently with listener address
collisions/store-close leakage.
- `go vet ./pkg/logservice` with the repository CGo flags and `git diff
--check`, passed.

## CI triage for run 34300098985

The source changes in this PR are limited to pkg/logservice. In the
exact-head CI run:

- Shared build, SCA, normal UT, Compose BVT, and Standalone BVT passed.
- The UT coverage producer failed only at the unrelated existing test
pkg/sql/compile/TestIssue27261StopSendingDuringParallelReaderBuildStaysGraceful,
which returned context canceled; the producer report recorded no build
failures and two failed events in pkg/sql/compile.
- The downstream coverage merge failed because the required UT producer
artifact was incomplete (prerequisites_ready=false); it did not
calculate a coverage verdict.
- The same TestIssue27261 test passed locally 10 times, and the PR
retry/close focused tests passed locally 20 times normally and 100 times
under -race; go vet and git diff --check passed.

No unrelated compile/pipeline change is included to mask this flaky
coverage-only failure. This PR was not rebased and the existing PR base
was not changed.
VioletQwQ-0 added a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#28378

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

Add regression coverage for queued stream cancellation, shuffle receiver
retirement, and distributed IVF query cleanup. Production fixes are
already present through matrixorigin#28358, the relevant dispatch/remote pipeline
changes in matrixorigin#28364, and matrixorigin#28539; this PR changes tests only and does not
establish their individual causal contribution to the original TKE
incident.

- Observe serialized MORPC sequence numbers after a queued message is
canceled. The identical test compiles on the matrixorigin#28358 parent and fails
with expected sequence 2 versus actual 3.
- Cover first, middle, last, and consecutive shuffle receiver
retirement, checking both subsequent sends and one-time notification.
Exercise query/connection cancellation during real receiver credit
waiting through the CN handler, preserving the terminal error and
releasing lifecycle registration.
- Add a two-CN IVF test with 256 128-dimensional vectors. The
representative L2 case exercises eight concurrent sessions with one
simultaneous query per session; cosine, normalized L2, and raw-vector
IP/normalized-query retain their per-distance lifecycle and result
checks. The test covers exact full-probe comparison, approximate-result
validity, empty results, and subsequent queries. Test preparation
failure uses the actual phase runner, transaction rollback, worker exit,
and database cleanup. Preparation and query budgets are cumulative but
separate; cleanup gets its own context. SQL pre-cancellation is not
presented as proof of active remote cancellation. The fixture provides
16 vectors per IVF list on average; Vector Index Scan selects Multi-CN
without a 65,536-row threshold, so the 256-row fixture preserves the
lifecycle and result oracles while bounding the owning package's race
cost.
- Extend test/distributed/cases/vector/vector_ivf_multicn_search.sql and
.result with cosine, raw-vector IP/normalized-query, empty-result, and
follow-up checks. The GROUP_CONCAT metadata expectation uses the
existing server TEXT mapping and Connector/J 8.0.15 metadata; results
were not regenerated blindly.

Validation (final file contents include the follow-up assertion, SCA,
coverage-budget, fixture-size, and concurrency-budget fixes; exact head
323daee; upstream base
07b2596; product base
2a6fe7f):

- macOS arm64, Go 1.26.4, repository CGo wrapper, GOMAXPROCS=4, test
package parallelism 1.
- New mechanism tests: ordinary 100 iterations and race 20 iterations
passed. MORPC, dispatch, and compile packages passed ordinary/race
checks; unchanged evidence was reused.
- Follow-up P2 validation:
TestRemoteNotifyCancellationReleasesCreditWaitAndRegistration passed
ordinary 100 iterations and race 20 iterations after asserting that
connection cancellation closes proc.Ctx, records a non-nil
ErrStreamClosed cause, and preserves it through repeated terminal
cleanup.
- After the follow-up edit, the complete owning ./pkg/sql/compile
package passed once under the race detector; no race report was emitted.
- Exact prior-head fixture validation: GOWORK=off go test -mod=readonly
-count=1 -timeout=15m -run '^TestIssue28378IVFFlatRemoteLifecycle$'
./pkg/tests/issues passed in 14.855s; the same exact test with -race and
a 20m timeout passed in 34.817s. After the first fixture-size change,
the 1,024-row test passed ordinary in 16.675s and race in 33.739s; after
the final 256-row/one-iteration change, it passed ordinary in 16.591s
and race in 24.467s.
- The MORPC parent counterexample validates the sequence mechanism. The
IVF integration test is regression coverage, not a deterministic
reproduction of the historical incident.
- Reviewer P2 response: the fixture was reduced from 65,536 to 256 rows
and the concurrent repeat count from two to one in 323daee. XuPeng-SH
measured the prior 65,536-row test at 573.55s in the exclusive -p 1
-race UT stage on parent head 7944a5b; the focused runs above measure
the latest local fixture at 16.591s ordinary and 24.467s race. These are
different environments and modes, so the numbers are reported as bounded
before/after evidence rather than a CI performance claim. The exact-head
CI run below provides the Linux cost measurement.
- Exact current-head CI run 34756863153 for f7cb131 passed Ubuntu UT,
SCA, UT Coverage, shared build, Proxy/Pessimistic BVT, and CI Required.
The subsequent exact-head run 34799486791 for 323daee passed on
attempt 2: Ubuntu UT, SCA, UT Coverage, shared build, Proxy/Pessimistic
BVT, Coverage, and CI Required are green. Its first attempt failed only
in the unrelated optools TestUTHeartbeatStopsCleanly with `WaitDelay
expired before I/O complete`; the failed Coverage chain passed on rerun
without code changes.
- Formal BVT: CN1 and CN2 JDBC entry points each passed 36/36
comparisons with full metadata checking. go vet, gofmt, and diff checks
passed.

Deployment evidence for the already-fixed product base, independently of
this new test commit:

- Old baseline run
https://github.com/matrixorigin/mo-nightly-regression/actions/runs/34352473993:
HNSW/L2/cosine/normalize errors were 0/1702/1266/588.
- Fixed-product run
https://github.com/matrixorigin/mo-nightly-regression/actions/runs/34464342049:
all four original million-vector SIFT128 cases completed with 100
terminals, five-minute measurements, and zero client errors. The five
data hashes match the failed baseline. Acceptance was checked from
artifact counters and error files, not only workflow success.

QA required: yes — distributed timing and deployed-workload acceptance.
Automated terminal coverage includes completed SQL assertions,
cancellation waiter exit, preserved terminal errors, registration
removal, and cleanup. QA should review the target release's inclusion of
the existing production fixes and the attached run evidence. First-error
query/stream/peer correlation and unique root-cause attribution remain
unavailable; this PR must not auto-close matrixorigin#28378.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
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
…gin#28453)

## Summary

HAKeeper can report a failed MORPC transport generation as
`ErrBackendClosed` instead of EOF. The managed client previously reset
that generation but returned the error directly, so a transient
control-plane disconnect escaped as a SQL failure during
`TestIssue26640CrossAccountRestoreRebindsPrivileges`.

This change:

- retries the transport-generation errors (`ErrBackendClosed`,
connect/admission failures, connection reset) through the caller's
existing deadline;
- makes `managedHAKeeperClient.Close` terminal, prevents late failures
from recreating a transport, and makes concurrent `Close` calls join the
same cleanup result;
- consolidates the retry regressions into deterministic table-driven
tests, including deadline, business-error, in-flight-close, and
concurrent-close cases.

The retry is bounded by every public HAKeeper request context. An
allocation whose response is lost may consume an ID range, as the
existing EOF retry already did, but the server's monotonic allocator
prevents duplicate IDs from being returned.

## Root cause and scope

- matrixorigin#28443 failed before its restore/privilege assertions. The embedded
LogService first reported checker/raft timing pressure, then MORPC
returned `backend connection closed` while allocating an ID. The failure
was a downstream control-plane transport error; the deeper first
scheduler/WAL/IO fault is not proven by that job.
- matrixorigin#28447 is a separate MORPC stream-sequence-gap failure. It was already
fixed by merged matrixorigin#28358, which is in this branch's base. The exact
regression test passes repeatedly on current main, so this PR
intentionally does not duplicate that dispatch implementation.

Fixes matrixorigin#28452

Related: matrixorigin#28443, matrixorigin#28447, matrixorigin#28313, matrixorigin#28358

## Validation

- `TestIssue26640CrossAccountRestoreRebindsPrivileges`: `-count=3`,
passed.
- `TestIssue28313EmptyRemoteDispatch`: `-count=5`, passed.
- HAKeeper retry/close focused tests: normal and `-race -count=100`,
passed.
- `pkg/logservice`: normal and race package runs passed with the known
unrelated flaky `TestNewServiceClosesStoreOnReplicaStartFailure`
excluded; that test still fails independently with listener address
collisions/store-close leakage.
- `go vet ./pkg/logservice` with the repository CGo flags and `git diff
--check`, passed.

## CI triage for run 34300098985

The source changes in this PR are limited to pkg/logservice. In the
exact-head CI run:

- Shared build, SCA, normal UT, Compose BVT, and Standalone BVT passed.
- The UT coverage producer failed only at the unrelated existing test
pkg/sql/compile/TestIssue27261StopSendingDuringParallelReaderBuildStaysGraceful,
which returned context canceled; the producer report recorded no build
failures and two failed events in pkg/sql/compile.
- The downstream coverage merge failed because the required UT producer
artifact was incomplete (prerequisites_ready=false); it did not
calculate a coverage verdict.
- The same TestIssue27261 test passed locally 10 times, and the PR
retry/close focused tests passed locally 20 times normally and 100 times
under -race; go vet and git diff --check passed.

No unrelated compile/pipeline change is included to mask this flaky
coverage-only failure. This PR was not rebased and the existing PR base
was not changed.
VioletQwQ-0 added a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#28378

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

Add regression coverage for queued stream cancellation, shuffle receiver
retirement, and distributed IVF query cleanup. Production fixes are
already present through matrixorigin#28358, the relevant dispatch/remote pipeline
changes in matrixorigin#28364, and matrixorigin#28539; this PR changes tests only and does not
establish their individual causal contribution to the original TKE
incident.

- Observe serialized MORPC sequence numbers after a queued message is
canceled. The identical test compiles on the matrixorigin#28358 parent and fails
with expected sequence 2 versus actual 3.
- Cover first, middle, last, and consecutive shuffle receiver
retirement, checking both subsequent sends and one-time notification.
Exercise query/connection cancellation during real receiver credit
waiting through the CN handler, preserving the terminal error and
releasing lifecycle registration.
- Add a two-CN IVF test with 256 128-dimensional vectors. The
representative L2 case exercises eight concurrent sessions with one
simultaneous query per session; cosine, normalized L2, and raw-vector
IP/normalized-query retain their per-distance lifecycle and result
checks. The test covers exact full-probe comparison, approximate-result
validity, empty results, and subsequent queries. Test preparation
failure uses the actual phase runner, transaction rollback, worker exit,
and database cleanup. Preparation and query budgets are cumulative but
separate; cleanup gets its own context. SQL pre-cancellation is not
presented as proof of active remote cancellation. The fixture provides
16 vectors per IVF list on average; Vector Index Scan selects Multi-CN
without a 65,536-row threshold, so the 256-row fixture preserves the
lifecycle and result oracles while bounding the owning package's race
cost.
- Extend test/distributed/cases/vector/vector_ivf_multicn_search.sql and
.result with cosine, raw-vector IP/normalized-query, empty-result, and
follow-up checks. The GROUP_CONCAT metadata expectation uses the
existing server TEXT mapping and Connector/J 8.0.15 metadata; results
were not regenerated blindly.

Validation (final file contents include the follow-up assertion, SCA,
coverage-budget, fixture-size, and concurrency-budget fixes; exact head
323daee; upstream base
07b2596; product base
2a6fe7f):

- macOS arm64, Go 1.26.4, repository CGo wrapper, GOMAXPROCS=4, test
package parallelism 1.
- New mechanism tests: ordinary 100 iterations and race 20 iterations
passed. MORPC, dispatch, and compile packages passed ordinary/race
checks; unchanged evidence was reused.
- Follow-up P2 validation:
TestRemoteNotifyCancellationReleasesCreditWaitAndRegistration passed
ordinary 100 iterations and race 20 iterations after asserting that
connection cancellation closes proc.Ctx, records a non-nil
ErrStreamClosed cause, and preserves it through repeated terminal
cleanup.
- After the follow-up edit, the complete owning ./pkg/sql/compile
package passed once under the race detector; no race report was emitted.
- Exact prior-head fixture validation: GOWORK=off go test -mod=readonly
-count=1 -timeout=15m -run '^TestIssue28378IVFFlatRemoteLifecycle$'
./pkg/tests/issues passed in 14.855s; the same exact test with -race and
a 20m timeout passed in 34.817s. After the first fixture-size change,
the 1,024-row test passed ordinary in 16.675s and race in 33.739s; after
the final 256-row/one-iteration change, it passed ordinary in 16.591s
and race in 24.467s.
- The MORPC parent counterexample validates the sequence mechanism. The
IVF integration test is regression coverage, not a deterministic
reproduction of the historical incident.
- Reviewer P2 response: the fixture was reduced from 65,536 to 256 rows
and the concurrent repeat count from two to one in 323daee. XuPeng-SH
measured the prior 65,536-row test at 573.55s in the exclusive -p 1
-race UT stage on parent head 7944a5b; the focused runs above measure
the latest local fixture at 16.591s ordinary and 24.467s race. These are
different environments and modes, so the numbers are reported as bounded
before/after evidence rather than a CI performance claim. The exact-head
CI run below provides the Linux cost measurement.
- Exact current-head CI run 34756863153 for f7cb131 passed Ubuntu UT,
SCA, UT Coverage, shared build, Proxy/Pessimistic BVT, and CI Required.
The subsequent exact-head run 34799486791 for 323daee passed on
attempt 2: Ubuntu UT, SCA, UT Coverage, shared build, Proxy/Pessimistic
BVT, Coverage, and CI Required are green. Its first attempt failed only
in the unrelated optools TestUTHeartbeatStopsCleanly with `WaitDelay
expired before I/O complete`; the failed Coverage chain passed on rerun
without code changes.
- Formal BVT: CN1 and CN2 JDBC entry points each passed 36/36
comparisons with full metadata checking. go vet, gofmt, and diff checks
passed.

Deployment evidence for the already-fixed product base, independently of
this new test commit:

- Old baseline run
https://github.com/matrixorigin/mo-nightly-regression/actions/runs/34352473993:
HNSW/L2/cosine/normalize errors were 0/1702/1266/588.
- Fixed-product run
https://github.com/matrixorigin/mo-nightly-regression/actions/runs/34464342049:
all four original million-vector SIFT128 cases completed with 100
terminals, five-minute measurements, and zero client errors. The five
data hashes match the failed baseline. Acceptance was checked from
artifact counters and error files, not only workflow success.

QA required: yes — distributed timing and deployed-workload acceptance.
Automated terminal coverage includes completed SQL assertions,
cancellation waiter exit, preserved terminal errors, registration
removal, and cleanup. QA should review the target release's inclusion of
the existing production fixes and the attached run evidence. First-error
query/stream/peer correlation and unique root-cause attribution remain
unavailable; this PR must not auto-close matrixorigin#28378.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
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
…gin#28453)

## Summary

HAKeeper can report a failed MORPC transport generation as
`ErrBackendClosed` instead of EOF. The managed client previously reset
that generation but returned the error directly, so a transient
control-plane disconnect escaped as a SQL failure during
`TestIssue26640CrossAccountRestoreRebindsPrivileges`.

This change:

- retries the transport-generation errors (`ErrBackendClosed`,
connect/admission failures, connection reset) through the caller's
existing deadline;
- makes `managedHAKeeperClient.Close` terminal, prevents late failures
from recreating a transport, and makes concurrent `Close` calls join the
same cleanup result;
- consolidates the retry regressions into deterministic table-driven
tests, including deadline, business-error, in-flight-close, and
concurrent-close cases.

The retry is bounded by every public HAKeeper request context. An
allocation whose response is lost may consume an ID range, as the
existing EOF retry already did, but the server's monotonic allocator
prevents duplicate IDs from being returned.

## Root cause and scope

- matrixorigin#28443 failed before its restore/privilege assertions. The embedded
LogService first reported checker/raft timing pressure, then MORPC
returned `backend connection closed` while allocating an ID. The failure
was a downstream control-plane transport error; the deeper first
scheduler/WAL/IO fault is not proven by that job.
- matrixorigin#28447 is a separate MORPC stream-sequence-gap failure. It was already
fixed by merged matrixorigin#28358, which is in this branch's base. The exact
regression test passes repeatedly on current main, so this PR
intentionally does not duplicate that dispatch implementation.

Fixes matrixorigin#28452

Related: matrixorigin#28443, matrixorigin#28447, matrixorigin#28313, matrixorigin#28358

## Validation

- `TestIssue26640CrossAccountRestoreRebindsPrivileges`: `-count=3`,
passed.
- `TestIssue28313EmptyRemoteDispatch`: `-count=5`, passed.
- HAKeeper retry/close focused tests: normal and `-race -count=100`,
passed.
- `pkg/logservice`: normal and race package runs passed with the known
unrelated flaky `TestNewServiceClosesStoreOnReplicaStartFailure`
excluded; that test still fails independently with listener address
collisions/store-close leakage.
- `go vet ./pkg/logservice` with the repository CGo flags and `git diff
--check`, passed.

## CI triage for run 34300098985

The source changes in this PR are limited to pkg/logservice. In the
exact-head CI run:

- Shared build, SCA, normal UT, Compose BVT, and Standalone BVT passed.
- The UT coverage producer failed only at the unrelated existing test
pkg/sql/compile/TestIssue27261StopSendingDuringParallelReaderBuildStaysGraceful,
which returned context canceled; the producer report recorded no build
failures and two failed events in pkg/sql/compile.
- The downstream coverage merge failed because the required UT producer
artifact was incomplete (prerequisites_ready=false); it did not
calculate a coverage verdict.
- The same TestIssue27261 test passed locally 10 times, and the PR
retry/close focused tests passed locally 20 times normally and 100 times
under -race; go vet and git diff --check passed.

No unrelated compile/pipeline change is included to mask this flaky
coverage-only failure. This PR was not rebased and the existing PR base
was not changed.
VioletQwQ-0 added a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#28378

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

Add regression coverage for queued stream cancellation, shuffle receiver
retirement, and distributed IVF query cleanup. Production fixes are
already present through matrixorigin#28358, the relevant dispatch/remote pipeline
changes in matrixorigin#28364, and matrixorigin#28539; this PR changes tests only and does not
establish their individual causal contribution to the original TKE
incident.

- Observe serialized MORPC sequence numbers after a queued message is
canceled. The identical test compiles on the matrixorigin#28358 parent and fails
with expected sequence 2 versus actual 3.
- Cover first, middle, last, and consecutive shuffle receiver
retirement, checking both subsequent sends and one-time notification.
Exercise query/connection cancellation during real receiver credit
waiting through the CN handler, preserving the terminal error and
releasing lifecycle registration.
- Add a two-CN IVF test with 256 128-dimensional vectors. The
representative L2 case exercises eight concurrent sessions with one
simultaneous query per session; cosine, normalized L2, and raw-vector
IP/normalized-query retain their per-distance lifecycle and result
checks. The test covers exact full-probe comparison, approximate-result
validity, empty results, and subsequent queries. Test preparation
failure uses the actual phase runner, transaction rollback, worker exit,
and database cleanup. Preparation and query budgets are cumulative but
separate; cleanup gets its own context. SQL pre-cancellation is not
presented as proof of active remote cancellation. The fixture provides
16 vectors per IVF list on average; Vector Index Scan selects Multi-CN
without a 65,536-row threshold, so the 256-row fixture preserves the
lifecycle and result oracles while bounding the owning package's race
cost.
- Extend test/distributed/cases/vector/vector_ivf_multicn_search.sql and
.result with cosine, raw-vector IP/normalized-query, empty-result, and
follow-up checks. The GROUP_CONCAT metadata expectation uses the
existing server TEXT mapping and Connector/J 8.0.15 metadata; results
were not regenerated blindly.

Validation (final file contents include the follow-up assertion, SCA,
coverage-budget, fixture-size, and concurrency-budget fixes; exact head
323daee; upstream base
07b2596; product base
2a6fe7f):

- macOS arm64, Go 1.26.4, repository CGo wrapper, GOMAXPROCS=4, test
package parallelism 1.
- New mechanism tests: ordinary 100 iterations and race 20 iterations
passed. MORPC, dispatch, and compile packages passed ordinary/race
checks; unchanged evidence was reused.
- Follow-up P2 validation:
TestRemoteNotifyCancellationReleasesCreditWaitAndRegistration passed
ordinary 100 iterations and race 20 iterations after asserting that
connection cancellation closes proc.Ctx, records a non-nil
ErrStreamClosed cause, and preserves it through repeated terminal
cleanup.
- After the follow-up edit, the complete owning ./pkg/sql/compile
package passed once under the race detector; no race report was emitted.
- Exact prior-head fixture validation: GOWORK=off go test -mod=readonly
-count=1 -timeout=15m -run '^TestIssue28378IVFFlatRemoteLifecycle$'
./pkg/tests/issues passed in 14.855s; the same exact test with -race and
a 20m timeout passed in 34.817s. After the first fixture-size change,
the 1,024-row test passed ordinary in 16.675s and race in 33.739s; after
the final 256-row/one-iteration change, it passed ordinary in 16.591s
and race in 24.467s.
- The MORPC parent counterexample validates the sequence mechanism. The
IVF integration test is regression coverage, not a deterministic
reproduction of the historical incident.
- Reviewer P2 response: the fixture was reduced from 65,536 to 256 rows
and the concurrent repeat count from two to one in 323daee. XuPeng-SH
measured the prior 65,536-row test at 573.55s in the exclusive -p 1
-race UT stage on parent head 7944a5b; the focused runs above measure
the latest local fixture at 16.591s ordinary and 24.467s race. These are
different environments and modes, so the numbers are reported as bounded
before/after evidence rather than a CI performance claim. The exact-head
CI run below provides the Linux cost measurement.
- Exact current-head CI run 34756863153 for f7cb131 passed Ubuntu UT,
SCA, UT Coverage, shared build, Proxy/Pessimistic BVT, and CI Required.
The subsequent exact-head run 34799486791 for 323daee passed on
attempt 2: Ubuntu UT, SCA, UT Coverage, shared build, Proxy/Pessimistic
BVT, Coverage, and CI Required are green. Its first attempt failed only
in the unrelated optools TestUTHeartbeatStopsCleanly with `WaitDelay
expired before I/O complete`; the failed Coverage chain passed on rerun
without code changes.
- Formal BVT: CN1 and CN2 JDBC entry points each passed 36/36
comparisons with full metadata checking. go vet, gofmt, and diff checks
passed.

Deployment evidence for the already-fixed product base, independently of
this new test commit:

- Old baseline run
https://github.com/matrixorigin/mo-nightly-regression/actions/runs/34352473993:
HNSW/L2/cosine/normalize errors were 0/1702/1266/588.
- Fixed-product run
https://github.com/matrixorigin/mo-nightly-regression/actions/runs/34464342049:
all four original million-vector SIFT128 cases completed with 100
terminals, five-minute measurements, and zero client errors. The five
data hashes match the failed baseline. Acceptance was checked from
artifact counters and error files, not only workflow success.

QA required: yes — distributed timing and deployed-workload acceptance.
Automated terminal coverage includes completed SQL assertions,
cancellation waiter exit, preserved terminal errors, registration
removal, and cleanup. QA should review the target release's inclusion of
the existing production fixes and the attached run evidence. First-error
query/stream/peer correlation and unique root-cause attribution remain
unavailable; this PR must not auto-close matrixorigin#28378.

---------

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

size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants