Skip to content

fix(malloc): handle munmap ENOMEM with bounded recovery and diagnostics - #28737

Merged
XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-mmap-reclaim-enomem
Sep 11, 2026
Merged

XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-mmap-reclaim-enomem

Conversation

@XuPeng-SH

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

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

#28736

What this PR does / why we need it:

Linux can coalesce independently allocated anonymous mappings. Unmapping an interior allocation can require splitting a VMA and fail with ENOMEM at vm.max_map_count. This is not necessarily Go heap OOM or an invalid pointer. The incident's actual VMA count is unavailable; the mechanism is reproduced, not asserted as a confirmed production diagnosis.

Ownership and failure handling

  • Centralize the package's mmap/unmap boundary: cached and direct SimpleCAllocator, HybridMmapAllocator, and fixed-size allocator reclamation. The latter previously discarded unmap errors.
  • On ENOMEM, retain exclusive ownership of the failed mapping; never drop it, reuse it, or acknowledge physical reclamation through the pending metrics.
  • One retry owner, at most 256 mappings per pass, fair rotation, 1/2/4/8/16/30-second backoff without progress. Progress resets the delay to one second. New arrivals cannot start additional workers or reset the backoff.
  • Pause new mappings from this package while any failed mapping remains. Cached/pool reuse and small libc allocation continue. This bounds retained mapping identities by existing live/pool/queued mappings plus concurrently admitted allocations, rather than adding an unbounded stream of new mappings or dropping failed frees at a queue cap.
  • Reopen mmap admission only after all retained mappings have been reclaimed. Other errors (e.g. EINVAL) remain fail-fast, not silently retried.

This is graceful degradation, not a promise that all requests succeed under exhausted VM resources: fresh mmap requests can fail until recovery, and a large backlog drains at a bounded rate. libc/runtime/other packages are outside this admission gate.

Normal-path performance

No new normal-path logs, metric updates, queue locks, or allocations. Successful unmap still goes directly to the syscall; only fresh mmap admission adds one atomic load. Cache/pool hits and small libc paths are unchanged.

Same-source A/B benchmark against main 77dbf5464466b1d5ae784e7d17d92cd1c1c8d17d, on 55 (i7-11700, Linux/amd64): 64-byte and 336-KiB allocations, cache on/off, CPU=1/8, six 300ms samples in each execution order. No additional allocations; no consistent regression across orders. Concurrent timings are noisy, so a further pinned, alternating-order run used CPU 0-7, CPU=8, four 1s samples per binary:

336-KiB case Base median Candidate median
Direct mmap/free 2588 ns/op 2603.5 ns/op (+0.6%)
Cache reuse/free 5854 ns/op 5842 ns/op (-0.2%)

One candidate direct sample was 4013 ns/op; other candidate samples were 2479/2503/2704 ns/op. These are allocator microbenchmarks, not end-to-end SQL results or a claim of mathematically zero overhead.

Incident evidence without storms

  • At most one diagnostic report every 30 seconds across both sustained failures and repeated recovery/failure episodes.
  • Record observation time, errno, first failing address/size and original reclamation stack, pending bytes/mappings, cumulative failed attempts, bounded /proc/self/maps count with completeness flag, max_map_count, kernel version, process memory status and cgroup path.
  • No smaps/page-table walks or VMA-sized buffers. Maps scanning has byte/work-time bounds and runs outside allocator/cache locks, only on the error path.
  • One lazy, process-lifetime log writer and a one-entry buffer. A blocked log sink cannot stall reclaim or create unbounded goroutines/reports; saturated log submissions are dropped. Metrics remain available independently.
  • Scrape-time metrics: mo_mmap_reclaim_pending_bytes, mo_mmap_reclaim_pending_mappings, mo_mmap_reclaim_failures_total. Pending values returning to zero indicate recovery; failure deltas retain evidence of log-suppressed episodes.

Test plan / QA

Completed on final code:

  • Normal and -race -count=1 suites for ./pkg/common/malloc ./pkg/common/mpool.
  • Concurrent ownership and blocked-log-sink tests with -race -count=100.
  • Deterministic tests: partial success/repeated ENOMEM, exactly-once release, concurrent enqueue during detached retry, batch/worker/backoff bounds, flapping log suppression, invalid ownership, blocked new mmap versus continued libc/pool/cache reuse, recovery, diagnostics, and 10,000 submissions to a blocked log sink.
  • Incremental golangci-lint over the affected ./pkg/common/malloc package: zero issues. git diff --check passed.
  • 55 (10.222.1.55), isolated test process, real allocator/cache expiry path, final binary -count=2: three independently allocated adjacent 344064-byte mappings were confirmed coalesced; mprotect-generated VMA pressure caused actual cached munmap ENOMEM; process survived, retained exactly 344064 bytes, rejected fresh mmap, and emitted original-stack diagnostics showing maps=1048576, max_map_count=1048576. Removing pressure allowed retry to release the mapping, pending counters reached zero, and fresh allocations succeeded. Both episodes passed; only one warning was emitted across them.

The pressure test is explicitly opt-in (linux && mmap_reclaim_integration), not part of ordinary CI. It uses up to 1.1M VMAs and approximately 4 GiB of untouched virtual address space; run only on a test host with kernel-memory headroom. It does not change sysctls or start a MatrixOne service. This validates the real allocator/kernel boundary, not a full production-server workload.

.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=180s ./pkg/common/malloc ./pkg/common/mpool
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=100 -timeout=120s -run '^(TestMmapReclaimConcurrentOwnership|TestMmapReclaimBlockedLogSink)$' ./pkg/common/malloc
# Dedicated test host only:
.agents/skills/mo-dev/scripts/mo-cgo-test -tags=mmap_reclaim_integration -count=2 -timeout=45s -v -run '^TestMmapReclaimRealVMAExhaustion$' ./pkg/common/malloc

Review scope

Reviewed all changed allocator entry points, queue ownership across concurrent enqueue/retry, recovery/admission ordering, retry and log bounds, blocked logging, resource accounting, and explicit-test cleanup. Existing valid baseline evidence was reused; no production services or sysctls were changed.

Versioned design and review follow-up

Addresses 4.2 design-gate review.

  • Incident: bug(malloc): mmap cache expiry panics on munmap ENOMEM and restarts CN #28736.
  • Exact reviewed design: v1 at 1c4858f063.
  • Separate design decision and subsequent implementation-alignment record.
  • The record is explicitly a Codex design self-review, not independent human approval or a GitHub APPROVE. Maintainer review remains required. The original missing design phase is acknowledged rather than retroactively claimed.
  • Accepted limits: process-wide fresh-mmap degradation can last indefinitely under persistent pressure; retention is admission-relative, not a fixed byte cap; retries have bounded work/rate, not lifetime; proc diagnostics have a cooperative work budget, not a hard syscall deadline; a blocked log sink can later emit its two retained reports together.
  • Follow-up is docs-only. No runtime/test/dependency changes; existing branch-native UT/race/55 evidence is reused, not falsely reported as rerun. Both PRs carry identical design/decision documents.

@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 requested a review from fengttt as a code owner September 11, 2026 14:15
XuPeng-SH added a commit that referenced this pull request Sep 11, 2026
…gnostics (#28739)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

#28736

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

Linux may coalesce independent mmap allocations. Unmapping an interior
allocation can require a VMA split and return ENOMEM at
`vm.max_map_count`. Retain exclusive ownership and retry instead of
panicking or silently losing the failed mapping.

- Cover this branch's SimpleCAllocator direct/cache reclamation and
fixed-size allocator background reclamation.
- One retry owner, 256 mappings per pass, fair rotation, bounded
exponential backoff (up to 30 seconds).
- Pause fresh package-owned mmap admission while failures remain;
preserve small libc allocation and cache/pool reuse. Resume fresh mmap
only after the pending queue is drained. Retention is bounded by
already-existing mappings plus concurrently admitted allocations, not a
growing stream of fresh mappings. Persistent pressure can still cause
new allocation requests to fail.
- Diagnostics include original reclamation stack, address/size, VMA
count/completeness and limit, kernel, memory status, cgroup and
cumulative/pending counters. One report per 30 seconds across flapping
episodes; a single bounded asynchronous log writer prevents blocked
logging from blocking recovery.
- Export scrape-time `mo_mmap_reclaim_pending_bytes`,
`mo_mmap_reclaim_pending_mappings`, and `mo_mmap_reclaim_failures_total`
metrics. No normal-path log, metric update, queue lock or allocation;
fresh mmap adds only an atomic admission load.

### Branch adaptation / review

Base: `4199b11c5c7bb24eccdb379cd6f68abcbd89e450` (`4.2-dev`).

The recovery/diagnostics implementation and SimpleCAllocator changes are
identical to #28737. This release branch has no HybridMmapAllocator: it
is deliberately **not** introduced. The pool-reuse test uses the
existing `NewFixedSizeMmapAllocator` constructor instead of main's
internal configurable constructor, and the unavailable hybrid-only
assertion is omitted. No allocator selection, dependencies, SQL
semantics, wire/disk formats, or unrelated main changes are backported.

Self-review checked branch-specific constructors/callers, ownership
transfer, detached-batch accounting, recovery/admission ordering,
retry/log bounds and all delivered artifacts. The Q1/Q2/Q3
ownership/wait/growth analysis from the unchanged core is retained; no
additional backport blocker was found.

### Test plan / QA

Newly run on the 4.2-dev patch, all passed:

- All seven `TestMmapReclaim*` deterministic tests, including fault
recovery, partial success, retry/log limits, concurrent ownership,
invalid ownership, admission versus cache/pool reuse, diagnostics and a
blocked log sink.
- Normal and `-race -count=1` full suites for `./pkg/common/malloc
./pkg/common/mpool`.
- `TestMmapReclaimConcurrentOwnership` and
`TestMmapReclaimBlockedLogSink`, each separately with `-race
-count=100`.
- Incremental golangci-lint for the affected `./pkg/common/malloc`
package: zero issues; `git diff --check` passed.
- Final 4.2-dev test binary on 55 (`10.222.1.55`), real allocator/cache
expiry and kernel ENOMEM, `-count=2`: each episode retained exactly one
344064-byte mapping without panic, rejected fresh mmap under pressure,
reclaimed it after pressure removal, reached zero pending bytes/mappings
and accepted fresh allocation. One warning across both episodes included
`maps=1048576`, `max_map_count=1048576` and the original cache expiry
stack. Both episodes passed (3.85s / 3.76s).

Native CGo was rebuilt from this branch's CPU sources with matching
third-party versions; Go 1.26.4 and this branch's module versions were
used. The real kernel experiment was rerun rather than assuming main's
result covers release dependencies.

Normal-path performance evidence is linked in #28737, not relabeled as a
new release-branch A/B measurement. SimpleCAllocator, the recovery
hot-path code, benchmark and the x/sys mmap bookkeeping source are
unchanged across the relevant versions; no extra hot-path work was
introduced by the adaptation. No full SQL/BVT run is claimed: the
changed boundary is allocator/kernel ownership, with no SQL or protocol
change.

```sh
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=120s ./pkg/common/malloc ./pkg/common/mpool
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=180s ./pkg/common/malloc ./pkg/common/mpool
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=100 -timeout=120s -run '^TestMmapReclaimConcurrentOwnership$' ./pkg/common/malloc
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=100 -timeout=120s -run '^TestMmapReclaimBlockedLogSink$' ./pkg/common/malloc
# Dedicated test host only, never a production service:
.agents/skills/mo-dev/scripts/mo-cgo-test -tags=mmap_reclaim_integration -count=2 -timeout=45s -v -run '^TestMmapReclaimRealVMAExhaustion$' ./pkg/common/malloc
```

The opt-in pressure experiment creates up to 1.1M VMAs and about 4 GiB
untouched virtual address space; it requires kernel-memory headroom. It
changes no sysctl and starts no MatrixOne service. Ordinary CI does not
enable the integration build tag.


### Versioned design and review follow-up

Addresses [4.2 design-gate
review](#28739 (review)).

- Incident: #28736.
- Exact reviewed design: [v1 at
1c4858f](https://github.com/XuPeng-SH/matrixone/blob/1c4858f0636362cfb0ace04d6d386fd066f14dd3/docs/design/mmap-reclamation.md).
- [Separate design decision and subsequent implementation-alignment
record](https://github.com/XuPeng-SH/matrixone/blob/10979864f895eb7f6ad525e723b9ae3fb091d680/docs/design/mmap-reclamation-review.md).
- The record is explicitly a Codex design **self-review**, not
independent human approval or a GitHub APPROVE. Maintainer review
remains required. The original missing design phase is acknowledged
rather than retroactively claimed.
- Accepted limits: process-wide fresh-mmap degradation can last
indefinitely under persistent pressure; retention is admission-relative,
not a fixed byte cap; retries have bounded work/rate, not lifetime; proc
diagnostics have a cooperative work budget, not a hard syscall deadline;
a blocked log sink can later emit its two retained reports together.
- Follow-up is docs-only. No runtime/test/dependency changes; existing
branch-native UT/race/55 evidence is reused, not falsely reported as
rerun. Both PRs carry identical design/decision documents.

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

Reviewed 6f2ab380c385bb66e9fda86c2fc3bb9a2523b3a2 against main@a0770f5dc4a296f8407bbebf6a2664bac9972e53. COMMENT only for this self-authored PR.

No concrete blocker found. Design PASS and implementation alignment PASS within the documented containment scope.

The exact versioned design and decision documents are byte-identical to those independently reviewed for #28739. The design closes the original gate: alternatives, exclusive mapping ownership, admission-relative bounds, persistent-pressure degradation, retry/logging budgets and operational recovery are explicit. This is not a waiver of ordinary maintainer/merge requirements.

Compared the full 11-file change map with #28739: recovery/diagnostics, SimpleCAllocator/cache, benchmark and opt-in pressure-test blobs are identical. Reused the shared ownership/concurrency analysis, then traced main's additional HybridMmapAllocator integration. Large/direct hybrid allocations retain their page-rounded backing length in the deallocator rather than using the returned user slice length; failed exact mappings transfer to unmapMemory and never return to reuse pools. Small hybrid allocations use the existing fixed-size pool path, whose fresh mmap is gated while pool reuse remains possible. The main test adds hybrid direct-allocation rejection and uses the configurable fixed-size constructor. Main's actual x/sys v0.47.0 Munmap was checked separately: registration remains on syscall error and is deleted only on success, preserving the retry prerequisite.

The shared controller keeps detached batches accounted, admits one retry owner, rotates failed mappings, and reopens admission only after pending ownership drains. Non-ENOMEM remains fail-fast. Batch size/backoff and retained log reports are bounded; retry lifetime and service degradation are intentionally not time-bounded. Proc diagnostics have a cooperative budget, not a cancellable syscall deadline. No request cancellation discards cleanup ownership, and the process-lifetime state is not reused across restarts. No disk/wire migration is introduced.

Performance/evidence limits: fresh mmap adds an atomic check; reuse/successful-free paths do not enter the retry queue. Reused author-reported main malloc/mpool normal/race suites, focused race x100, real-kernel recovery x2 and same-source allocator A/B measurements, with their stated noise and workload limits. These are not tests or benchmarks I independently reran, nor proof of the original production incident's exact cause. No CI wait or large native suite. Exact live head/base rechecked before posting.

@XuPeng-SH
XuPeng-SH merged commit 06de981 into matrixorigin:main Sep 11, 2026
16 of 19 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/fix-mmap-reclaim-enomem branch September 11, 2026 16:42
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…cs (matrixorigin#28737)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

matrixorigin#28736

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

Linux can coalesce independently allocated anonymous mappings. Unmapping
an interior allocation can require splitting a VMA and fail with ENOMEM
at `vm.max_map_count`. This is not necessarily Go heap OOM or an invalid
pointer. The incident's actual VMA count is unavailable; the mechanism
is reproduced, not asserted as a confirmed production diagnosis.

### Ownership and failure handling

- Centralize the package's mmap/unmap boundary: cached and direct
SimpleCAllocator, HybridMmapAllocator, and fixed-size allocator
reclamation. The latter previously discarded unmap errors.
- On ENOMEM, retain exclusive ownership of the failed mapping; never
drop it, reuse it, or acknowledge physical reclamation through the
pending metrics.
- One retry owner, at most 256 mappings per pass, fair rotation,
1/2/4/8/16/30-second backoff without progress. Progress resets the delay
to one second. New arrivals cannot start additional workers or reset the
backoff.
- Pause new mappings from this package while any failed mapping remains.
Cached/pool reuse and small libc allocation continue. This bounds
retained mapping identities by existing live/pool/queued mappings plus
concurrently admitted allocations, rather than adding an unbounded
stream of new mappings or dropping failed frees at a queue cap.
- Reopen mmap admission only after all retained mappings have been
reclaimed. Other errors (e.g. EINVAL) remain fail-fast, not silently
retried.

This is graceful degradation, not a promise that all requests succeed
under exhausted VM resources: fresh mmap requests can fail until
recovery, and a large backlog drains at a bounded rate.
libc/runtime/other packages are outside this admission gate.

### Normal-path performance

No new normal-path logs, metric updates, queue locks, or allocations.
Successful unmap still goes directly to the syscall; only fresh mmap
admission adds one atomic load. Cache/pool hits and small libc paths are
unchanged.

Same-source A/B benchmark against main
`77dbf5464466b1d5ae784e7d17d92cd1c1c8d17d`, on 55 (i7-11700,
Linux/amd64): 64-byte and 336-KiB allocations, cache on/off, CPU=1/8,
six 300ms samples in each execution order. No additional allocations; no
consistent regression across orders. Concurrent timings are noisy, so a
further pinned, alternating-order run used CPU 0-7, CPU=8, four 1s
samples per binary:

| 336-KiB case | Base median | Candidate median |
|---|---:|---:|
| Direct mmap/free | 2588 ns/op | 2603.5 ns/op (+0.6%) |
| Cache reuse/free | 5854 ns/op | 5842 ns/op (-0.2%) |

One candidate direct sample was 4013 ns/op; other candidate samples were
2479/2503/2704 ns/op. These are allocator microbenchmarks, not
end-to-end SQL results or a claim of mathematically zero overhead.

### Incident evidence without storms

- At most one diagnostic report every 30 seconds across both sustained
failures and repeated recovery/failure episodes.
- Record observation time, errno, first failing address/size and
original reclamation stack, pending bytes/mappings, cumulative failed
attempts, bounded `/proc/self/maps` count with completeness flag,
max_map_count, kernel version, process memory status and cgroup path.
- No smaps/page-table walks or VMA-sized buffers. Maps scanning has
byte/work-time bounds and runs outside allocator/cache locks, only on
the error path.
- One lazy, process-lifetime log writer and a one-entry buffer. A
blocked log sink cannot stall reclaim or create unbounded
goroutines/reports; saturated log submissions are dropped. Metrics
remain available independently.
- Scrape-time metrics: `mo_mmap_reclaim_pending_bytes`,
`mo_mmap_reclaim_pending_mappings`, `mo_mmap_reclaim_failures_total`.
Pending values returning to zero indicate recovery; failure deltas
retain evidence of log-suppressed episodes.

### Test plan / QA

Completed on final code:

- Normal and `-race -count=1` suites for `./pkg/common/malloc
./pkg/common/mpool`.
- Concurrent ownership and blocked-log-sink tests with `-race
-count=100`.
- Deterministic tests: partial success/repeated ENOMEM, exactly-once
release, concurrent enqueue during detached retry, batch/worker/backoff
bounds, flapping log suppression, invalid ownership, blocked new mmap
versus continued libc/pool/cache reuse, recovery, diagnostics, and
10,000 submissions to a blocked log sink.
- Incremental golangci-lint over the affected `./pkg/common/malloc`
package: zero issues. `git diff --check` passed.
- 55 (`10.222.1.55`), isolated test process, real allocator/cache expiry
path, final binary `-count=2`: three independently allocated adjacent
344064-byte mappings were confirmed coalesced; mprotect-generated VMA
pressure caused actual cached munmap ENOMEM; process survived, retained
exactly 344064 bytes, rejected fresh mmap, and emitted original-stack
diagnostics showing `maps=1048576`, `max_map_count=1048576`. Removing
pressure allowed retry to release the mapping, pending counters reached
zero, and fresh allocations succeeded. Both episodes passed; only one
warning was emitted across them.

The pressure test is explicitly opt-in (`linux &&
mmap_reclaim_integration`), not part of ordinary CI. It uses up to 1.1M
VMAs and approximately 4 GiB of untouched virtual address space; run
only on a test host with kernel-memory headroom. It does not change
sysctls or start a MatrixOne service. This validates the real
allocator/kernel boundary, not a full production-server workload.

```sh
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=180s ./pkg/common/malloc ./pkg/common/mpool
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=100 -timeout=120s -run '^(TestMmapReclaimConcurrentOwnership|TestMmapReclaimBlockedLogSink)$' ./pkg/common/malloc
# Dedicated test host only:
.agents/skills/mo-dev/scripts/mo-cgo-test -tags=mmap_reclaim_integration -count=2 -timeout=45s -v -run '^TestMmapReclaimRealVMAExhaustion$' ./pkg/common/malloc
```

### Review scope

Reviewed all changed allocator entry points, queue ownership across
concurrent enqueue/retry, recovery/admission ordering, retry and log
bounds, blocked logging, resource accounting, and explicit-test cleanup.
Existing valid baseline evidence was reused; no production services or
sysctls were changed.


### Versioned design and review follow-up

Addresses [4.2 design-gate
review](matrixorigin#28739 (review)).

- Incident: matrixorigin#28736.
- Exact reviewed design: [v1 at
1c4858f](https://github.com/XuPeng-SH/matrixone/blob/1c4858f0636362cfb0ace04d6d386fd066f14dd3/docs/design/mmap-reclamation.md).
- [Separate design decision and subsequent implementation-alignment
record](https://github.com/XuPeng-SH/matrixone/blob/6f2ab380c385bb66e9fda86c2fc3bb9a2523b3a2/docs/design/mmap-reclamation-review.md).
- The record is explicitly a Codex design **self-review**, not
independent human approval or a GitHub APPROVE. Maintainer review
remains required. The original missing design phase is acknowledged
rather than retroactively claimed.
- Accepted limits: process-wide fresh-mmap degradation can last
indefinitely under persistent pressure; retention is admission-relative,
not a fixed byte cap; retries have bounded work/rate, not lifetime; proc
diagnostics have a cooperative work budget, not a hard syscall deadline;
a blocked log sink can later emit its two retained reports together.
- Follow-up is docs-only. No runtime/test/dependency changes; existing
branch-native UT/race/55 evidence is reused, not falsely reported as
rerun. Both PRs carry identical design/decision documents.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…cs (matrixorigin#28737)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

matrixorigin#28736

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

Linux can coalesce independently allocated anonymous mappings. Unmapping
an interior allocation can require splitting a VMA and fail with ENOMEM
at `vm.max_map_count`. This is not necessarily Go heap OOM or an invalid
pointer. The incident's actual VMA count is unavailable; the mechanism
is reproduced, not asserted as a confirmed production diagnosis.

### Ownership and failure handling

- Centralize the package's mmap/unmap boundary: cached and direct
SimpleCAllocator, HybridMmapAllocator, and fixed-size allocator
reclamation. The latter previously discarded unmap errors.
- On ENOMEM, retain exclusive ownership of the failed mapping; never
drop it, reuse it, or acknowledge physical reclamation through the
pending metrics.
- One retry owner, at most 256 mappings per pass, fair rotation,
1/2/4/8/16/30-second backoff without progress. Progress resets the delay
to one second. New arrivals cannot start additional workers or reset the
backoff.
- Pause new mappings from this package while any failed mapping remains.
Cached/pool reuse and small libc allocation continue. This bounds
retained mapping identities by existing live/pool/queued mappings plus
concurrently admitted allocations, rather than adding an unbounded
stream of new mappings or dropping failed frees at a queue cap.
- Reopen mmap admission only after all retained mappings have been
reclaimed. Other errors (e.g. EINVAL) remain fail-fast, not silently
retried.

This is graceful degradation, not a promise that all requests succeed
under exhausted VM resources: fresh mmap requests can fail until
recovery, and a large backlog drains at a bounded rate.
libc/runtime/other packages are outside this admission gate.

### Normal-path performance

No new normal-path logs, metric updates, queue locks, or allocations.
Successful unmap still goes directly to the syscall; only fresh mmap
admission adds one atomic load. Cache/pool hits and small libc paths are
unchanged.

Same-source A/B benchmark against main
`77dbf5464466b1d5ae784e7d17d92cd1c1c8d17d`, on 55 (i7-11700,
Linux/amd64): 64-byte and 336-KiB allocations, cache on/off, CPU=1/8,
six 300ms samples in each execution order. No additional allocations; no
consistent regression across orders. Concurrent timings are noisy, so a
further pinned, alternating-order run used CPU 0-7, CPU=8, four 1s
samples per binary:

| 336-KiB case | Base median | Candidate median |
|---|---:|---:|
| Direct mmap/free | 2588 ns/op | 2603.5 ns/op (+0.6%) |
| Cache reuse/free | 5854 ns/op | 5842 ns/op (-0.2%) |

One candidate direct sample was 4013 ns/op; other candidate samples were
2479/2503/2704 ns/op. These are allocator microbenchmarks, not
end-to-end SQL results or a claim of mathematically zero overhead.

### Incident evidence without storms

- At most one diagnostic report every 30 seconds across both sustained
failures and repeated recovery/failure episodes.
- Record observation time, errno, first failing address/size and
original reclamation stack, pending bytes/mappings, cumulative failed
attempts, bounded `/proc/self/maps` count with completeness flag,
max_map_count, kernel version, process memory status and cgroup path.
- No smaps/page-table walks or VMA-sized buffers. Maps scanning has
byte/work-time bounds and runs outside allocator/cache locks, only on
the error path.
- One lazy, process-lifetime log writer and a one-entry buffer. A
blocked log sink cannot stall reclaim or create unbounded
goroutines/reports; saturated log submissions are dropped. Metrics
remain available independently.
- Scrape-time metrics: `mo_mmap_reclaim_pending_bytes`,
`mo_mmap_reclaim_pending_mappings`, `mo_mmap_reclaim_failures_total`.
Pending values returning to zero indicate recovery; failure deltas
retain evidence of log-suppressed episodes.

### Test plan / QA

Completed on final code:

- Normal and `-race -count=1` suites for `./pkg/common/malloc
./pkg/common/mpool`.
- Concurrent ownership and blocked-log-sink tests with `-race
-count=100`.
- Deterministic tests: partial success/repeated ENOMEM, exactly-once
release, concurrent enqueue during detached retry, batch/worker/backoff
bounds, flapping log suppression, invalid ownership, blocked new mmap
versus continued libc/pool/cache reuse, recovery, diagnostics, and
10,000 submissions to a blocked log sink.
- Incremental golangci-lint over the affected `./pkg/common/malloc`
package: zero issues. `git diff --check` passed.
- 55 (`10.222.1.55`), isolated test process, real allocator/cache expiry
path, final binary `-count=2`: three independently allocated adjacent
344064-byte mappings were confirmed coalesced; mprotect-generated VMA
pressure caused actual cached munmap ENOMEM; process survived, retained
exactly 344064 bytes, rejected fresh mmap, and emitted original-stack
diagnostics showing `maps=1048576`, `max_map_count=1048576`. Removing
pressure allowed retry to release the mapping, pending counters reached
zero, and fresh allocations succeeded. Both episodes passed; only one
warning was emitted across them.

The pressure test is explicitly opt-in (`linux &&
mmap_reclaim_integration`), not part of ordinary CI. It uses up to 1.1M
VMAs and approximately 4 GiB of untouched virtual address space; run
only on a test host with kernel-memory headroom. It does not change
sysctls or start a MatrixOne service. This validates the real
allocator/kernel boundary, not a full production-server workload.

```sh
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=180s ./pkg/common/malloc ./pkg/common/mpool
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=100 -timeout=120s -run '^(TestMmapReclaimConcurrentOwnership|TestMmapReclaimBlockedLogSink)$' ./pkg/common/malloc
# Dedicated test host only:
.agents/skills/mo-dev/scripts/mo-cgo-test -tags=mmap_reclaim_integration -count=2 -timeout=45s -v -run '^TestMmapReclaimRealVMAExhaustion$' ./pkg/common/malloc
```

### Review scope

Reviewed all changed allocator entry points, queue ownership across
concurrent enqueue/retry, recovery/admission ordering, retry and log
bounds, blocked logging, resource accounting, and explicit-test cleanup.
Existing valid baseline evidence was reused; no production services or
sysctls were changed.


### Versioned design and review follow-up

Addresses [4.2 design-gate
review](matrixorigin#28739 (review)).

- Incident: matrixorigin#28736.
- Exact reviewed design: [v1 at
1c4858f](https://github.com/XuPeng-SH/matrixone/blob/1c4858f0636362cfb0ace04d6d386fd066f14dd3/docs/design/mmap-reclamation.md).
- [Separate design decision and subsequent implementation-alignment
record](https://github.com/XuPeng-SH/matrixone/blob/6f2ab380c385bb66e9fda86c2fc3bb9a2523b3a2/docs/design/mmap-reclamation-review.md).
- The record is explicitly a Codex design **self-review**, not
independent human approval or a GitHub APPROVE. Maintainer review
remains required. The original missing design phase is acknowledged
rather than retroactively claimed.
- Accepted limits: process-wide fresh-mmap degradation can last
indefinitely under persistent pressure; retention is admission-relative,
not a fixed byte cap; retries have bounded work/rate, not lifetime; proc
diagnostics have a cooperative work budget, not a hard syscall deadline;
a blocked log sink can later emit its two retained reports together.
- Follow-up is docs-only. No runtime/test/dependency changes; existing
branch-native UT/race/55 evidence is reused, not falsely reported as
rerun. Both PRs carry identical design/decision documents.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…cs (matrixorigin#28737)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

matrixorigin#28736

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

Linux can coalesce independently allocated anonymous mappings. Unmapping
an interior allocation can require splitting a VMA and fail with ENOMEM
at `vm.max_map_count`. This is not necessarily Go heap OOM or an invalid
pointer. The incident's actual VMA count is unavailable; the mechanism
is reproduced, not asserted as a confirmed production diagnosis.

### Ownership and failure handling

- Centralize the package's mmap/unmap boundary: cached and direct
SimpleCAllocator, HybridMmapAllocator, and fixed-size allocator
reclamation. The latter previously discarded unmap errors.
- On ENOMEM, retain exclusive ownership of the failed mapping; never
drop it, reuse it, or acknowledge physical reclamation through the
pending metrics.
- One retry owner, at most 256 mappings per pass, fair rotation,
1/2/4/8/16/30-second backoff without progress. Progress resets the delay
to one second. New arrivals cannot start additional workers or reset the
backoff.
- Pause new mappings from this package while any failed mapping remains.
Cached/pool reuse and small libc allocation continue. This bounds
retained mapping identities by existing live/pool/queued mappings plus
concurrently admitted allocations, rather than adding an unbounded
stream of new mappings or dropping failed frees at a queue cap.
- Reopen mmap admission only after all retained mappings have been
reclaimed. Other errors (e.g. EINVAL) remain fail-fast, not silently
retried.

This is graceful degradation, not a promise that all requests succeed
under exhausted VM resources: fresh mmap requests can fail until
recovery, and a large backlog drains at a bounded rate.
libc/runtime/other packages are outside this admission gate.

### Normal-path performance

No new normal-path logs, metric updates, queue locks, or allocations.
Successful unmap still goes directly to the syscall; only fresh mmap
admission adds one atomic load. Cache/pool hits and small libc paths are
unchanged.

Same-source A/B benchmark against main
`77dbf5464466b1d5ae784e7d17d92cd1c1c8d17d`, on 55 (i7-11700,
Linux/amd64): 64-byte and 336-KiB allocations, cache on/off, CPU=1/8,
six 300ms samples in each execution order. No additional allocations; no
consistent regression across orders. Concurrent timings are noisy, so a
further pinned, alternating-order run used CPU 0-7, CPU=8, four 1s
samples per binary:

| 336-KiB case | Base median | Candidate median |
|---|---:|---:|
| Direct mmap/free | 2588 ns/op | 2603.5 ns/op (+0.6%) |
| Cache reuse/free | 5854 ns/op | 5842 ns/op (-0.2%) |

One candidate direct sample was 4013 ns/op; other candidate samples were
2479/2503/2704 ns/op. These are allocator microbenchmarks, not
end-to-end SQL results or a claim of mathematically zero overhead.

### Incident evidence without storms

- At most one diagnostic report every 30 seconds across both sustained
failures and repeated recovery/failure episodes.
- Record observation time, errno, first failing address/size and
original reclamation stack, pending bytes/mappings, cumulative failed
attempts, bounded `/proc/self/maps` count with completeness flag,
max_map_count, kernel version, process memory status and cgroup path.
- No smaps/page-table walks or VMA-sized buffers. Maps scanning has
byte/work-time bounds and runs outside allocator/cache locks, only on
the error path.
- One lazy, process-lifetime log writer and a one-entry buffer. A
blocked log sink cannot stall reclaim or create unbounded
goroutines/reports; saturated log submissions are dropped. Metrics
remain available independently.
- Scrape-time metrics: `mo_mmap_reclaim_pending_bytes`,
`mo_mmap_reclaim_pending_mappings`, `mo_mmap_reclaim_failures_total`.
Pending values returning to zero indicate recovery; failure deltas
retain evidence of log-suppressed episodes.

### Test plan / QA

Completed on final code:

- Normal and `-race -count=1` suites for `./pkg/common/malloc
./pkg/common/mpool`.
- Concurrent ownership and blocked-log-sink tests with `-race
-count=100`.
- Deterministic tests: partial success/repeated ENOMEM, exactly-once
release, concurrent enqueue during detached retry, batch/worker/backoff
bounds, flapping log suppression, invalid ownership, blocked new mmap
versus continued libc/pool/cache reuse, recovery, diagnostics, and
10,000 submissions to a blocked log sink.
- Incremental golangci-lint over the affected `./pkg/common/malloc`
package: zero issues. `git diff --check` passed.
- 55 (`10.222.1.55`), isolated test process, real allocator/cache expiry
path, final binary `-count=2`: three independently allocated adjacent
344064-byte mappings were confirmed coalesced; mprotect-generated VMA
pressure caused actual cached munmap ENOMEM; process survived, retained
exactly 344064 bytes, rejected fresh mmap, and emitted original-stack
diagnostics showing `maps=1048576`, `max_map_count=1048576`. Removing
pressure allowed retry to release the mapping, pending counters reached
zero, and fresh allocations succeeded. Both episodes passed; only one
warning was emitted across them.

The pressure test is explicitly opt-in (`linux &&
mmap_reclaim_integration`), not part of ordinary CI. It uses up to 1.1M
VMAs and approximately 4 GiB of untouched virtual address space; run
only on a test host with kernel-memory headroom. It does not change
sysctls or start a MatrixOne service. This validates the real
allocator/kernel boundary, not a full production-server workload.

```sh
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=180s ./pkg/common/malloc ./pkg/common/mpool
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=100 -timeout=120s -run '^(TestMmapReclaimConcurrentOwnership|TestMmapReclaimBlockedLogSink)$' ./pkg/common/malloc
# Dedicated test host only:
.agents/skills/mo-dev/scripts/mo-cgo-test -tags=mmap_reclaim_integration -count=2 -timeout=45s -v -run '^TestMmapReclaimRealVMAExhaustion$' ./pkg/common/malloc
```

### Review scope

Reviewed all changed allocator entry points, queue ownership across
concurrent enqueue/retry, recovery/admission ordering, retry and log
bounds, blocked logging, resource accounting, and explicit-test cleanup.
Existing valid baseline evidence was reused; no production services or
sysctls were changed.


### Versioned design and review follow-up

Addresses [4.2 design-gate
review](matrixorigin#28739 (review)).

- Incident: matrixorigin#28736.
- Exact reviewed design: [v1 at
1c4858f](https://github.com/XuPeng-SH/matrixone/blob/1c4858f0636362cfb0ace04d6d386fd066f14dd3/docs/design/mmap-reclamation.md).
- [Separate design decision and subsequent implementation-alignment
record](https://github.com/XuPeng-SH/matrixone/blob/6f2ab380c385bb66e9fda86c2fc3bb9a2523b3a2/docs/design/mmap-reclamation-review.md).
- The record is explicitly a Codex design **self-review**, not
independent human approval or a GitHub APPROVE. Maintainer review
remains required. The original missing design phase is acknowledged
rather than retroactively claimed.
- Accepted limits: process-wide fresh-mmap degradation can last
indefinitely under persistent pressure; retention is admission-relative,
not a fixed byte cap; retries have bounded work/rate, not lifetime; proc
diagnostics have a cooperative work budget, not a hard syscall deadline;
a blocked log sink can later emit its two retained reports together.
- Follow-up is docs-only. No runtime/test/dependency changes; existing
branch-native UT/race/55 evidence is reused, not falsely reported as
rerun. Both PRs carry identical design/decision documents.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/enhancement size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants