Skip to content

fix(morpc): wake waiters when backend creation completes - #25771

Merged
XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/morpc-demand-aware-backend-creation
Jul 15, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/morpc-demand-aware-backend-creation

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Jul 15, 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:

Related to #25650 #25770

What this PR does / why we need it:

The MORPC recovery changes for CN hot recreation moved backend factory I/O out of the client mutex and deduplicated creation per remote generation. This preserved reset responsiveness and stale-generation safety, but callers waiting for that asynchronous result could only poll with exponential backoff. A backend that became ready just after a retry timer started remained unused until the timer expired. Multi-CN queries amplify this delay because remote pipelines repeatedly acquire locked streams.

This PR makes backend creation completion event-driven while preserving the recovery guarantees:

  • associates each queued or in-flight create with a generation-scoped completion signal;
  • makes Send, NewStream, and Ping wait for the actual create state transition instead of sleeping past a ready backend;
  • publishes a new backend before waking waiters;
  • wakes waiters when reset, generation eviction, or client close invalidates their create;
  • preserves exponential backoff after factory failures to avoid a retry storm;
  • retains context cancellation, the bounded auto-create timeout, create deduplication, and stale-generation rejection.

Validation:

  • Deterministic regression: clean origin/main slept on retry backoff and failed the 1-second assertion; this change completed immediately.
  • go test -mod=mod -count=1 -timeout 120s ./pkg/common/morpc
  • Race-enabled create/reset/dedup and new regression tests.
  • Local TPCH 10G with one TN and two CN processes, six warm runs:
Query origin/main This PR Speedup
q2 1.567 s 0.342 s 4.58x
q5 2.812 s 0.975 s 2.88x

The benchmark used the same LOG/TN processes and persisted data while switching the two CN binaries. Switching back to origin/main reproduced the slowdown, ruling out benchmark order and warm-cache effects.

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

Re-reviewed the latest head 8ba0cdb7c1. The new backendCreateState wakeup path looks coherent: waiters now block on a real creation-completion signal instead of sleeping through long retry backoff, failed creates still retain throttling via the failed bit, and targeted backend resets invalidate both the generation token and any queued create state before replacement. I also reran the focused backend-creation regressions in pkg/common/morpc, and I do not see a remaining high-confidence correctness, leak, hang, or OOM blocker on this head. GitHub does not allow me to approve my own pull request, so I am leaving this as an approve-level review comment instead of an approval.

@XuPeng-SH
XuPeng-SH requested a review from LeftHandCold July 15, 2026 08:47

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed head 8ba0cdb7c1. I traced the generation-scoped create state through queue admission, factory success/failure, queue-full fallback, targeted reset, generation eviction, client close, and the unregistered-GC path. Each admitted state is removed and its completion channel is closed; waits remain bounded by caller context / auto-create timeout, failed creates retain retry backoff, and successful backends are published before waiters are woken. Full pkg/common/morpc tests, the full race suite, and 50 repeated runs of the new success/failure regressions passed locally. I do not see a high-confidence correctness, leak, hang, OOM, or normal-business regression blocker on this head.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Fixed the TestCloseIdleBackends failure in ffce45e49b.

This was not introduced by the first PR commit. The same race reproduces on clean origin/main@2d01d204b2 with -race -count=5000 (both ErrBackendClosed and ErrBackendCreating). The failure exposed an existing lookup/create-admission TOCTOU:

  1. a lookup observed no available backend under c.mu;
  2. it released c.mu before submitting creation;
  3. the first asynchronous create published an available backend in that gap;
  4. the stale lookup still submitted a second create;
  5. the test's explicit second create then raced with the speculative create and saw either an in-flight claim or a full pool.

The fix makes backend selection and create admission one atomic state transition under c.mu. The create-channel send remains non-blocking, and factory/DNS/connection I/O remains outside the lock. Queue-full fallback now claims the same observed demand before unlocking, so publication cannot slip between observation and ownership. The obsolete post-unlock fallback-state lookup was removed.

Validation:

  • clean main reproducer: failed with the same two errors;
  • fixed branch: TestCloseIdleBackends -race -count=5000 passed;
  • focused success/failure/queue-full/reset/idle matrix: normal count=100, race count=50, shuffled;
  • full pkg/common/morpc ordinary and race suites;
  • go vet and go build for pkg/common/morpc;
  • full downstream pkg/lockservice suite;
  • hot available-backend benchmark versus prior PR head: median approximately 102 ns/op → 103 ns/op, unchanged 128 B/op and 1 alloc/op (noise-level difference);
  • git diff --check.

New CI run: https://github.com/matrixorigin/matrixone/actions/runs/29405085709

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

Re-reviewed the latest head ffce45e49b, focusing on the new atomic create-admission change. The revised getBackendForOperation now claims either the async queue slot or the synchronous creating[backend] slot while c.mu still protects the observed pool state, so the queue-full fallback no longer races a successful publication between demand observation and local create admission. I reran the focused pkg/common/morpc regression that exercises CloseBackendFor against a concurrent synchronous create, and I do not see a new high-confidence correctness, leak, hang, or OOM blocker in the latest delta. GitHub still does not allow me to approve my own pull request, so I am leaving this as an approve-level review comment rather than an approval.

@mergify

mergify Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@XuPeng-SH
XuPeng-SH merged commit cfca2ec into matrixorigin:main Jul 15, 2026
15 of 20 checks passed
@XuPeng-SH
XuPeng-SH deleted the fix/morpc-demand-aware-backend-creation branch July 15, 2026 10:39
XuPeng-SH added a commit that referenced this pull request Jul 17, 2026
## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes #25816

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

Remote dispatch readiness is a lifecycle event, not a wall-clock
duration. The fixed 30-second watchdog can classify a valid slow
registration as a failed CN, while simply extending the timeout leaves
the same correctness bug and delays real cancellation.

This PR closes the receiver lifecycle and its resource consequences as
one system:

- replaces fixed pre-readiness watchdogs with query/connection
cancellation-driven waits;
- models receiver state explicitly as ready, attached, closed, or
terminal, with generation-scoped waiters and per-UUID wakeups;
- makes publication, attachment, cancellation, completion, duplicate
notify, and owner cleanup race-safe;
- cancels the parent pipeline on early local/remote errors before
waiting for sibling scopes, preventing error-path wait cycles;
- keeps new-client/old-server compatibility through a query-bounded,
jittered legacy retry only for typed `NotRegistered` responses;
- records bounded receiver-wait outcomes and legacy retry counts without
high-cardinality labels;
- routes large (>=128 KiB) mpool buffers through direct mmap/munmap
while retaining libc for small allocations, so short-lived multi-CN
fan-out buffers return RSS deterministically instead of accumulating in
libc arenas.

The allocator change follows a causal 2-CN control test: with identical
2380 MiB CN limits, the affected baseline completed the first 400-query
wave and was OOM-killed early in the second wave, while the
implementation in this PR completed two full 400-query waves without
OOM. Connection counts had already plateaued and live Go heap grew only
slightly, isolating retained off-heap arena memory rather than an active
connection leak.

### Compatibility and failure semantics

- cancellation before registration does not poison a future registration
for the same UUID;
- cancellation after attachment cancels the owning process;
- a terminal owner cannot be resurrected by a late publish/attach race;
- legacy retry is never used for unrelated errors and is bounded by the
query context;
- no polling or hot-path sleep is reintroduced, preserving the
event-driven backend creation behavior from #25771;
- FIN/FIN_ACK connection reuse and response sequence semantics from
recent MORPC fixes remain unchanged.

### Validation completed

Package-level validation:

- `mo-cgo-test -count=1` on `pkg/sql/colexec`,
`pkg/sql/colexec/dispatch`, `pkg/sql/compile`, `pkg/util/metric/v2`,
`pkg/common/morpc`, `pkg/common/malloc`, and `pkg/common/mpool`;
- 30 repeated race runs for the new receiver
lifecycle/cancellation/retry tests;
- 10 repeated race runs for allocator threshold and realloc transitions;
- full `pkg/common/morpc` race run;
- `go vet` on all changed/adjacent packages;
- allocator matrix covers below/at/above threshold, small-to-small,
small-to-large, large-to-large, large-to-small, logical length smaller
than capacity, zero size, mismatch rejection, and concurrent
transitions.

Fresh Linux image and resource-constrained 2-CN validation, with no
`MALLOC_*` environment override and a 2380 MiB cgroup limit per CN:

- cold `make dev-build` completed successfully;
- wave 1: 400/400 queries, 0 failures, 21.289 s wall time, 0.756 s
median, 2.481 s max;
- wave 2: 400/400 queries, 0 failures, 18.180 s wall time, 0.695 s
median, 1.334 s max;
- peak cgroup memory: CN1 2,206,769,152 bytes, CN2 1,221,582,848 bytes;
- both CNs reported `memory.events`: `max=0`, `oom=0`, `oom_kill=0`;
- receiver lifecycle reached zero active entries after completion,
terminal receiver errors remained zero, and `TIME_WAIT` remained one per
CN.

Cancellation unhappy path:

- 16 clients deliberately hit a 1-second client read timeout;
- an immediate recovery query returned the correct result in 0.136 s;
- the temporary connection/lifecycle increase returned to the pre-test
baseline within 10 seconds and remained stable through 50 seconds;
- no stuck receiver owner, connection leak, or OOM event was observed.

Mixed-version compatibility (new CN plus affected old CN):

- 160/160 queries succeeded, with 0 failures;
- the new CN recorded 601 typed legacy retries, proving that the
compatibility path was exercised rather than bypassed;
- no protocol sequence, unsupported-method, or OOM errors were observed.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…n#25771)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Related to matrixorigin#25650 matrixorigin#25770

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

The MORPC recovery changes for CN hot recreation moved backend factory
I/O out of the client mutex and deduplicated creation per remote
generation. This preserved reset responsiveness and stale-generation
safety, but callers waiting for that asynchronous result could only poll
with exponential backoff. A backend that became ready just after a retry
timer started remained unused until the timer expired. Multi-CN queries
amplify this delay because remote pipelines repeatedly acquire locked
streams.

This PR makes backend creation completion event-driven while preserving
the recovery guarantees:

- associates each queued or in-flight create with a generation-scoped
completion signal;
- makes `Send`, `NewStream`, and `Ping` wait for the actual create state
transition instead of sleeping past a ready backend;
- publishes a new backend before waking waiters;
- wakes waiters when reset, generation eviction, or client close
invalidates their create;
- preserves exponential backoff after factory failures to avoid a retry
storm;
- retains context cancellation, the bounded auto-create timeout, create
deduplication, and stale-generation rejection.

Validation:

- Deterministic regression: clean `origin/main` slept on retry backoff
and failed the 1-second assertion; this change completed immediately.
- `go test -mod=mod -count=1 -timeout 120s ./pkg/common/morpc`
- Race-enabled create/reset/dedup and new regression tests.
- Local TPCH 10G with one TN and two CN processes, six warm runs:

| Query | `origin/main` | This PR | Speedup |
| --- | ---: | ---: | ---: |
| q2 | 1.567 s | 0.342 s | 4.58x |
| q5 | 2.812 s | 0.975 s | 2.88x |

The benchmark used the same LOG/TN processes and persisted data while
switching the two CN binaries. Switching back to `origin/main`
reproduced the slowdown, ruling out benchmark order and warm-cache
effects.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…xorigin#25820)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes matrixorigin#25816

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

Remote dispatch readiness is a lifecycle event, not a wall-clock
duration. The fixed 30-second watchdog can classify a valid slow
registration as a failed CN, while simply extending the timeout leaves
the same correctness bug and delays real cancellation.

This PR closes the receiver lifecycle and its resource consequences as
one system:

- replaces fixed pre-readiness watchdogs with query/connection
cancellation-driven waits;
- models receiver state explicitly as ready, attached, closed, or
terminal, with generation-scoped waiters and per-UUID wakeups;
- makes publication, attachment, cancellation, completion, duplicate
notify, and owner cleanup race-safe;
- cancels the parent pipeline on early local/remote errors before
waiting for sibling scopes, preventing error-path wait cycles;
- keeps new-client/old-server compatibility through a query-bounded,
jittered legacy retry only for typed `NotRegistered` responses;
- records bounded receiver-wait outcomes and legacy retry counts without
high-cardinality labels;
- routes large (>=128 KiB) mpool buffers through direct mmap/munmap
while retaining libc for small allocations, so short-lived multi-CN
fan-out buffers return RSS deterministically instead of accumulating in
libc arenas.

The allocator change follows a causal 2-CN control test: with identical
2380 MiB CN limits, the affected baseline completed the first 400-query
wave and was OOM-killed early in the second wave, while the
implementation in this PR completed two full 400-query waves without
OOM. Connection counts had already plateaued and live Go heap grew only
slightly, isolating retained off-heap arena memory rather than an active
connection leak.

### Compatibility and failure semantics

- cancellation before registration does not poison a future registration
for the same UUID;
- cancellation after attachment cancels the owning process;
- a terminal owner cannot be resurrected by a late publish/attach race;
- legacy retry is never used for unrelated errors and is bounded by the
query context;
- no polling or hot-path sleep is reintroduced, preserving the
event-driven backend creation behavior from matrixorigin#25771;
- FIN/FIN_ACK connection reuse and response sequence semantics from
recent MORPC fixes remain unchanged.

### Validation completed

Package-level validation:

- `mo-cgo-test -count=1` on `pkg/sql/colexec`,
`pkg/sql/colexec/dispatch`, `pkg/sql/compile`, `pkg/util/metric/v2`,
`pkg/common/morpc`, `pkg/common/malloc`, and `pkg/common/mpool`;
- 30 repeated race runs for the new receiver
lifecycle/cancellation/retry tests;
- 10 repeated race runs for allocator threshold and realloc transitions;
- full `pkg/common/morpc` race run;
- `go vet` on all changed/adjacent packages;
- allocator matrix covers below/at/above threshold, small-to-small,
small-to-large, large-to-large, large-to-small, logical length smaller
than capacity, zero size, mismatch rejection, and concurrent
transitions.

Fresh Linux image and resource-constrained 2-CN validation, with no
`MALLOC_*` environment override and a 2380 MiB cgroup limit per CN:

- cold `make dev-build` completed successfully;
- wave 1: 400/400 queries, 0 failures, 21.289 s wall time, 0.756 s
median, 2.481 s max;
- wave 2: 400/400 queries, 0 failures, 18.180 s wall time, 0.695 s
median, 1.334 s max;
- peak cgroup memory: CN1 2,206,769,152 bytes, CN2 1,221,582,848 bytes;
- both CNs reported `memory.events`: `max=0`, `oom=0`, `oom_kill=0`;
- receiver lifecycle reached zero active entries after completion,
terminal receiver errors remained zero, and `TIME_WAIT` remained one per
CN.

Cancellation unhappy path:

- 16 clients deliberately hit a 1-second client read timeout;
- an immediate recovery query returned the correct result in 0.136 s;
- the temporary connection/lifecycle increase returned to the pre-test
baseline within 10 seconds and remained stable through 50 seconds;
- no stuck receiver owner, connection leak, or OOM event was observed.

Mixed-version compatibility (new CN plus affected old CN):

- 160/160 queries succeeded, with 0 failures;
- the new CN recorded 601 typed legacy retries, proving that the
compatibility path was exercised rather than bypassed;
- no protocol sequence, unsupported-method, or OOM errors were observed.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…n#25771)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Related to matrixorigin#25650 matrixorigin#25770

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

The MORPC recovery changes for CN hot recreation moved backend factory
I/O out of the client mutex and deduplicated creation per remote
generation. This preserved reset responsiveness and stale-generation
safety, but callers waiting for that asynchronous result could only poll
with exponential backoff. A backend that became ready just after a retry
timer started remained unused until the timer expired. Multi-CN queries
amplify this delay because remote pipelines repeatedly acquire locked
streams.

This PR makes backend creation completion event-driven while preserving
the recovery guarantees:

- associates each queued or in-flight create with a generation-scoped
completion signal;
- makes `Send`, `NewStream`, and `Ping` wait for the actual create state
transition instead of sleeping past a ready backend;
- publishes a new backend before waking waiters;
- wakes waiters when reset, generation eviction, or client close
invalidates their create;
- preserves exponential backoff after factory failures to avoid a retry
storm;
- retains context cancellation, the bounded auto-create timeout, create
deduplication, and stale-generation rejection.

Validation:

- Deterministic regression: clean `origin/main` slept on retry backoff
and failed the 1-second assertion; this change completed immediately.
- `go test -mod=mod -count=1 -timeout 120s ./pkg/common/morpc`
- Race-enabled create/reset/dedup and new regression tests.
- Local TPCH 10G with one TN and two CN processes, six warm runs:

| Query | `origin/main` | This PR | Speedup |
| --- | ---: | ---: | ---: |
| q2 | 1.567 s | 0.342 s | 4.58x |
| q5 | 2.812 s | 0.975 s | 2.88x |

The benchmark used the same LOG/TN processes and persisted data while
switching the two CN binaries. Switching back to `origin/main`
reproduced the slowdown, ruling out benchmark order and warm-cache
effects.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…xorigin#25820)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes matrixorigin#25816

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

Remote dispatch readiness is a lifecycle event, not a wall-clock
duration. The fixed 30-second watchdog can classify a valid slow
registration as a failed CN, while simply extending the timeout leaves
the same correctness bug and delays real cancellation.

This PR closes the receiver lifecycle and its resource consequences as
one system:

- replaces fixed pre-readiness watchdogs with query/connection
cancellation-driven waits;
- models receiver state explicitly as ready, attached, closed, or
terminal, with generation-scoped waiters and per-UUID wakeups;
- makes publication, attachment, cancellation, completion, duplicate
notify, and owner cleanup race-safe;
- cancels the parent pipeline on early local/remote errors before
waiting for sibling scopes, preventing error-path wait cycles;
- keeps new-client/old-server compatibility through a query-bounded,
jittered legacy retry only for typed `NotRegistered` responses;
- records bounded receiver-wait outcomes and legacy retry counts without
high-cardinality labels;
- routes large (>=128 KiB) mpool buffers through direct mmap/munmap
while retaining libc for small allocations, so short-lived multi-CN
fan-out buffers return RSS deterministically instead of accumulating in
libc arenas.

The allocator change follows a causal 2-CN control test: with identical
2380 MiB CN limits, the affected baseline completed the first 400-query
wave and was OOM-killed early in the second wave, while the
implementation in this PR completed two full 400-query waves without
OOM. Connection counts had already plateaued and live Go heap grew only
slightly, isolating retained off-heap arena memory rather than an active
connection leak.

### Compatibility and failure semantics

- cancellation before registration does not poison a future registration
for the same UUID;
- cancellation after attachment cancels the owning process;
- a terminal owner cannot be resurrected by a late publish/attach race;
- legacy retry is never used for unrelated errors and is bounded by the
query context;
- no polling or hot-path sleep is reintroduced, preserving the
event-driven backend creation behavior from matrixorigin#25771;
- FIN/FIN_ACK connection reuse and response sequence semantics from
recent MORPC fixes remain unchanged.

### Validation completed

Package-level validation:

- `mo-cgo-test -count=1` on `pkg/sql/colexec`,
`pkg/sql/colexec/dispatch`, `pkg/sql/compile`, `pkg/util/metric/v2`,
`pkg/common/morpc`, `pkg/common/malloc`, and `pkg/common/mpool`;
- 30 repeated race runs for the new receiver
lifecycle/cancellation/retry tests;
- 10 repeated race runs for allocator threshold and realloc transitions;
- full `pkg/common/morpc` race run;
- `go vet` on all changed/adjacent packages;
- allocator matrix covers below/at/above threshold, small-to-small,
small-to-large, large-to-large, large-to-small, logical length smaller
than capacity, zero size, mismatch rejection, and concurrent
transitions.

Fresh Linux image and resource-constrained 2-CN validation, with no
`MALLOC_*` environment override and a 2380 MiB cgroup limit per CN:

- cold `make dev-build` completed successfully;
- wave 1: 400/400 queries, 0 failures, 21.289 s wall time, 0.756 s
median, 2.481 s max;
- wave 2: 400/400 queries, 0 failures, 18.180 s wall time, 0.695 s
median, 1.334 s max;
- peak cgroup memory: CN1 2,206,769,152 bytes, CN2 1,221,582,848 bytes;
- both CNs reported `memory.events`: `max=0`, `oom=0`, `oom_kill=0`;
- receiver lifecycle reached zero active entries after completion,
terminal receiver errors remained zero, and `TIME_WAIT` remained one per
CN.

Cancellation unhappy path:

- 16 clients deliberately hit a 1-second client read timeout;
- an immediate recovery query returned the correct result in 0.136 s;
- the temporary connection/lifecycle increase returned to the pre-test
baseline within 10 seconds and remained stable through 50 seconds;
- no stuck receiver owner, connection leak, or OOM event was observed.

Mixed-version compatibility (new CN plus affected old CN):

- 160/160 queries succeeded, with 0 failures;
- the new CN recorded 601 typed legacy retries, proving that the
compatibility path was exercised rather than bypassed;
- no protocol sequence, unsupported-method, or OOM errors were observed.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…n#25771)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Related to matrixorigin#25650 matrixorigin#25770

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

The MORPC recovery changes for CN hot recreation moved backend factory
I/O out of the client mutex and deduplicated creation per remote
generation. This preserved reset responsiveness and stale-generation
safety, but callers waiting for that asynchronous result could only poll
with exponential backoff. A backend that became ready just after a retry
timer started remained unused until the timer expired. Multi-CN queries
amplify this delay because remote pipelines repeatedly acquire locked
streams.

This PR makes backend creation completion event-driven while preserving
the recovery guarantees:

- associates each queued or in-flight create with a generation-scoped
completion signal;
- makes `Send`, `NewStream`, and `Ping` wait for the actual create state
transition instead of sleeping past a ready backend;
- publishes a new backend before waking waiters;
- wakes waiters when reset, generation eviction, or client close
invalidates their create;
- preserves exponential backoff after factory failures to avoid a retry
storm;
- retains context cancellation, the bounded auto-create timeout, create
deduplication, and stale-generation rejection.

Validation:

- Deterministic regression: clean `origin/main` slept on retry backoff
and failed the 1-second assertion; this change completed immediately.
- `go test -mod=mod -count=1 -timeout 120s ./pkg/common/morpc`
- Race-enabled create/reset/dedup and new regression tests.
- Local TPCH 10G with one TN and two CN processes, six warm runs:

| Query | `origin/main` | This PR | Speedup |
| --- | ---: | ---: | ---: |
| q2 | 1.567 s | 0.342 s | 4.58x |
| q5 | 2.812 s | 0.975 s | 2.88x |

The benchmark used the same LOG/TN processes and persisted data while
switching the two CN binaries. Switching back to `origin/main`
reproduced the slowdown, ruling out benchmark order and warm-cache
effects.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…xorigin#25820)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes matrixorigin#25816

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

Remote dispatch readiness is a lifecycle event, not a wall-clock
duration. The fixed 30-second watchdog can classify a valid slow
registration as a failed CN, while simply extending the timeout leaves
the same correctness bug and delays real cancellation.

This PR closes the receiver lifecycle and its resource consequences as
one system:

- replaces fixed pre-readiness watchdogs with query/connection
cancellation-driven waits;
- models receiver state explicitly as ready, attached, closed, or
terminal, with generation-scoped waiters and per-UUID wakeups;
- makes publication, attachment, cancellation, completion, duplicate
notify, and owner cleanup race-safe;
- cancels the parent pipeline on early local/remote errors before
waiting for sibling scopes, preventing error-path wait cycles;
- keeps new-client/old-server compatibility through a query-bounded,
jittered legacy retry only for typed `NotRegistered` responses;
- records bounded receiver-wait outcomes and legacy retry counts without
high-cardinality labels;
- routes large (>=128 KiB) mpool buffers through direct mmap/munmap
while retaining libc for small allocations, so short-lived multi-CN
fan-out buffers return RSS deterministically instead of accumulating in
libc arenas.

The allocator change follows a causal 2-CN control test: with identical
2380 MiB CN limits, the affected baseline completed the first 400-query
wave and was OOM-killed early in the second wave, while the
implementation in this PR completed two full 400-query waves without
OOM. Connection counts had already plateaued and live Go heap grew only
slightly, isolating retained off-heap arena memory rather than an active
connection leak.

### Compatibility and failure semantics

- cancellation before registration does not poison a future registration
for the same UUID;
- cancellation after attachment cancels the owning process;
- a terminal owner cannot be resurrected by a late publish/attach race;
- legacy retry is never used for unrelated errors and is bounded by the
query context;
- no polling or hot-path sleep is reintroduced, preserving the
event-driven backend creation behavior from matrixorigin#25771;
- FIN/FIN_ACK connection reuse and response sequence semantics from
recent MORPC fixes remain unchanged.

### Validation completed

Package-level validation:

- `mo-cgo-test -count=1` on `pkg/sql/colexec`,
`pkg/sql/colexec/dispatch`, `pkg/sql/compile`, `pkg/util/metric/v2`,
`pkg/common/morpc`, `pkg/common/malloc`, and `pkg/common/mpool`;
- 30 repeated race runs for the new receiver
lifecycle/cancellation/retry tests;
- 10 repeated race runs for allocator threshold and realloc transitions;
- full `pkg/common/morpc` race run;
- `go vet` on all changed/adjacent packages;
- allocator matrix covers below/at/above threshold, small-to-small,
small-to-large, large-to-large, large-to-small, logical length smaller
than capacity, zero size, mismatch rejection, and concurrent
transitions.

Fresh Linux image and resource-constrained 2-CN validation, with no
`MALLOC_*` environment override and a 2380 MiB cgroup limit per CN:

- cold `make dev-build` completed successfully;
- wave 1: 400/400 queries, 0 failures, 21.289 s wall time, 0.756 s
median, 2.481 s max;
- wave 2: 400/400 queries, 0 failures, 18.180 s wall time, 0.695 s
median, 1.334 s max;
- peak cgroup memory: CN1 2,206,769,152 bytes, CN2 1,221,582,848 bytes;
- both CNs reported `memory.events`: `max=0`, `oom=0`, `oom_kill=0`;
- receiver lifecycle reached zero active entries after completion,
terminal receiver errors remained zero, and `TIME_WAIT` remained one per
CN.

Cancellation unhappy path:

- 16 clients deliberately hit a 1-second client read timeout;
- an immediate recovery query returned the correct result in 0.136 s;
- the temporary connection/lifecycle increase returned to the pre-test
baseline within 10 seconds and remained stable through 50 seconds;
- no stuck receiver owner, connection leak, or OOM event was observed.

Mixed-version compatibility (new CN plus affected old CN):

- 160/160 queries succeeded, with 0 failures;
- the new CN recorded 601 typed legacy retries, proving that the
compatibility path was exercised rather than bypassed;
- no protocol sequence, unsupported-method, or OOM errors were observed.

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.

3 participants