Skip to content

fix(pipeline): make remote receiver readiness lifecycle-driven - #25820

Merged
XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/pipeline-readiness-resource-admission
Jul 17, 2026
Merged

XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/pipeline-readiness-resource-admission

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Fixes #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 fix(morpc): wake waiters when backend creation completes #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.

@XuPeng-SH
XuPeng-SH requested review from aptend and aunjgr as code owners July 16, 2026 14:01
@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 →

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Blocking allocator ownership issue: SimpleCAllocator.ReallocZero chooses mmap vs libc provenance from cap(old), but callers can legally pass a reduced-cap view of an existing mpool allocation. A concrete existing path is: allocate 128 KiB off-heap (mmap), PtrLen.Replace shrinks only its logical length, PtrLen.ToByteSlice reconstructs len/cap from that shorter length, then AppendRawBytes calls MPool.ReallocZero. sane_allocator.go then sees cap(old) below 128 KiB and calls C.realloc on a unix.Mmap pointer, which is an invalid-pointer abort/undefined behavior. A reduced-cap mmap slice that still stays above the threshold instead reaches unix.Munmap with the wrong mapping length and panics with EINVAL. The current logical-length test preserves the original cap, so it misses this case. Please derive allocation size/provenance from stable mpool ownership metadata (not slice capacity) and add a reduced-cap regression covering threshold transitions.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Addressed the requested allocator ownership fix in 50c25fdd7b.

The review finding was valid: a slice's cap is a mutable view property and cannot identify the backing allocator or its actual size. The fix now uses the stable MPool allocation header (allocSz, offHeap, and poolId) as the source of truth whenever growth exceeds the caller-visible capacity. SimpleCAllocator.ReallocZero receives the recorded old allocation size explicitly, so mmap/libc selection, unmap length, accounting, and copy/free ownership no longer depend on a reduced-capacity view.

The common capacity-local resize path remains lock-free. The metadata path also handles the related closure cases rather than special-casing PtrLen:

  • reduced-cap and zero-cap views;
  • libc -> mmap, mmap -> libc, and mmap -> mmap transitions;
  • on-heap -> off-heap and off-heap -> on-heap transitions;
  • growth within the recorded backing allocation without an unnecessary realloc;
  • growth beyond the recorded allocation with exactly-once old ownership release;
  • allocation failure preserving the old allocation/header.

Added regressions include the concrete PtrLen.Replace shrink followed by AppendRawBytes, reduced-cap transitions across the mmap threshold, zero-cap tracked views, and source-provenance transitions.

The branch was then rebased onto latest main (757cacf0a5). git range-diff reports both commits semantically unchanged by the rebase.

Fresh post-rebase validation:

  • all affected packages passed: colexec, dispatch, compile, metrics, MORPC, malloc, and mpool;
  • allocator/provenance focused race stress: -race -count=10;
  • receiver lifecycle/cancellation focused race stress: -race -count=30;
  • full MORPC race suite passed;
  • full race suites for all other owning packages passed;
  • build, vet, and git diff --check passed.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Blocking allocator ownership issue: SimpleCAllocator.ReallocZero chooses mmap vs libc provenance from cap(old), but callers can legally pass a reduced-cap view of an existing mpool allocation. A concrete existing path is: allocate 128 KiB off-heap (mmap), PtrLen.Replace shrinks only its logical length, PtrLen.ToByteSlice reconstructs len/cap from that shorter length, then AppendRawBytes calls MPool.ReallocZero. sane_allocator.go then sees cap(old) below 128 KiB and calls C.realloc on a unix.Mmap pointer, which is an invalid-pointer abort/undefined behavior. A reduced-cap mmap slice that still stays above the threshold instead reaches unix.Munmap with the wrong mapping length and panics with EINVAL. The current logical-length test preserves the original cap, so it misses this case. Please derive allocation size/provenance from stable mpool ownership metadata (not slice capacity) and add a reduced-cap regression covering threshold transitions.

fixed

@XuPeng-SH
XuPeng-SH force-pushed the fix/pipeline-readiness-resource-admission branch from 50c25fd to b9710c5 Compare July 16, 2026 16:52
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Added the liveness closure in b9710c5436 and rebased the branch onto latest main (734fa4e50b).

The 120s limit is admission-only: it bounds the period in which a remote dispatch receiver has not registered/attached. It does not become the stream context and does not limit an attached HTAP query, so queries running longer than 120s remain valid.

The fix closes all registration wait chains:

  • local dispatch waiting for all remote receivers;
  • new server waiting for a receiver UUID to be published;
  • new client retrying an old server that returns typed RemoteDispatchNotRegistered.

Boundary and performance details:

  • timeout races perform a final registry lookup while the waiter reference is still held, so a receiver published or closed at the boundary wins with its real terminal state;
  • timeout/cancel paths release generation-scoped waiter references and do not poison later registration of the same UUID;
  • the compatibility deadline is captured from notify start but its timer is created lazily only after an old peer returns NotRegistered; the normal new-to-new path gets no extra client timer;
  • only startup/admission paths allocate timers; there is no per-batch hot-path cost;
  • the wait histogram now includes a timeout outcome and a finite bucket range beyond 120s.

Added coverage for no registration, partial registration, timeout cleanup followed by later registration, legacy retry exhaustion, and an already-expired admission budget after successful attach (proving the successful stream still uses the query context).

Fresh post-rebase validation:

  • affected packages passed: colexec, dispatch, compile, metrics, MORPC, malloc, and mpool;
  • full race suites passed for colexec/dispatch/compile/metrics;
  • full race suites also passed for MORPC/malloc/mpool before the final lazy-timer-only refinement;
  • focused timeout/compatibility tests passed with -race -count=10 after the refinement;
  • go build, go vet, git diff --check, and clean-worktree checks passed;
  • git range-diff shows the two prior commits are semantically unchanged by the rebase.

@XuPeng-SH
XuPeng-SH merged commit 7ffd26c into matrixorigin:main Jul 17, 2026
22 of 23 checks passed
@XuPeng-SH
XuPeng-SH deleted the fix/pipeline-readiness-resource-admission branch July 17, 2026 10:51
mergify Bot pushed a commit that referenced this pull request Jul 19, 2026
TestFetchWhoWaitingMeUsesActiveRemoteWaiterSnapshots used its 10-second setup context for the background waiter and then called an unbounded test helper while waiting for that waiter to reach the owner queue. If setup or remote routing consumed the deadline, Lock returned without entering the queue and the helper spun until the package-level 40-minute timeout.

The test now gives the background waiter an explicit lifecycle, bounds both admission and post-release waits, and uses independent cleanup contexts. On every assertion-failure path it releases the holder, cancels the waiter, and unlocks a waiter that acquired the lock before cleanup.

A follow-up CI run exposed that the independent waiter initially used a context without a deadline. Remote Lock crosses MORPC, whose Future contract requires every non-one-way send to carry a deadline. The waiter now has an independent 30-second timeout: it remains decoupled from setup while satisfying the RPC contract and retaining a hard liveness bound. The later RWMutex fatal in that run was cascading panic cleanup after the deadline-contract panic, not the original lockservice hang.

This is a test-liveness repair; it does not change lockservice production behavior.

Related CI failure #25729 is already covered by the receiver lifecycle fix merged in #25820. Current main dispatch regression no longer contains the racy post-send assertion, so no duplicate issue or code change is needed here.

Tested with:

mo-cgo-test -v -count=1 -timeout=90s ./pkg/lockservice -run ^TestFetchWhoWaitingMeUsesActiveRemoteWaiterSnapshots$

20 independent process repetitions of the focused test

mo-cgo-test -race -count=20 -timeout=180s ./pkg/lockservice -run ^TestFetchWhoWaitingMeUsesActiveRemoteWaiterSnapshots$

mo-cgo-test -count=1 -timeout=300s ./pkg/lockservice

go build ./pkg/lockservice

go vet ./pkg/lockservice

Approved by: @gouhongshen, @XuPeng-SH
XuPeng-SH added a commit that referenced this pull request Jul 24, 2026
## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes #26132

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

### Corrected root cause

The original issue attributed Q18 to MARK join falling back to LoopJoin.
Controlled plans and adjacent-commit A/B refute that attribution:
canonical Q18 remains a SEMI hash join, and #25822 is neutral/slightly
faster than its direct parent.

Further bisection identifies `7ffd26c7e1` from #25820 as the first bad
commit. Besides its pipeline lifecycle changes, that commit moved all
off-heap allocations at or above 128 KiB from libc to immediate
`mmap`/`munmap`. Q18 builds a roughly 1 GiB, 15-million-row hash
aggregate; repeated growth faults transient tables, and immediate unmap
makes the final working set fault again on the next execution. Disabling
only that mmap path restores the old timing, while the physical plan and
scan cardinalities remain unchanged.

### Changes

1. Segment large Int64/String hash tables at 4 MiB instead of 256 MiB.
Growth appends blocks and preserves existing mappings rather than
allocating and faulting another full contiguous table. Load-factor
decisions still use the total table size, preserving the original 1/2,
2/3, 3/4, and 4/5 thresholds.
2. Add bounded exact-size reuse for Linux mmap allocations used by
zeroing `Allocate`/`ReallocZero`:
- freed pages are marked `MADV_FREE`, so the kernel can reclaim them
under pressure;
- retained virtual memory is bounded by `min(global memory limit / 4, 1
GiB)`;
- all cached mappings are actively `munmap`ed after one second of
inactivity;
- `Malloc` does not reuse LazyFree pages because its no-clear contract
cannot safely reactivate every page;
   - non-Linux platforms keep the existing immediate-unmap behavior;
- cached bytes are exposed as
`mo_mem_offheap_inuse_bytes{type="mpool-cache"}`.

### Performance

Single-node launch, TPCH 10G Q18, same data and machine:

| Version | Wall time |
|---|---:|
| current main before this change | 0.67-0.70 s, median 0.68 s |
| segmented hash table only | 0.55-0.58 s, median 0.57 s |
| final branch, after allocator cache idle | 0.517 s |
| final branch, burst steady state | 0.302-0.323 s, median 0.317 s |
| pre-regression `0d8111ae` | 0.47-0.50 s |

A 10-query process-counter sample reduced minor faults from 5,826,419 to
1,361,708 and system CPU ticks from 6,484 to 997. The cache sample
contained about 1.045 GiB of `LazyFree` pages; after two idle seconds
`LazyFree` returned to zero and RSS fell from 2.65 GiB to 1.61 GiB.

Spot checks of Q1, Q6, Q9, Q13, Q17, and Q21 against the main baseline
found no regression; all were neutral or faster.

### Ownership / unhappy-path review

- Mapping ownership has one linear path: mmap caller -> cache -> zeroing
caller, or cache -> idle timer -> munmap.
- Capacity rejection and failed `madvise` retain caller ownership and
fall back to immediate munmap.
- The cache mutex removes mappings before unmapping, so take/expiry
cannot double-release.
- Cache growth has both a hard byte bound and an idle recycle point.
- Old timer callbacks check the current idle generation before releasing
mappings.

### Validation

```text
.agents/skills/mo-dev/scripts/mo-cgo-test -race \
  -run TestSimpleCAllocatorMmapCache -count=20 -timeout=240s \
  ./pkg/common/malloc

.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s \
  ./pkg/common/malloc ./pkg/common/mpool ./pkg/container/hashtable \
  ./pkg/common/hashmap ./pkg/sql/colexec/group

.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=240s \
  ./pkg/common/malloc ./pkg/common/mpool ./pkg/container/hashtable \
  ./pkg/common/hashmap ./pkg/sql/colexec/group

make build
go vet ./pkg/common/malloc ./pkg/common/mpool ./pkg/container/hashtable \
  ./pkg/common/hashmap ./pkg/sql/colexec/group
```

All commands passed after rebasing onto current main.
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
…5860)

TestFetchWhoWaitingMeUsesActiveRemoteWaiterSnapshots used its 10-second setup context for the background waiter and then called an unbounded test helper while waiting for that waiter to reach the owner queue. If setup or remote routing consumed the deadline, Lock returned without entering the queue and the helper spun until the package-level 40-minute timeout.

The test now gives the background waiter an explicit lifecycle, bounds both admission and post-release waits, and uses independent cleanup contexts. On every assertion-failure path it releases the holder, cancels the waiter, and unlocks a waiter that acquired the lock before cleanup.

A follow-up CI run exposed that the independent waiter initially used a context without a deadline. Remote Lock crosses MORPC, whose Future contract requires every non-one-way send to carry a deadline. The waiter now has an independent 30-second timeout: it remains decoupled from setup while satisfying the RPC contract and retaining a hard liveness bound. The later RWMutex fatal in that run was cascading panic cleanup after the deadline-contract panic, not the original lockservice hang.

This is a test-liveness repair; it does not change lockservice production behavior.

Related CI failure matrixorigin#25729 is already covered by the receiver lifecycle fix merged in matrixorigin#25820. Current main dispatch regression no longer contains the racy post-send assertion, so no duplicate issue or code change is needed here.

Tested with:

mo-cgo-test -v -count=1 -timeout=90s ./pkg/lockservice -run ^TestFetchWhoWaitingMeUsesActiveRemoteWaiterSnapshots$

20 independent process repetitions of the focused test

mo-cgo-test -race -count=20 -timeout=180s ./pkg/lockservice -run ^TestFetchWhoWaitingMeUsesActiveRemoteWaiterSnapshots$

mo-cgo-test -count=1 -timeout=300s ./pkg/lockservice

go build ./pkg/lockservice

go vet ./pkg/lockservice

Approved by: @gouhongshen, @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…26143)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes matrixorigin#26132

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

### Corrected root cause

The original issue attributed Q18 to MARK join falling back to LoopJoin.
Controlled plans and adjacent-commit A/B refute that attribution:
canonical Q18 remains a SEMI hash join, and matrixorigin#25822 is neutral/slightly
faster than its direct parent.

Further bisection identifies `7ffd26c7e1` from matrixorigin#25820 as the first bad
commit. Besides its pipeline lifecycle changes, that commit moved all
off-heap allocations at or above 128 KiB from libc to immediate
`mmap`/`munmap`. Q18 builds a roughly 1 GiB, 15-million-row hash
aggregate; repeated growth faults transient tables, and immediate unmap
makes the final working set fault again on the next execution. Disabling
only that mmap path restores the old timing, while the physical plan and
scan cardinalities remain unchanged.

### Changes

1. Segment large Int64/String hash tables at 4 MiB instead of 256 MiB.
Growth appends blocks and preserves existing mappings rather than
allocating and faulting another full contiguous table. Load-factor
decisions still use the total table size, preserving the original 1/2,
2/3, 3/4, and 4/5 thresholds.
2. Add bounded exact-size reuse for Linux mmap allocations used by
zeroing `Allocate`/`ReallocZero`:
- freed pages are marked `MADV_FREE`, so the kernel can reclaim them
under pressure;
- retained virtual memory is bounded by `min(global memory limit / 4, 1
GiB)`;
- all cached mappings are actively `munmap`ed after one second of
inactivity;
- `Malloc` does not reuse LazyFree pages because its no-clear contract
cannot safely reactivate every page;
   - non-Linux platforms keep the existing immediate-unmap behavior;
- cached bytes are exposed as
`mo_mem_offheap_inuse_bytes{type="mpool-cache"}`.

### Performance

Single-node launch, TPCH 10G Q18, same data and machine:

| Version | Wall time |
|---|---:|
| current main before this change | 0.67-0.70 s, median 0.68 s |
| segmented hash table only | 0.55-0.58 s, median 0.57 s |
| final branch, after allocator cache idle | 0.517 s |
| final branch, burst steady state | 0.302-0.323 s, median 0.317 s |
| pre-regression `0d8111ae` | 0.47-0.50 s |

A 10-query process-counter sample reduced minor faults from 5,826,419 to
1,361,708 and system CPU ticks from 6,484 to 997. The cache sample
contained about 1.045 GiB of `LazyFree` pages; after two idle seconds
`LazyFree` returned to zero and RSS fell from 2.65 GiB to 1.61 GiB.

Spot checks of Q1, Q6, Q9, Q13, Q17, and Q21 against the main baseline
found no regression; all were neutral or faster.

### Ownership / unhappy-path review

- Mapping ownership has one linear path: mmap caller -> cache -> zeroing
caller, or cache -> idle timer -> munmap.
- Capacity rejection and failed `madvise` retain caller ownership and
fall back to immediate munmap.
- The cache mutex removes mappings before unmapping, so take/expiry
cannot double-release.
- Cache growth has both a hard byte bound and an idle recycle point.
- Old timer callbacks check the current idle generation before releasing
mappings.

### Validation

```text
.agents/skills/mo-dev/scripts/mo-cgo-test -race \
  -run TestSimpleCAllocatorMmapCache -count=20 -timeout=240s \
  ./pkg/common/malloc

.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s \
  ./pkg/common/malloc ./pkg/common/mpool ./pkg/container/hashtable \
  ./pkg/common/hashmap ./pkg/sql/colexec/group

.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=240s \
  ./pkg/common/malloc ./pkg/common/mpool ./pkg/container/hashtable \
  ./pkg/common/hashmap ./pkg/sql/colexec/group

make build
go vet ./pkg/common/malloc ./pkg/common/mpool ./pkg/container/hashtable \
  ./pkg/common/hashmap ./pkg/sql/colexec/group
```

All commands passed after rebasing onto current main.
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
…5860)

TestFetchWhoWaitingMeUsesActiveRemoteWaiterSnapshots used its 10-second setup context for the background waiter and then called an unbounded test helper while waiting for that waiter to reach the owner queue. If setup or remote routing consumed the deadline, Lock returned without entering the queue and the helper spun until the package-level 40-minute timeout.

The test now gives the background waiter an explicit lifecycle, bounds both admission and post-release waits, and uses independent cleanup contexts. On every assertion-failure path it releases the holder, cancels the waiter, and unlocks a waiter that acquired the lock before cleanup.

A follow-up CI run exposed that the independent waiter initially used a context without a deadline. Remote Lock crosses MORPC, whose Future contract requires every non-one-way send to carry a deadline. The waiter now has an independent 30-second timeout: it remains decoupled from setup while satisfying the RPC contract and retaining a hard liveness bound. The later RWMutex fatal in that run was cascading panic cleanup after the deadline-contract panic, not the original lockservice hang.

This is a test-liveness repair; it does not change lockservice production behavior.

Related CI failure matrixorigin#25729 is already covered by the receiver lifecycle fix merged in matrixorigin#25820. Current main dispatch regression no longer contains the racy post-send assertion, so no duplicate issue or code change is needed here.

Tested with:

mo-cgo-test -v -count=1 -timeout=90s ./pkg/lockservice -run ^TestFetchWhoWaitingMeUsesActiveRemoteWaiterSnapshots$

20 independent process repetitions of the focused test

mo-cgo-test -race -count=20 -timeout=180s ./pkg/lockservice -run ^TestFetchWhoWaitingMeUsesActiveRemoteWaiterSnapshots$

mo-cgo-test -count=1 -timeout=300s ./pkg/lockservice

go build ./pkg/lockservice

go vet ./pkg/lockservice

Approved by: @gouhongshen, @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…26143)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes matrixorigin#26132

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

### Corrected root cause

The original issue attributed Q18 to MARK join falling back to LoopJoin.
Controlled plans and adjacent-commit A/B refute that attribution:
canonical Q18 remains a SEMI hash join, and matrixorigin#25822 is neutral/slightly
faster than its direct parent.

Further bisection identifies `7ffd26c7e1` from matrixorigin#25820 as the first bad
commit. Besides its pipeline lifecycle changes, that commit moved all
off-heap allocations at or above 128 KiB from libc to immediate
`mmap`/`munmap`. Q18 builds a roughly 1 GiB, 15-million-row hash
aggregate; repeated growth faults transient tables, and immediate unmap
makes the final working set fault again on the next execution. Disabling
only that mmap path restores the old timing, while the physical plan and
scan cardinalities remain unchanged.

### Changes

1. Segment large Int64/String hash tables at 4 MiB instead of 256 MiB.
Growth appends blocks and preserves existing mappings rather than
allocating and faulting another full contiguous table. Load-factor
decisions still use the total table size, preserving the original 1/2,
2/3, 3/4, and 4/5 thresholds.
2. Add bounded exact-size reuse for Linux mmap allocations used by
zeroing `Allocate`/`ReallocZero`:
- freed pages are marked `MADV_FREE`, so the kernel can reclaim them
under pressure;
- retained virtual memory is bounded by `min(global memory limit / 4, 1
GiB)`;
- all cached mappings are actively `munmap`ed after one second of
inactivity;
- `Malloc` does not reuse LazyFree pages because its no-clear contract
cannot safely reactivate every page;
   - non-Linux platforms keep the existing immediate-unmap behavior;
- cached bytes are exposed as
`mo_mem_offheap_inuse_bytes{type="mpool-cache"}`.

### Performance

Single-node launch, TPCH 10G Q18, same data and machine:

| Version | Wall time |
|---|---:|
| current main before this change | 0.67-0.70 s, median 0.68 s |
| segmented hash table only | 0.55-0.58 s, median 0.57 s |
| final branch, after allocator cache idle | 0.517 s |
| final branch, burst steady state | 0.302-0.323 s, median 0.317 s |
| pre-regression `0d8111ae` | 0.47-0.50 s |

A 10-query process-counter sample reduced minor faults from 5,826,419 to
1,361,708 and system CPU ticks from 6,484 to 997. The cache sample
contained about 1.045 GiB of `LazyFree` pages; after two idle seconds
`LazyFree` returned to zero and RSS fell from 2.65 GiB to 1.61 GiB.

Spot checks of Q1, Q6, Q9, Q13, Q17, and Q21 against the main baseline
found no regression; all were neutral or faster.

### Ownership / unhappy-path review

- Mapping ownership has one linear path: mmap caller -> cache -> zeroing
caller, or cache -> idle timer -> munmap.
- Capacity rejection and failed `madvise` retain caller ownership and
fall back to immediate munmap.
- The cache mutex removes mappings before unmapping, so take/expiry
cannot double-release.
- Cache growth has both a hard byte bound and an idle recycle point.
- Old timer callbacks check the current idle generation before releasing
mappings.

### Validation

```text
.agents/skills/mo-dev/scripts/mo-cgo-test -race \
  -run TestSimpleCAllocatorMmapCache -count=20 -timeout=240s \
  ./pkg/common/malloc

.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s \
  ./pkg/common/malloc ./pkg/common/mpool ./pkg/container/hashtable \
  ./pkg/common/hashmap ./pkg/sql/colexec/group

.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=240s \
  ./pkg/common/malloc ./pkg/common/mpool ./pkg/container/hashtable \
  ./pkg/common/hashmap ./pkg/sql/colexec/group

make build
go vet ./pkg/common/malloc ./pkg/common/mpool ./pkg/container/hashtable \
  ./pkg/common/hashmap ./pkg/sql/colexec/group
```

All commands passed after rebasing onto current main.
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 kind/enhancement kind/refactor Code refactor kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] 30s remote dispatch watchdog can falsely fail slow receiver registration

4 participants