Repository navigation
Description
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:
- 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. - 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,
deallocateAllPtrssizing, stats). The on-heap class was not considered. - The leak is invisible to MO's own metrics. All accounting (
globalStats,mp.stats,mp.resource,mp.details,profileRecordAlloc) lives inside theif offHeapbranch ofalloc(). On-heap allocations are counted nowhere, somo_mem_mpool_allocated_sizeandmo_mem_offheap_inuse_bytes{type="mpool"}read ~0 while the Go heap holds gigabytes viaMPool.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
- From a session, allocate on-heap through an
MPooland drop the reference without callingFree()— e.g.vector.AppendBytes(vec, buf, false, mp)on a vector that is neverCleaned. - Force GC repeatedly (
runtime.GC()), then take a heap profile. - The allocation remains in
inuse_spaceundermpool.(*MPool).alloc, and the corresponding entry stays inglobalPtrShards. - Observe that
mo_mem_mpool_allocated_sizeremains 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
gRecordPtr's own self size reflects map backing-store high-water mark (Go maps do not shrink ondelete), so it indicates that entries accumulated at some point — it is not a direct count of currently-outstanding entries. The conclusive evidence is the missingCleanat the call site ([Bug]: saveMeta never frees the query-result metadata batch, leaking session mpool memory on every saved query #27405), not this number.- Absolute GiB figures above are heuristic (
self% × median snapshot heap size); theself%trend is the reliable signal. - The
NoLockpool variant stores pointers in a pool-local map (:385) instead of the global shards, so aNoLockpool that is discarded entirely can still be collected. This report concerns normal/globally-registered pools. - Related: Agg Framework Redo, Step 1. #23293 (introduced), [Performance]: mpool global lock causes severe contention under high concurrency #23421 / fix(mpool): Fix cross-pool free memory leak and optimize with sharded locks #23423 (contention + off-heap leaks from the same change).
- Not reproduced in a controlled test; the cluster was accessed read-only, so no SQL could be executed to build a counter-experiment.
Activity
loveRhythm1990 commentedon Aug 20, 2026
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),
SelectSeriessamples used to size a single snapshot, the Prometheus series, andanalyze.pyto rebuild the call tree.README.mdinside has the file list and reproduction commands.Relevant to this issue specifically:
derived-holders.txt—mpool.(*MPool).allocgoes 6.90% → 40.82% → 54.59% of live heap while every other holder stays flat in absolute terms (disttae/cache.getTableDefsits at ~1.06 → 1.21 GiB throughout).metric-mo-mpool.csv/metric-mo-offheap.csv—mo_mem_mpool_allocated_size(all types, includingglobal_stats_allocated) andmo_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:
SelectMergeStacktracesreturns the sum over all sampled snapshots in the window, soflamegraph.totalis 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 ondelete), not a count of currently outstanding entries.aunjgr commentedon Aug 23, 2026
The fix is now proposed in #27497, with the 4.2-dev backport in #27498.
The design keeps
globalPtrShardsas strong, authoritative allocation provenance. We should not make on-heap MPool ownership weak or silently let GC replace the allocator lifecycle: every successful non-emptyAllocmust reachFree, withNoLockpool 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
Freestill 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.2] fix(mpool): make on-heap ownership observable (#27498)
fix(mpool): make on-heap ownership observable (#27497)
Ariznawlll commentedon Aug 25, 2026
测试版本
main22b91fe986b269d24a6b8816eafdd1fa6327c8e1原问题验证
复验正常 MPool 的 on-heap 分配归属与全局统计:分配后 live bytes/live objects 增加,
Free后回到分配前的基线;连续运行 3 轮通过。Happy Path 覆盖
ReportJson统计和释放后归零。Free后归属统计正确回收。Unhappy Path 覆盖
白盒验证
pkg/common/mpool中TestOnHeapStatsLifecycleAndReport、TestOnHeapStatsNoLockAndGrow、TestOnHeapStatsFailedAllocationDoesNotAdvance、TestCrossPoolFreeOnHeap以-count=3通过。回归测试
该问题是 MPool ownership/accounting 内部路径,回归已在 MatrixOne 仓库的
pkg/common/mpool/mpool_test.go;不适合添加为 SQL MOTR。测试证据
测试结论
测试通过。
fix(mpool): make on-heap ownership observable (matrixorigin#27497)
fix(mpool): make on-heap ownership observable (matrixorigin#27497)
fix(mpool): make on-heap ownership observable (matrixorigin#27497)