Skip to content

aggState: mpool.MakeSlice leak when subsequent Alloc fails #24058

Closed

Description

@XuPeng-SH

Summary

In pkg/sql/colexec/aggexec/aggState.go:122-132, when mpool.MakeSlice() succeeds for ag.argCnt but the subsequent mp.Alloc() fails, the allocated slice is never freed.

Root Cause

// aggState.go:122-132
if ag.argCnt, err = mpool.MakeSlice[uint32](int(c), mp, true); err != nil {
    return err  // OK — nothing allocated yet
}

bufsz := kAggArgArenaSize
if c < 1024 {
    bufsz = 16 * 1024
}

if ag.argbuf, err = mp.Alloc(bufsz, true); err != nil {
    return err  // BUG: ag.argCnt leaked
}

The free() method (line 578) only cleans up when ag.argSkl != nil:

func (ag *aggState) free(mp *mpool.MPool) {
    if ag.argSkl != nil {  // Only enters if argSkl was initialized
        mpool.FreeSlice(mp, ag.argCnt)
        // ...
    }
}

Since ag.argSkl is set AFTER the failed allocation (line 135), free() never releases argCnt.

Impact

  • Off-heap mpool memory leak on every aggregation allocation failure
  • Proportional to c (number of aggregation groups) × sizeof(uint32)
  • More likely under memory pressure when mp.Alloc() fails
  • Affects aggregation operators (GROUP BY, window functions)

Suggested Fix

Add cleanup before the error return:

if ag.argbuf, err = mp.Alloc(bufsz, true); err != nil {
    mpool.FreeSlice(mp, ag.argCnt)
    ag.argCnt = nil
    return err
}

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s0

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions