Skip to content

fix(mpool): Fix cross-pool free memory leak and optimize with sharded locks - #23423

Merged
fengttt merged 2 commits into
matrixorigin:mainfrom
XuPeng-SH:fix-mpool-bugs
Jan 2, 2026
Merged

fengttt merged 2 commits into
matrixorigin:mainfrom
XuPeng-SH:fix-mpool-bugs

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Jan 1, 2026 •

Copy link
Copy Markdown
Contributor

User description

What type of PR is this?

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

Which issue(s) this PR fixes:

issue #23421

What this PR does / why we need it:

Fixes memory leak introduced in #23293

Bugs Fixed:

  1. Cross-pool free memory leak: offHeap memory was not being deallocated when freed from a different pool
  2. Incorrect deallocateAllPtrs size calculation: was using allocSz + kMemHdrSz but new design doesn't allocate headers
  3. Stats inconsistency: cross-pool free didn't properly update original pool stats

Performance Optimizations:

  • Sharded locks: Replace single global lock (globalPtrsMu) with 128 sharded locks (globalPtrShards) to reduce lock contention
  • Better hash distribution: Use FNV-like hash mixing for even shard distribution

Key Changes:

  • Restore delegation to original pool for cross-pool free to ensure correct stats tracking
  • Handle edge case where original pool is deleted before cross-pool free
  • Fix deallocateAllPtrs to only deallocate offHeap memory with correct size
  • Replace globalPtrs + globalPtrsMu with globalPtrShards[128] for better concurrency

PR Type

Bug fix, Enhancement


Description

  • Fix cross-pool free memory leak by delegating to original pool

  • Replace global lock with 128 sharded locks for better concurrency

  • Fix deallocateAllPtrs to only deallocate offHeap memory correctly

  • Add comprehensive tests for cross-pool free and concurrent operations


Diagram Walkthrough

flowchart LR
  A["Cross-pool Free Request"] --> B{"Original Pool Exists?"}
  B -->|Yes| C["Delegate to Original Pool"]
  B -->|No| D["Free Memory Directly"]
  C --> E["Update Stats Correctly"]
  D --> E
  F["Global Ptr Map"] --> G["128 Sharded Locks"]
  G --> H["Reduced Lock Contention"]
Loading

File Walkthrough

Relevant files
Bug fix, enhancement
mpool.go
Implement sharded locks and fix cross-pool free delegation

pkg/common/mpool/mpool.go

  • Fixed deallocateAllPtrs to only deallocate offHeap memory with correct
    size (removed kMemHdrSz)
  • Replaced single global lock (globalPtrsMu) with 128 sharded locks
    (globalPtrShards) using FNV-like hash mixing
  • Refactored freePtr to delegate cross-pool free to original pool via
    new freePtrInternal method
  • Added edge case handling when original pool is deleted before
    cross-pool free
  • Initialize sharded pointer maps in init() function
+57/-16 
Tests
mpool_test.go
Add comprehensive tests for memory management fixes           

pkg/common/mpool/mpool_test.go

  • Added TestCrossPoolFreeOffHeap to verify offHeap memory deallocation
    on cross-pool free
  • Added TestCrossPoolFreeOnHeap to verify on-heap cross-pool free
    behavior
  • Added TestDoubleFree to verify double free detection and panic
  • Added TestConcurrentAllocFree to test concurrent allocation/free with
    sharded locks
  • Added TestConcurrentCrossPoolFree to test concurrent cross-pool
    operations
  • Added TestAllocZeroSize, TestFreeNil, and TestShardDistribution for
    edge cases
+177/-0 

@qodo-code-review

qodo-code-review Bot commented Jan 1, 2026 •

Copy link
Copy Markdown

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
⚪
Double free risk

Description: Cross-pool free delegates to (otherPool.(*MPool)).freePtrInternal(detailk, ptr, hdr) after
removing the pointer record from the freeing pool, but it does not show removal of the
pointer record from the original pool’s tracking map before deallocation; if the original
pool still retains the entry, later cleanup (e.g., pool deletion via deallocateAllPtrs)
could attempt to deallocate the same off-heap pointer again, creating a potential
double-free/use-after-free against the underlying C allocator.
mpool.go [569-601]

Referred Code
func (mp *MPool) freePtr(detailk string, ptr unsafe.Pointer) {
	hdr, ok := mp.removePtrHdr(ptr)
	if !ok {
		// this is a double free.
		panic(moerr.NewInternalErrorNoCtx("invalid ptr, double free"))
	}

	if hdr.poolId != mp.id {
		// Cross-pool free: delegate to the original pool
		mp.stats.RecordXPoolFree(detailk, int64(hdr.allocSz))
		globalStats.RecordXPoolFree(detailk, int64(hdr.allocSz))
		otherPool, ok := globalPools.Load(hdr.poolId)
		if !ok {
			logutil.Errorf("invalid mpool id %d", hdr.poolId)
			// Pool already deleted, we still need to free the memory
			if hdr.offHeap {
				sz := int64(hdr.allocSz)
				globalStats.NumCurrBytes.Add(-sz)
				simpleCAllocator().Deallocate(unsafe.Slice((*byte)(ptr), sz), uint64(sz))
			}
		} else {


 ... (clipped 12 lines)
Ticket Compliance
⚪
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
⚪
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

🔴
Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Unsafe slice length: New code converts hdr.allocSz to int (and once passes an int64 directly) when building
unsafe.Slice, which can overflow or not compile and lacks bounds checking for large
allocations.

Referred Code
		if hdr.offHeap {
			sz := int(hdr.allocSz)
			simpleCAllocator().Deallocate(unsafe.Slice((*byte)(ptr), sz), uint64(sz))
		}
	}
	mp.ptrs = nil
}

func (mp *MPool) EnableDetailRecording() {
	if mp.details == nil {
		mp.details = newMpoolDetails()
	}
}

func (mp *MPool) DisableDetailRecording() {
	mp.details = nil
}

func (mp *MPool) getDetailK() string {
	if mp == nil || mp.details == nil {
		return ""


 ... (clipped 279 lines)

Learn more about managing compliance generic rules or creating your own custom rules

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review

qodo-code-review Bot commented Jan 1, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix incorrect pointer in deallocation

In deallocateAllPtrs, fix the deallocation logic by calculating the original
pointer (subtracting kMemHdrSz) and using the total allocated size to prevent
memory corruption.

pkg/common/mpool/mpool.go [289-292]

 		if hdr.offHeap {
 			sz := int(hdr.allocSz)
-			simpleCAllocator().Deallocate(unsafe.Slice((*byte)(ptr), sz), uint64(sz))
+			origPtr := unsafe.Pointer(uintptr(ptr) - kMemHdrSz)
+			totalSize := sz + kMemHdrSz
+			simpleCAllocator().Deallocate(unsafe.Slice((*byte)(origPtr), totalSize), uint64(totalSize))
 		}
  • Apply / Chat
Suggestion importance[1-10]: 10

__

Why: The suggestion correctly identifies a critical memory corruption bug in deallocateAllPtrs where an incorrect pointer and size are used for deallocation, which would lead to crashes or undefined behavior.

High
Protect pool pointer map with mutex

Add a sync.Mutex to the MPool struct and use it to protect concurrent access to
the ptrs map, preventing data races.

pkg/common/mpool/mpool.go [249-258]

 type MPool struct {
-    id      int64      // mpool generated, used to look up the MPool
-    tag     string     // user supplied, for debug/inspect
-    cap     int64      // pool capacity
-    stats   MPoolStats // stats
+    id      int64
+    tag     string
+    cap     int64
+    stats   MPoolStats
     details *mpoolDetails
 
     noLock bool
-    ptrs   map[unsafe.Pointer]memHdr
+    mu      sync.Mutex
+    ptrs    map[unsafe.Pointer]memHdr
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical data race on the per-pool ptrs map, which is not thread-safe. The TestConcurrentAllocFree test added in the PR is likely to fail without this fix.

High
Remove pointers from shard map on destroy

In deallocateAllPtrs, call gRemovePtr(ptr) inside the loop to remove pointers
from the global shard map and prevent a memory leak.

pkg/common/mpool/mpool.go [287-295]

 func (mp *MPool) deallocateAllPtrs() {
     for ptr, hdr := range mp.ptrs {
         if hdr.offHeap {
             sz := int(hdr.allocSz)
             simpleCAllocator().Deallocate(unsafe.Slice((*byte)(ptr), sz), uint64(sz))
         }
+        // also clear from global shards
+        gRemovePtr(ptr)
     }
     mp.ptrs = nil
 }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a memory leak where pointers are not removed from the global shard map when a pool is destroyed, which is a significant bug.

Medium
Only record and delegate frees for off-heap memory

In freePtr, only record cross-pool free statistics and delegate the free
operation for off-heap memory by adding an if hdr.offHeap check.

pkg/common/mpool/mpool.go [569-596]

 func (mp *MPool) freePtr(detailk string, ptr unsafe.Pointer) {
     hdr, ok := mp.removePtrHdr(ptr)
     if !ok {
-        // this is a double free.
         panic(moerr.NewInternalErrorNoCtx("invalid ptr, double free"))
     }
 
-    if hdr.poolId != mp.id {
-        // Cross-pool free: delegate to the original pool
+    if hdr.poolId != mp.id && hdr.offHeap {
+        // Cross-pool off-heap free
         mp.stats.RecordXPoolFree(detailk, int64(hdr.allocSz))
         globalStats.RecordXPoolFree(detailk, int64(hdr.allocSz))
         otherPool, ok := globalPools.Load(hdr.poolId)
         if !ok {
             logutil.Errorf("invalid mpool id %d", hdr.poolId)
-            // Pool already deleted, we still need to free the memory
-            if hdr.offHeap {
-                sz := int64(hdr.allocSz)
-                globalStats.NumCurrBytes.Add(-sz)
-                simpleCAllocator().Deallocate(unsafe.Slice((*byte)(ptr), sz), uint64(sz))
-            }
+            sz := int64(hdr.allocSz)
+            globalStats.NumCurrBytes.Add(-sz)
+            simpleCAllocator().Deallocate(unsafe.Slice((*byte)(ptr), sz), uint64(sz))
         } else {
             (otherPool.(*MPool)).freePtrInternal(detailk, ptr, hdr)
         }
         return
     }
 
     mp.freePtrInternal(detailk, ptr, hdr)
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 5

__

Why: The suggestion correctly points out that cross-pool free statistics are being recorded for on-heap memory, which is inconsistent since on-heap memory is not tracked by the pool. This improves correctness of statistics.

Low
  • Update

@fengttt
fengttt merged commit 92453fa into matrixorigin:main Jan 2, 2026
fengttt pushed a commit to fengttt/matrixone that referenced this pull request May 7, 2026
… locks (matrixorigin#23423)

### **User description**
## 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:

issue matrixorigin#23421

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

Fixes memory leak introduced in matrixorigin#23293

### Bugs Fixed:
1. **Cross-pool free memory leak**: offHeap memory was not being
deallocated when freed from a different pool
2. **Incorrect deallocateAllPtrs size calculation**: was using `allocSz
+ kMemHdrSz` but new design doesn't allocate headers
3. **Stats inconsistency**: cross-pool free didn't properly update
original pool stats

### Performance Optimizations:
- **Sharded locks**: Replace single global lock (`globalPtrsMu`) with
128 sharded locks (`globalPtrShards`) to reduce lock contention
- **Better hash distribution**: Use FNV-like hash mixing for even shard
distribution

### Key Changes:
- Restore delegation to original pool for cross-pool free to ensure
correct stats tracking
- Handle edge case where original pool is deleted before cross-pool free
- Fix `deallocateAllPtrs` to only deallocate offHeap memory with correct
size
- Replace `globalPtrs + globalPtrsMu` with `globalPtrShards[128]` for
better concurrency


___

### **PR Type**
Bug fix, Enhancement


___

### **Description**
- Fix cross-pool free memory leak by delegating to original pool

- Replace global lock with 128 sharded locks for better concurrency

- Fix deallocateAllPtrs to only deallocate offHeap memory correctly

- Add comprehensive tests for cross-pool free and concurrent operations


___

### Diagram Walkthrough


```mermaid
flowchart LR
  A["Cross-pool Free Request"] --> B{"Original Pool Exists?"}
  B -->|Yes| C["Delegate to Original Pool"]
  B -->|No| D["Free Memory Directly"]
  C --> E["Update Stats Correctly"]
  D --> E
  F["Global Ptr Map"] --> G["128 Sharded Locks"]
  G --> H["Reduced Lock Contention"]
```



<details><summary><h3>File Walkthrough</h3></summary>

<table><thead><tr><th></th><th align="left">Relevant
files</th></tr></thead><tbody><tr><td><strong>Bug fix,
enhancement</strong></td><td><table>
<tr>
  <td>
    <details>
<summary><strong>mpool.go</strong><dd><code>Implement sharded locks and
fix cross-pool free delegation</code></dd></summary>
<hr>

pkg/common/mpool/mpool.go

<ul><li>Fixed <code>deallocateAllPtrs</code> to only deallocate offHeap
memory with correct <br>size (removed kMemHdrSz)<br> <li> Replaced
single global lock (<code>globalPtrsMu</code>) with 128 sharded locks
<br>(<code>globalPtrShards</code>) using FNV-like hash mixing<br> <li>
Refactored <code>freePtr</code> to delegate cross-pool free to original
pool via <br>new <code>freePtrInternal</code> method<br> <li> Added edge
case handling when original pool is deleted before <br>cross-pool
free<br> <li> Initialize sharded pointer maps in <code>init()</code>
function</ul>


</details>


  </td>
<td><a
href="https://github.com/matrixorigin/matrixone/pull/23423/files#diff-464ac4ea6ea162c1e0867b367c850faf4525f2518a4099319f0e944457cae7c1">+57/-16</a>&nbsp;
</td>

</tr>
</table></td></tr><tr><td><strong>Tests</strong></td><td><table>
<tr>
  <td>
    <details>
<summary><strong>mpool_test.go</strong><dd><code>Add comprehensive tests
for memory management fixes</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; </dd></summary>
<hr>

pkg/common/mpool/mpool_test.go

<ul><li>Added <code>TestCrossPoolFreeOffHeap</code> to verify offHeap
memory deallocation <br>on cross-pool free<br> <li> Added
<code>TestCrossPoolFreeOnHeap</code> to verify on-heap cross-pool free
<br>behavior<br> <li> Added <code>TestDoubleFree</code> to verify double
free detection and panic<br> <li> Added
<code>TestConcurrentAllocFree</code> to test concurrent allocation/free
with <br>sharded locks<br> <li> Added
<code>TestConcurrentCrossPoolFree</code> to test concurrent cross-pool
<br>operations<br> <li> Added <code>TestAllocZeroSize</code>,
<code>TestFreeNil</code>, and <code>TestShardDistribution</code> for
<br>edge cases</ul>


</details>


  </td>
<td><a
href="https://github.com/matrixorigin/matrixone/pull/23423/files#diff-01e2ed668061952031bd9d6a3ca32adcff3aad73e7abf9e7519d7e6992dad197">+177/-0</a>&nbsp;
</td>

</tr>
</table></td></tr></tbody></table>

</details>

___
@XuPeng-SH
XuPeng-SH deleted the fix-mpool-bugs branch July 4, 2026 14:05

This branch was previously deployed

1 inactive deployment
ci — d2b1d388 Deployed Jan 2, 2026 by fengttt
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 Review effort 3/5 size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants