Skip to content

[Bug]: mpool records on-heap allocations in globalPtrShards, making every missed Free() permanently unreclaimable (behaviour change since #23293) #27404

Closed

Description

@loveRhythm1990

Is there an existing issue for the same bug?

  • I have checked the existing issues.

Searched mpool on-heap, globalPtrShards, recordPtrHdr, mpool pointer not freed — no existing report. Closest is #23421 (lock contention on the same map, fixed by #23423) and #23423 itself, which fixed three off-heap leaks introduced by #23293. This report is about a fourth, on-heap consequence of the same change that has not been raised.

Branch Name

main

Commit ID

c30cd37058 (analysis baseline; main is at d7899e703d and still affected). Behaviour observed on an internal development cluster running a v4.2.0-e9d53c499-2026-08-19 build.

Other Environment Information

Linux / x86_64, cgroup v2, Go heap profiling via pyroscope.

Actual Behavior

MPool.alloc (pkg/common/mpool/mpool.go:888) serves two kinds of allocation:

if offHeap {
    // ... accounting ...
    bs, err = simpleCAllocator().Allocate(uint64(sz))   // off-heap
} else {
    bs = make([]byte, sz)                                // Go heap
}

ptr := unsafe.Pointer(&bs[0])
if err = mp.recordPtrHdr(ptr, hdr); err != nil {         // BOTH branches
    ...
}

recordPtrHdr (:385) delegates to gRecordPtr (:1566) for non-NoLock pools, which stores the pointer as a key in the package-level globalPtrShards[128].m map[unsafe.Pointer]memHdr.

unsafe.Pointer is a GC-traced pointer type. &bs[0] is the base address of the backing array of make([]byte, sz). Storing it as a live map key therefore keeps the whole backing array reachable, so the Go GC can never reclaim it. The entry is only removed by gRemovePtrMetadata (:1633), reached from MPool.Free → freePtr (:1073).

Consequence: for on-heap mpool allocations, failing to call Free() is no longer a benign omission that the GC cleans up — it is a permanent leak for the lifetime of the process.

This is a behaviour change, not longstanding behaviour. Before #23293 (merged 2025-12-31, ee34e4a118), the on-heap branch was not recorded at all:

// pre-#23293, mpool.go alloc()
if offHeap {
    bs, err = simpleCAllocator().Allocate(uint64(allocateSize))
    mp.recordPtr(unsafe.Pointer(&bs[0]))    // <-- only off-heap was recorded
    ...
} else {
    bs = make([]byte, allocateSize)          // <-- no record, no pinning
}

and freePtr read the header inline from a prefix, needing no map:

func (mp *MPool) freePtr(detailk string, ptr unsafe.Pointer) {
    hdr := unsafe.Add(ptr, -kMemHdrSz)

#23293 removed the per-allocation header (see #23423: "new design doesn't allocate headers"), which makes the global map load-bearing: Free() now has no other way to determine whether a pointer is on-heap or off-heap, so it must consult the map and panics if the pointer is absent (:1073, "invalid ptr, double free").

We are not claiming the map is wrong — in a header-less allocator it is hard to avoid. The problems we would like triaged are:

  1. The semantic change was never documented. Agg Framework Redo, Step 1. #23293 is a 48-file agg-framework refactor whose description is one line ("Further fix of agg issues"); the mpool change is a side effect. It was approved with zero comments. Every call site in the codebase that allocates on-heap via mpool and does not pair a Free() silently changed from harmless to leaking.
  2. No migration audit appears to have been done. fix(mpool): Fix cross-pool free memory leak and optimize with sharded locks #23423 fixed three leaks "introduced in Agg Framework Redo, Step 1. #23293" two days later, but all three were off-heap (cross-pool free, deallocateAllPtrs sizing, stats). The on-heap class was not considered.
  3. The leak is invisible to MO's own metrics. All accounting (globalStats, mp.stats, mp.resource, mp.details, profileRecordAlloc) lives inside the if offHeap branch of alloc(). On-heap allocations are counted nowhere, so mo_mem_mpool_allocated_size and mo_mem_offheap_inuse_bytes{type="mpool"} read ~0 while the Go heap holds gigabytes via MPool.alloc. Only a Go heap profile reveals it.

We hit exactly this on an internal cluster — see #27405, where saveMeta never frees its metadata batch. That call site has existed unchanged since 2023-01-06 (#7415) and was harmless for three years; it only started leaking after #23293.

Affected versions

git tag --contains ee34e4a118 (the #23293 merge) and a source check across branches:

ref on-heap pinning present saveMeta missing Clean leaks?
v3.0.18, 3.0-dev no yes no — GC still reclaims
v4.0.0-rc1 … rc4 yes yes yes
v4.1.0 … v4.1.4, 4.1-dev yes yes yes
main (d7899e703d) yes yes yes

So the 4.x line is affected from v4.0.0-rc1 onward; 3.0.x carries the same missing Clean but it is harmless there.

Expected Behavior

Either:

  • on-heap allocations are not retained by a GC-visible global structure, or
  • the requirement that on-heap mpool allocations must be explicitly freed is documented, all existing call sites are audited, and on-heap usage is included in mpool accounting so leaks are observable.

We are deliberately not proposing an implementation — restoring a tag/header, or tracking off-heap-ness at the batch/vector layer so Free() need not consult the map, are both design decisions with costs we are not in a position to weigh.

Steps to Reproduce

  1. From a session, allocate on-heap through an MPool and drop the reference without calling Free() — e.g. vector.AppendBytes(vec, buf, false, mp) on a vector that is never Cleaned.
  2. Force GC repeatedly (runtime.GC()), then take a heap profile.
  3. The allocation remains in inuse_space under mpool.(*MPool).alloc, and the corresponding entry stays in globalPtrShards.
  4. Observe that mo_mem_mpool_allocated_size remains 0 throughout.

Field observation, internal development cluster (Go heap profile, memory:inuse_space, single CN over its 23-hour lifetime, three sample points):

holder +50 min +11 h +23 h
mpool.(*MPool).alloc 6.90% 40.82% 54.59%
mpool.gRecordPtr 0.60% 2.55% 5.87%
disttae/cache.getTableDef 30.40% (~1.06 GiB) 14.01% (~1.12 GiB) 8.90% (~1.21 GiB)

Live heap grew 3.485 → 13.603 GiB. getTableDef is flat in absolute terms (a healthy bounded cache); its falling share is dilution. Essentially all growth is the two mpool entries. The process was eventually killed by the kernel OOM killer.

Additional information

Activity

  1. loveRhythm1990 commented on Aug 20, 2026

    @loveRhythm1990
    ContributorAuthor

    Raw heap-profile evidence for this report is attached to #27405 (the call site where we hit it):

    mo-27405-heap-evidence.zip (218 KB, sanitized — function symbols only, no SQL or user data)

    Contents: merged stacktraces at three points in the process lifetime (+50 min / +11 h / +23 h), SelectSeries samples used to size a single snapshot, the Prometheus series, and analyze.py to rebuild the call tree. README.md inside has the file list and reproduction commands.

    Relevant to this issue specifically:

    • derived-holders.txt — mpool.(*MPool).alloc goes 6.90% → 40.82% → 54.59% of live heap while every other holder stays flat in absolute terms (disttae/cache.getTableDef sits at ~1.06 → 1.21 GiB throughout).
    • metric-mo-mpool.csv / metric-mo-offheap.csv — mo_mem_mpool_allocated_size (all types, including global_stats_allocated) and mo_mem_offheap_inuse_bytes{type="mpool"} read ~0 across the whole 23 hours, i.e. point 3 in the description: the on-heap path is accounted nowhere, so this class of leak is invisible to metrics and only a Go heap profile surfaces it.

    Two cautions on reading the numbers, also in the README:

    • SelectMergeStacktraces returns the sum over all sampled snapshots in the window, so flamegraph.total is not the process heap size. self% is the reliable quantity; absolute GiB figures are heuristic estimates.
    • mpool.gRecordPtr's self size is the high-water mark of the map's backing store (Go maps do not shrink on delete), not a count of currently outstanding entries.
  2. added
    severity/s0
    and removed on Aug 20, 2026
  3. aunjgr commented on Aug 23, 2026

    @aunjgr
    Contributor

    The fix is now proposed in #27497, with the 4.2-dev backport in #27498.

    The design keeps globalPtrShards as strong, authoritative allocation provenance. We should not make on-heap MPool ownership weak or silently let GC replace the allocator lifecycle: every successful non-empty Alloc must reach Free, with NoLock pool teardown as the one explicit bulk-release boundary.

    To make violations diagnosable, the change adds bounded global live-byte/live-object accounting and metrics, per-pool outstanding ownership at reporting/deletion boundaries, optional on-heap allocation/free call-site details, and a structured warning when a normal pool is deleted with outstanding on-heap ownership. Normal-pool metadata remains registered after deletion so a legitimate late cross-pool Free still closes the ownership.

    The known production call-site leaks are fixed separately by #27454 and #27455. Their dedicated 4.2-dev backports are #27499 and #27500. The ownership audit also found and fixed several test-only missing cleanups in #27497/#27498.

  4. assigned and unassigned on Aug 24, 2026
  5. Ariznawlll commented on Aug 25, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:main
    • commit:22b91fe986b269d24a6b8816eafdd1fa6327c8e1
    • 部署方式:本地 Go 单元测试环境
    • 测试日期:2026-08-25

    原问题验证

    复验正常 MPool 的 on-heap 分配归属与全局统计:分配后 live bytes/live objects 增加,Free 后回到分配前的基线;连续运行 3 轮通过。

    Happy Path 覆盖

    1. 常规 MPool 的 on-heap 分配、ReportJson 统计和释放后归零。
    2. NoLock MPool 的增长与释放路径。
    3. cross-pool late Free 后归属统计正确回收。

    Unhappy Path 覆盖

    1. 超出限制的分配被拒绝,on-heap 统计不前移。
    2. 失败分配后继续执行正常分配/释放,未遗留统计或 ownership 状态。

    白盒验证

    pkg/common/mpool 中 TestOnHeapStatsLifecycleAndReport、TestOnHeapStatsNoLockAndGrow、TestOnHeapStatsFailedAllocationDoesNotAdvance、TestCrossPoolFreeOnHeap 以 -count=3 通过。

    回归测试

    该问题是 MPool ownership/accounting 内部路径,回归已在 MatrixOne 仓库的 pkg/common/mpool/mpool_test.go;不适合添加为 SQL MOTR。

    测试证据

    • 关联修复:MatrixOne #27497
    • 本地 focused UT:4 个用例 × 3 轮全部通过。

    测试结论

    测试通过。

  6. added 3 commits that reference this issue on Sep 17, 2026
    a3d3d2c
    be46955
    1db619b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions