Skip to content

[4.2] fix(malloc): handle munmap ENOMEM with bounded recovery and diagnostics - #28739

Merged
XuPeng-SH merged 3 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:codex/4.2-fix-mmap-reclaim-enomem
Sep 11, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:codex/4.2-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?

  • API-change
  • BUG
  • 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.

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

  • 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 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 head 2e2a5b31e4e174a9251a0566befa0683180e3fd4 against 4.2-dev@4199b11c5c7bb24eccdb379cd6f68abcbd89e450. COMMENT only because this is a self-authored PR.

[P1] Complete the required design-first gate for the recovery/admission controller before landing. This is more than changing an errno branch: mmap_reclaim.go:35-81,112-215 introduces process-wide allocation-admission state, exclusive deferred mapping ownership, a retry queue/state machine, and a long-lived asynchronous reporting owner. A single retained mapping can now reject all fresh package-owned mmap allocations until recovery. These are explicit lifecycle/resource-controller/availability complexity triggers in the repository's feature-design-review contract, including when delivered as the #28737/#28739 series. Neither PR currently links an exact, stable versioned design revision with a traceable design approval; the detailed implementation/QA descriptions and incident issue #28736 do not satisfy that mandatory artifact gate.

Suggested closure: link a versioned design for the shared controller, record its distinct design review/approval, and identify the 4.2-specific adaptation. Cover the admission scope and in-flight allowance, ownership through failed/retried munmap, persistent-pressure behavior and operational recovery, alternatives, retry/log resource bounds, platform assumptions, and acceptance evidence. This need not be an RFC or duplicate the main-branch design.

Implementation observations (not a full implementation PASS while the gate is open): the changed surfaces cover SimpleCAllocator direct/cache reclamation and fixed-size background reclamation without importing the absent HybridMmapAllocator. Detached batches remain included in pending accounting; concurrent enqueue does not create another retry owner; unsuccessful mappings rotate behind queued arrivals; admission reopens only at zero pending count. Retry work is capped at 256 mappings/pass with delay capped at 30 seconds, and logging has one writer plus one buffered report. The retry lifetime is intentionally unbounded under persistent pressure, distinct from the bounded work/rate claim. No concrete additional runtime defect was established in this pass.

Evidence/limits: read the complete eight-file diff, PR/incident descriptions, comments, and the main-branch series description; inspected deterministic recovery/concurrency/admission/logging tests and opt-in real-VMA test. The author reports branch-native malloc/mpool normal/race suites, repeated concurrency tests, and two real-kernel pressure/recovery episodes; these are reused author-reported evidence, not tests I independently executed. No CI wait or large native test run. Head and base rechecked immediately before submission.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Addressed the design-gate review in 1c4858f + 1097986. Added a versioned design covering alternatives, admission/in-flight scope, ownership, persistent-pressure availability, retry/log bounds, platform assumptions, rollout and acceptance; then recorded a separate design self-review and subsequent implementation-alignment decision. Both exact revisions are linked in the PR body. This is explicitly not independent human approval. No new runtime defect was established, so this follow-up changes documentation only and reuses the unchanged branch-native UT/race/55 evidence. The identical documents are also pushed to main PR #28737 (a38980c + 6f2ab38), preserving its intervening main merge.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Re-review of 10979864f895eb7f6ad525e723b9ae3fb091d680 against 4.2-dev@4199b11c5c7bb24eccdb379cd6f68abcbd89e450. COMMENT only for this self-authored PR.

Conclusion: the previous P1 design-gate finding is closed; no remaining concrete blocker found.

Design phase: I independently reviewed design v1 at its exact revision, followed by the separate decision record. Design PASS for the stated containment scope. The artifact now compares credible alternatives, defines ownership and admission/in-flight bounds, explicitly accepts persistent-pressure availability degradation, distinguishes bounded retry work/rate from lifetime, documents cooperative proc diagnostics rather than a hard deadline, and covers operations, rollback, platform assumptions and acceptance criteria. This closes the missing artifact/decision requirement; it does not retroactively make the original implementation design-first, impersonate human approval, or waive normal merge requirements.

Implementation alignment and counterexamples checked:

  • The two new commits change documentation only. The full current change still routes 4.2 SimpleCAllocator direct/cache release and fixed-size background release through one owner; it does not import main's absent HybridMmapAllocator.
  • Cache expiry detaches entries under its mutex before release. Failed mappings never re-enter reuse pools. The actual dependency, x/sys v0.44.0, retains mmap registration on syscall failure and deletes it only after successful munmap, permitting exact-slice retry without losing wrapper ownership.
  • A detached retry batch remains accounted while concurrent failures append; enqueue cannot start another retry owner. Success removes ownership once, failed entries rotate to the tail, and admission reopens only after pending accounting reaches zero. Already-admitted allocations may finish after closure, as the design explicitly allows.
  • Permanent pressure retains ownership and continues bounded-rate retry rather than falsely reporting reclamation. It can indefinitely reject fresh package mmap; this is an explicit accepted tradeoff, not a guaranteed recovery timeout. libc and reuse paths remain available.
  • Retry batches, backoff, diagnostic storage and logging queue are bounded. A blocked log writer does not hold the reclaim path; proc reads can delay a pass beyond the cooperative budget, as now documented. Non-ENOMEM remains fail-fast. Process exit, not request cancellation, is the terminal cleanup for the process-lifetime controller.
  • No SQL, disk/catalog or wire contract changes. Normal cache/pool hits are unchanged; fresh mmap adds the atomic admission check. The Linux-specific VMA test is opt-in and not silently added to ordinary CI.

Evidence/limits: read the full current change map and both new documents, rechecked affected consumers/dependency ownership, and reused the unchanged deterministic test coverage plus author-reported branch-native malloc/mpool normal/race, focused race repetitions and real-kernel recovery x2 evidence. No independent native suite, pressure experiment or benchmark was rerun; main's A/B figures are not represented as new 4.2 measurements. No CI wait. Exact live head/base rechecked immediately before this submission.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

复审结论:Approve,未发现新的确定性 blocker。

范围:HEAD 1097986,base/merge-base 4199b11(4.2-dev)。完整检查 10 个变更文件,在独立干净 worktree 复核;相对 2e2a5b3 的后续提交仅新增两份设计文档,运行代码、测试和依赖未改变。

设计阶段:复核 v1@1c4858f063 与单独设计决策记录,认可其作为失败隔离方案的设计 PASS。上轮设计门禁已闭环,不重复提出已解决的文档问题。它不是 arena/VMA 碎片根治,也不保证持续 ENOMEM 下请求成功;单个 pending mapping 可持续阻止全进程新的 package-owned mmap。该可用性取舍已明确记录,不能解读为无限可用或固定恢复时间。

实现与 unhappy-path 复核:

维度 结论
Q1 所有权 direct/cache/fixed-size 释放统一进入同一回收边界;cache 先摘除再释放,失败映射不回池;x/sys v0.44.0 在 munmap 失败时保留登记,成功才删除,支持原始 slice 重试
Q2 等待 单 retry owner,队列锁不跨 unmap/proc/log I/O;日志阻塞不阻塞回收;kernel/proc 延迟与持续压力不是硬 deadline,符合文档限制
Q3 增长 detached batch 仍计入 pending,失败轮转;最多 256 次/pass,退避最高 30 秒;关闭新 mmap 准入约束后续映射来源,日志最多一个执行中和一个等待中

特别检查了并发 enqueue 与批次摘除/回填、最后成功后 reopen 的顺序、EINVAL fail-fast、小块 libc 与 cache/pool reuse、失败后重新分配以及指标快照。4.2 未引入 HybridMmapAllocator。没有 SQL、catalog/disk/wire 或持久化恢复格式变化;正常成功释放仍直接 syscall,新 mmap 增加 atomic admission check。

证据:最新 HEAD 的 CI run 34609047497 已 completed/success,包括 Linux UT、UT Coverage、Linux/arm64 SCA 与 Compose BVT,CI Required 成功。复用语义未变的作者报告:4.2-native malloc/mpool normal/race、两个 focused race x100、隔离 Linux 真实 ENOMEM/recovery x2;这些不是本轮独立重跑的结果。阅读全部新测试及 benchmark,git diff --check 通过。本轮未启动服务、高内存 VMA 压力测试或额外全量 UT;main 的微基准不冒充 4.2 新测结果。

上线仍建议 canary 观察 pending mappings/bytes 持续时间、allocation errors 和吞吐延迟;持续 pending 应按文档检查节点 map-count/内存压力并采取运维措施,不强制丢弃 pending ownership。

@XuPeng-SH
XuPeng-SH merged commit 7d150ee into matrixorigin:4.2-dev Sep 11, 2026
27 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/4.2-fix-mmap-reclaim-enomem branch September 11, 2026 16:29
XuPeng-SH added a commit that referenced this pull request Sep 11, 2026
…cs (#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:

#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](#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/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>
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.

3 participants