Skip to content

[Bug]: CN streaming spill leaks its merge buffer when the file sinker panics #32156

Done

Description

@iamlinjunhong

Is there an existing issue for the same bug?

  • I have checked the existing issues.

Branch Name

main (the 4.2-dev counterpart is tracked by #32154)

Commit ID

0a7847abed712ed893d841a3c5fa415327eec761

Other Environment Information

Go unit test only, darwin/arm64. Go code from the commit above, linked against CGO artifacts built from d39d8a4034.
No cluster is needed to reproduce this.

Actual Behavior

When a panic is raised under FileSinker.Sink during a streaming merge spill, the output merge buffer is never returned, and its mpool allocations survive Sinker.Close. The memory is off-heap, so Go GC cannot reclaim it. On a locking mpool it stays charged after teardown, until the process restarts.

#31634 fixed the returned-error path by keeping the buffer with return data, err, but a panic never reaches that return. It also skips sinker.putBackBuffer(buffer) in trySpillMergeSortStreaming, which is not deferred:

buffer, err = mergeutil.MergeSortBatches(
	sinker.staged.inMemory,
	sinker.schema.sortKeyIdx,
	buffer,
	streamSinker, // a panic under fSinker.Sink unwinds through here
	sinker.mp,
	sinker.putBackOneInMemory,
)
sinker.putBackBuffer(buffer) // skipped on panic
return err

The panic is reachable because WriteArena.CompressBuf still turns an allocation failure into panic(err), and Pipeline.Run recovers it into an ordinary query error. The query fails normally, the leak stays hidden, and an application retry leaks again.

Reproducer result on this commit (one 8192-row batch, small schema, Sinker.Close called after failure):

Sink failure mode Leaked bytes
returns error 0
panics 98304

Production evidence comes from the deployed 4.2 build 71498157cc and is described in #32154: repeated failed UPDATE retries each left about 1.06 GiB behind, and the CN was later OOM-killed. That leak does not account for the whole off-heap baseline in that incident.

Limits of what was verified on main:

Expected Behavior

A spill failure, whether a returned error or a recovered panic, must return every buffer the sinker owns. After Sinker.Close, the mpool accounting should be back at its starting value, without double-returning any buffer to the freelist (see #31283).

Steps to Reproduce

Add this to package pkg/objectio/ioutil and run with -tags matrixone_test -v.
RESULT reports leaked_bytes=0 for mode=error and a non-zero value for mode=panic.
type zzSinker struct {
	mode     string
	received *batch.Batch
}

func (s *zzSinker) Sink(_ context.Context, b *batch.Batch) error {
	s.received = b
	switch s.mode {
	case "error":
		return errors.New("injected")
	case "panic":
		panic(errors.New("mpool memory allocation exceed limit")) // same shape as WriteArena.CompressBuf
	}
	return nil
}
func (*zzSinker) Sync(context.Context) (*objectio.ObjectStats, error) {
	return &objectio.ObjectStats{}, nil
}
func (*zzSinker) Reset()       {}
func (*zzSinker) Close() error { return nil }

func TestZZSpillFailureMode(t *testing.T) {
	for _, mode := range []string{"error", "panic"} {
		t.Run(mode, func(t *testing.T) {
			proc := testutil.NewProc(t)
			fs, err := fileservice.NewMemoryFS("shared", fileservice.DisabledCacheConfig, nil)
			require.NoError(t, err)
			attrs, typs, _ := mockSchema(3, 2)
			file := &zzSinker{mode: mode}
			sinker := NewSinker(2, attrs, typs,
				func(*mpool.MPool, fileservice.FileService) FileSinker { return file },
				proc.Mp(), fs, WithMemorySizeThreshold(1), WithOffHeap())
			data := containers.MockBatch(typs, int(objectio.BlockMaxRows), 2, nil)
			defer data.Close()
			before := proc.Mp().CurrNB()
			func() {
				defer func() { _ = recover() }() // stands in for Pipeline.Run's catchPanic
				_ = sinker.Write(context.Background(), containers.ToCNBatch(data))
			}()
			require.NoError(t, sinker.Close())
			leaked := proc.Mp().CurrNB() - before
			fmt.Printf("RESULT mode=%s leaked_bytes=%d\n", mode, leaked)
			if leaked != 0 {
				file.received.Clean(proc.Mp())
			}
		})
	}
}

Additional information

Suggested direction, not yet implemented or tested:

  1. Make buffer ownership panic-safe in trySpillMergeSortStreaming, for example by returning the buffer from a defer, or stop panicking on allocation failure in the compression path and return an error instead.
  2. Check the same failure for the other spill paths (trySpillMergeSortPipeline, trySpillMergeSortAccumulate), main's disjoint-range merge path, and cleanup skipped by the unwind, such as resetFileSinker and the file sinker's arena. These have not been audited.
  3. Add regression coverage for the panic mode next to the test from fix(objectio): recycle merge buffer when streaming spill fails #31634, with on-heap and off-heap buffers and partial and full blocks.

Any fix here should also be considered for 4.2-dev through #32154, which additionally lacks #31634.

Activity

  1. self-assigned this
    on Nov 4, 2026
  2. XuPeng-SH commented on Nov 29, 2026

    @XuPeng-SH
    Contributor

    #32160 已合入 main(231b68c2d642,与最终 PR head 的源码树一致),转测。请在合入版覆盖 streaming、accumulate、pipeline 的 sink 错误与 panic、替换 buffer 和 producer/worker 交接,检查关闭后 off-heap 归零、无双重释放且原始错误保留。作者报告定向普通/race(含 100 次重复)和较早 x86 UT 通过;最终 Required 未过,多项任务取消。未在本轮重跑最终构建,不宣称生产 OOM 已复现或解决;4.2-dev 的 #32154 是独立工单。

  3. Ariznawlll commented on Nov 30, 2026

    @Ariznawlll
    Collaborator

    QA 验收通过(最新 main)

    版本与方法

    • 被测及开测时官方 main:c255da6778fac39bc53b5b9defaab3b6f945e4d6;关闭前再次解析仍为该 SHA。
    • macOS arm64,真实 pkg/objectio/ioutil 白盒测试,启用 -race,串行执行。
    • 较早 main 的历史结果未计入本轮。

    结果:9 个 root tests × 3 轮,27/27 PASS

    覆盖 streaming、accumulate、pipeline 的 returned-error 与 panic,包含:

    • 100/8192 行、on-heap/off-heap、disjoint/non-disjoint 及 full-block range;
    • replacement buffer、producer/worker 交接和真实 sink/writer 关闭;
    • Close 后 on-heap bytes/objects 与 off-heap CurrNB() 回到基线;
    • freelist 不重复返回 batch,原始 error/panic 值保留,writer/arena 不重复关闭。

    无 FAIL、SKIP、DATA RACE。日志 SHA256:59a166a210e8407e195d057519d4d0a986bb926eb420c4790f4f09e75a0251cb。

    MOTR 回归与结论边界

    • 上述 9 个 root tests 已包含在 matrixorigin/motr PR 374 的 native gate,当前 head d7715c5907ac73f967096343b1e394ec8486504f,无需新增重复用例。
    • 评论时 hashbuild-boundary 为 FAILED;linux、HA、两个 branch-acceptance、latest-main-dual-cn、main-native-sql、main-native-engine 等仍为 pending(queued/in_progress)。这些状态未被当作通过证据。
    • 本结论证明注入故障路径的缓冲区所有权和释放正确;没有复现或宣称解决生产环境的整体 OOM。4.2-dev 对应项 [Bug]: CN streaming spill leaks its merge buffer when the file sinker panics on 4.2-dev #32154 是独立工单,不在本次关闭范围内。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugneeds-triage

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions