Skip to content

bug(malloc): mmap cache expiry panics on munmap ENOMEM and restarts CN #28736

Closed

Description

@volgariver6

现象

生产 CN mo-db/mo-cng1-cn-djmnn 在 2026-09-11 11:21:41 UTC 异常退出,Kubernetes 记录为 Reason=Error、ExitCode=2,并在 11:21:42 UTC 重启。镜像为 mocloud/matrixone:v4.2.0-9bf92dc56-2026-08-28。

kubectl logs --previous 的末尾:

ERROR malloc/sane_allocator_cache.go:158
error: internal error: failed to unmap cached 344064-byte allocation: cannot allocate memory
panic: internal error: failed to unmap cached 344064-byte allocation: cannot allocate memory

goroutine ... [running]:
.../pkg/common/malloc.unmapSimpleCAllocatorCacheEntries
.../pkg/common/malloc.(*simpleCAllocatorMmapCache).expire
.../pkg/common/malloc.(*simpleCAllocatorMmapCache).put.func1

该 Pod 的 memory limit 是 20 GiB,Kubernetes 未报告 OOMKilled;崩溃是 MO 自己在后台 mmap-cache expiry goroutine 中 panic,而不是 kubelet 因 cgroup OOM、探针失败或驱逐重启。

代码路径

  • SimpleCAllocator 对 >=128 KiB 的 off-heap 请求使用独立匿名 mmap:
    func simpleCAllocatorUsesMmap(size uint64) bool {
    return size >= simpleCAllocatorMmapThreshold
    }
    func (sca *SimpleCAllocator) allocateMemory(size uint64, clearMemory bool) ([]byte, error) {
    if simpleCAllocatorUsesMmap(size) {
    if size > uint64(maxIntValue()) {
    return nil, moerr.NewOOMNoCtx()
    }
    // MADV_FREE pages remain reclaimable until written. Allocate clears the
    // whole mapping below and therefore safely reclaims ownership of every
    // page. Malloc cannot reuse them because its no-clear contract would
    // leave untouched pages reclaimable after they were handed to a caller.
    if clearMemory && sca.mmapCache != nil {
    if slice, ok := sca.mmapCache.take(size); ok {
    clear(slice)
    return slice, nil
    }
    }
    slice, err := unix.Mmap(
    -1,
    0,
    int(size),
    unix.PROT_READ|unix.PROT_WRITE,
    unix.MAP_PRIVATE|unix.MAP_ANONYMOUS,
    )
    if err != nil {
    return nil, moerr.NewOOMNoCtx()
    }
    // Anonymous mappings are zero-filled by the kernel. This also satisfies
    // Malloc's weaker contract, which does not promise non-zero contents.
    return slice, nil
  • 释放的 mapping 会先 MADV_FREE 并被放进 exact-size mmap cache;一秒空闲后,timer 调用 unmapSimpleCAllocatorCacheEntries:
    func (c *simpleCAllocatorMmapCache) put(slice []byte) bool {
    size := uint64(len(slice))
    if c.capacity == nil || size == 0 {
    return false
    }
    capacity := c.capacity()
    if size > capacity {
    return false
    }
    if !prepareSimpleCAllocatorMmapForCache(slice) {
    return false
    }
    c.mu.Lock()
    defer c.mu.Unlock()
    // Re-evaluate under the lock because a runtime limit may have changed while
    // the pages were being prepared.
    capacity = c.capacity()
    if size > capacity || c.bytes > capacity-size {
    return false
    }
    c.bySize[size] = append(c.bySize[size], slice)
    c.bytes += size
    c.lastPut = time.Now()
    c.updateGaugeLocked()
    if c.timer == nil {
    c.timerGeneration++
    generation := c.timerGeneration
    c.timer = time.AfterFunc(c.idle, func() {
    c.expire(generation)
    })
    } else {
    c.timer.Reset(c.idle)
    }
    return true
    }
    func (c *simpleCAllocatorMmapCache) expire(generation uint64) {
    c.mu.Lock()
    // drain may have stopped the timer after its callback became runnable and
    // a subsequent put may already have created another timer.
    if c.timer == nil || generation != c.timerGeneration {
    c.mu.Unlock()
    return
    }
    if remaining := c.idle - time.Since(c.lastPut); remaining > 0 {
    c.timer.Reset(remaining)
    c.mu.Unlock()
    return
    }
    entries := c.bySize
    c.bySize = make(map[uint64][][]byte)
    c.bytes = 0
    c.timer = nil
    c.timerGeneration++
    c.updateGaugeLocked()
    c.mu.Unlock()
    unmapSimpleCAllocatorCacheEntries(entries)
  • 任意 unix.Munmap 错误都会直接 panic:
    func unmapSimpleCAllocatorCacheEntries(entries map[uint64][][]byte) {
    for _, slices := range entries {
    for _, slice := range slices {
    if err := unix.Munmap(slice); err != nil {
    panic(moerr.NewInternalErrorNoCtxf(
    "failed to unmap cached %d-byte allocation: %v",
    len(slice),
    err,
    ))
    }
    }
    }

因此一次后台释放失败会杀死整个 CN,而非只拒绝本次内存回收。

根因分析

日志中的 ENOMEM 来自 munmap(344064),不等价于 cgroup OOM。事故节点的 vm.max_map_count 为 65530。Linux 在解除一个合并 VMA 的中间区间、因而需要拆分 VMA 且会超过该进程映射数量上限时,munmap 会返回 ENOMEM。参见 munmap(2)。

当前实现会对大量 >=128 KiB 请求创建独立匿名 mapping,并在 cache timer 中按原始分配范围批量 unmap。相邻匿名 mapping 被内核合并后,按单个分配范围释放可能变成“中间 unmap”,持续的分配/缓存/过期会造成 VMA 碎片和 map-count 增长。

旧进程已随崩溃退出,无法回读其当时的 /proc/<pid>/maps,故“撞到 map-count 上限”是基于 syscall 错误语义、节点阈值、调用路径和分配模型的高置信判断,尚缺该时刻的 map-count 直接采样。重启后新进程只有约 265 条 mappings。

影响

  • 一个正常的 cache 回收 timer 可以导致整个 CN 非优雅退出。
  • 问题可能在高频、大量 128 KiB 以上 off-heap 分配的负载下复发。
  • mpool-cache 的字节上限(最多 1 GiB)约束的是缓存字节数,不能保证 VMA 数量或 VMA 碎片有界。

期望与建议

  1. 修复 allocator 的 VMA 生命周期,使大块分配/回收不会因 VMA 合并后的局部 munmap 而触及 max_map_count;候选方向包括有界 arena/分段分配,或调整独立 mmap 的适用阈值和回收策略。
  2. 不应简单吞掉 Munmap 错误:若不再 panic,必须保留 mapping 的所有权/可观测性,避免遗失引用后留下永久虚拟地址空间泄漏。
  3. 增加隔离环境的回归:降低 vm.max_map_count,制造 >=128 KiB exact-size allocation/cache-expiry churn,验证不会 panic,并验证 mapping 数可控。
  4. 增加运行时观测:进程 map-count、cache entry/mapping 数、munmap errno;在接近节点阈值前告警。

相关提交

mmap cache 由 #26143(2c29244496)引入;本次运行镜像的 commit 9bf92dc56 已包含该实现。

Activity

  1. added
    kind/bug
    on Sep 11, 2026
  2. added 2 commits that reference this issue on Sep 11, 2026
    7d150ee
    06de981
  3. Ariznawlll commented on Sep 14, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:main
    • commit:61efcf43a145c53435933e14d98ff2ba61afabd5
    • 测试日期:2026-09-14
    • 环境:mo-srv-128,Linux 5.19.6-1.el8.elrepo.x86_64,vm.max_map_count=262144;测试前可用内存约 214 GiB。

    原问题验证

    原问题是在 mmap cache 到期释放映射时,unix.Munmap 因 VMA 数达到内核上限返回 ENOMEM,旧逻辑会 panic 并使 CN 重启。

    本次没有修改宿主机 sysctl,也没有启动或停止任何 MO 服务;在独立的 main 源码目录中执行真实 Linux 内核路径:

    go test -tags=mmap_reclaim_integration -count=3 -timeout=90s -v \
      -run '^TestMmapReclaimRealVMAExhaustion$' ./pkg/common/malloc

    该用例先让 allocator 的相邻 mmap 映射合并,再释放中间映射到 mmap cache;随后在同一测试进程内通过 mprotect 制造真实 VMA 耗尽。三轮均实际得到 ENOMEM:

    • maps=262145,高于宿主机 max_map_count=262144;
    • cache 到期回收时记录 pending_mappings=1、pending_bytes=344064;
    • 期间新 mmap 被正确阻塞并返回 ENOMEM,测试进程未 panic;
    • 解除 VMA 压力后,延迟回收队列归零,allocator 可以再次分配。

    三轮均通过,总耗时 9.411s。

    白盒验证

    执行:

    go test -race -count=1 -timeout=180s -v \
      -run '^(TestMmapReclaimConcurrentOwnership|TestMmapReclaimBlockedLogSink)$' \
      ./pkg/common/malloc

    结果:

    • TestMmapReclaimConcurrentOwnership 通过;
    • TestMmapReclaimBlockedLogSink 通过;
    • -race 通过,耗时 1.048s。

    压力恢复与资源检查

    • 压力用例退出后未发现残留的 mmap_reclaim 测试进程;
    • vm.max_map_count 未被修改;
    • 测试后可用内存约 210 GiB,swap 余量未变化;
    • 延迟回收映射和字节数均已归零。

    回归测试

    真实 VMA 耗尽用例使用 linux && mmap_reclaim_integration build tag,避免在普通 CI 中无约束地制造大量 VMA;常规逻辑和并发所有权由普通 UT 覆盖。

    测试证据

    • 独立执行日志:128 上的真实 VMA 耗尽用例 3/3 PASS,输出包含 maps=262145、pending_mappings=1、pending_bytes=344064 与 recovered: no pending mappings, allocator accepts fresh allocations。
    • 测试源码和触发条件见上面的两份固定 commit 链接;该集成测试仅在显式传入 mmap_reclaim_integration tag 时执行。

    测试结论

    测试通过。

  4. added 3 commits that reference this issue on Sep 17, 2026
    f02a147
    95eb843
    ff3bf94
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s-1

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions