Repository navigation
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
aptend
left a comment
There was a problem hiding this comment.
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.
fdf639a to
50c25fd
Compare
|
Addressed the requested allocator ownership fix in The review finding was valid: a slice's The common capacity-local resize path remains lock-free. The metadata path also handles the related closure cases rather than special-casing
Added regressions include the concrete The branch was then rebased onto latest Fresh post-rebase validation:
|
fixed |
50c25fd to
b9710c5
Compare
|
Added the liveness closure in 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:
Boundary and performance details:
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:
|
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
## 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.
…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.
…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
…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.
…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.
…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
…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.
…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.
What type of PR is this?
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:
NotRegisteredresponses;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
Validation completed
Package-level validation:
mo-cgo-test -count=1onpkg/sql/colexec,pkg/sql/colexec/dispatch,pkg/sql/compile,pkg/util/metric/v2,pkg/common/morpc,pkg/common/malloc, andpkg/common/mpool;pkg/common/morpcrace run;go veton all changed/adjacent packages;Fresh Linux image and resource-constrained 2-CN validation, with no
MALLOC_*environment override and a 2380 MiB cgroup limit per CN:make dev-buildcompleted successfully;memory.events:max=0,oom=0,oom_kill=0;TIME_WAITremained one per CN.Cancellation unhappy path:
Mixed-version compatibility (new CN plus affected old CN):