Skip to content

[Bug]: CN streaming spill leaks its merge buffer when the file sinker panics on 4.2-dev #32154

Closed

Description

@iamlinjunhong

Is there an existing issue for the same bug?

  • I have checked the existing issues.

Branch Name

4.2-dev (also observed on the deployed build below; the panic path is also present on main)

Commit ID

Other Environment Information

A CN executing a large whole-table UPDATE with wide variable-length rows, retried by the application after each failure.
CN cgroup limit 55 GiB. The unit reproducer below needs no cluster.

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 and mpool teardown. The memory is off-heap, so Go GC cannot reclaim it. It stays charged until the process restarts.

WriteArena.CompressBuf turns an allocation failure into a panic, so an mpool rejection reaches this path as a panic rather than an error:

Pipeline.Run (catchPanic recovers here)
 -> MultiUpdate.update_s3 -> s3WriterDelegate.append -> CNS3Writer.Write
 -> Sinker.Write -> pushStaged -> trySpill -> trySpillMergeSortStreaming
 -> MergeSortBatches -> streamSinker -> FSinkerImpl.Sink -> BlockWriter.WriteBatch
 -> objectWriterV1.Write -> AddBlock -> addBlock -> WriteWithCompress
 -> WriteArena.CompressBuf -> panic(err)

The unwind skips both the return ..., err in streamSinker and sinker.putBackBuffer(buffer) in trySpillMergeSortStreaming, which is not deferred.

#31634 does not cover this. It changes the returned-error path to return data, err, which is not reached on a panic. That PR is also on main only, so 4.2-dev still has return nil, err and leaks on the returned-error path as well.

Reproducer results (one 8192-row batch, small schema, Sinker.Close called after failure):

Branch Sink returns error Sink panics
4.2-dev 88e5fb5417 (no #31634) leaks 98304 bytes leaks 98304 bytes
main d39d8a4034 (has #31634) 0 leaks 98304 bytes

Evidence from the deployed build, where CompressBuf requested 2147483648 bytes (#32051) and the application retried about every 6 minutes:

  • Eight mpool teardowns on one CN each logged mp error with exactly current bytes: 1137115136 (about 1.06 GiB) and 13 unfreed allocations.
  • One teardown came 38 ms before the application received the requested size 2147483648 failure, whose stack is the one above.
  • The global off-heap mpool gauge kept rising between retries and reached 20.7 GiB, then the CN was OOM-killed. It returned to about 0 after restart and began climbing again with the retries.

Limits of this evidence:

  • That the 1.06 GiB residual is exactly one output batch is inferred from its size and repeatability, not from an allocation trace.
  • This leak does not account for the whole baseline: eight logged leaks total about 8.5 GiB, against 19.6 GiB in the gauge at 14:40 local time. The rest is unattributed, and the Go heap was also about 25 GiB near the first OOM.
  • The reproducer injects a panic in a test FileSinker. It does not perform a real oversized allocation.

Relation to other issues: #32081 stops the 2 GiB rounding on 4.2-dev, so the observed request size should no longer panic, but it does not make this path panic-safe. Any later panic under Sink still leaks, including a compression bound above mpool.MaxAllocationSize(). #32146 tracks the unbounded size of CN spill blocks, which keeps such large blocks reachable. It does not cover this ownership defect.

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 non-zero leaked_bytes for mode=panic on both branches.
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. Backport fix(objectio): recycle merge buffer when streaming spill fails #31634, or an equivalent fix, to 4.2-dev so the returned-error path is covered too.
  3. Check the same failure for the other spill paths (trySpillMergeSortPipeline, trySpillMergeSortAccumulate) and for cleanup skipped by the unwind, such as resetFileSinker and the file sinker's arena. These have not been audited.
  4. Add regression coverage for both failure modes, with on-heap and off-heap buffers and partial and full blocks.

Separately, the unattributed part of the off-heap baseline and the Go heap usage in this incident still need their own investigation.

Activity

  1. self-assigned this
    on Nov 4, 2026
  2. added
    ai-easy
    on Nov 10, 2026
  3. Ariznawlll commented on Nov 17, 2026

    @Ariznawlll
    Collaborator

    QA 复测结论:最新 4.2-dev 已通过;最新 main 的 panic 场景仍失败(保持 OPEN)

    最终结论

    • 4.2-dev 原始问题场景已通过:origin/4.2-dev@e8fd84b331f168eafd0ec28149b043eaebc7e39d(2026-11-17)。在 streaming spill 的 FileSinker.Sink 注入 panic,模拟上层 recover 后调用一次 Sinker.Close(),on/off-heap、100/8192 行的资源残留均为 0 字节、0 对象。
    • main 仍未通过:在补测期间官方 main 已更新到 origin/main@e1160015bb5895c1677d5fc1496c4bee440592b3,我用同一探针在该新 main 上复测;success 和 returned-error 共 8 个子场景通过,但 4 个 panic 子场景全部失败,仍各残留 98,304 字节。
    • 因此不能把 4.2-dev 的通过扩大为整个 issue 通过;本 issue 继续保持 OPEN,剩余修复目标是 main 的 panic-safe 资源清理。

    具体测试场景与步骤

    失败路径不是普通 SQL,也不是 FileSinker.Sink 返回 error 的路径,而是 CN streaming merge spill 已将排序输出 batch 交给文件写入端时,FileSinker.Sink 发生 panic 的所有权清理路径。

    临时 TestQA32154SpillResourceInvariant 使用 -tags matrixone_test,按以下方式执行:

    1. 使用 NewSinker 和 WithMemorySizeThreshold(1),让 Sinker.Write 进入 spill;分别覆盖 on/off-heap、100/8192 行和 success/error/panic。
    2. 实际进入 Sinker.Write -> pushStaged -> trySpill -> trySpillMergeSortStreaming -> MergeSortBatches -> streamSinker -> FileSinker.Sink。
    3. Sink 收到输出 merge batch 后主动 panic,模拟 WriteArena.CompressBuf 分配失败转为 panic 的失败形态。
    4. 测试边界 recover,代表上层 Pipeline.Run 的 catchPanic,随后只调用一次 Sinker.Close()。
    5. 比较 Write 前与 Close 后的 on-heap bytes/objects 和 off-heap bytes;以全部回到基线为通过条件,而不是只打印日志。

    同一探针的实际分支对比

    offHeap 行数 success returned error panic:最新 4.2-dev panic:最新 main
    false 100 0 残留 0 残留 0 字节 / 0 对象 onheap_bytes=98304, objects=3,FAIL
    false 8192 0 残留 0 残留 0 字节 / 0 对象 onheap_bytes=98304, objects=3,FAIL
    true 100 0 残留 0 残留 0 字节 / 0 对象 offheap_bytes=98304,FAIL
    true 8192 0 残留 0 残留 0 字节 / 0 对象 offheap_bytes=98304,FAIL

    4.2-dev 严格探针共 12/12 子场景通过,独立复跑也通过。上游 TestStreamingSpillFailureBufferOwnership 的 12 个 success/error/panic 子场景通过,并通过 tracking buffer 检查重复归还;TestStreamingSpillReleasesMergeBuffer 的 8 个 success/error 子场景也通过。

    为什么 main 仍失败,而 4.2-dev 已通过

    当前 main 的 trySpillMergeSortStreaming 仍在 mergeutil.MergeSortBatches(...) 正常返回后才执行非 defer 的:

    sinker.putBackBuffer(buffer)

    Sink panic 会直接越过该归还操作,输出 batch 的引用遗失,后续 Close() 无法释放,所以四个 main panic 子场景都残留 98,304 字节。

    最新 4.2-dev 已包含 7283f12d0eaf919e253dab4ed0d7dc0828c6ff8e(#32155)和 e4f70a7268d46ea4ec45f87dceaf5b0e3f3d91d8(#32164),并通过 merge-base --is-ancestor 核实。其 streaming spill 对输出 buffer 建立了 defer 清理所有者,panic unwind 时也会归还;对应上游 panic 回归及本次独立探针均为零残留。

    回归归属和边界

    本项没有新增 motr 用例:资源所有权和 mpool 不变量应由 owning Go 测试覆盖。最新 4.2-dev 已有上述 panic 回归;main 应补齐同类 panic-safe 实现与 success/error/panic × on/off-heap × partial/full block 回归后,再申请整体验收关闭。

    本轮完成的是确定性 Go 故障注入,不是生产 OOM 全量归因,也未复测旧部署版本 71498157...。临时 Go 探针已删除,未修改产品实现。

  4. Ariznawlll commented on Nov 17, 2026

    @Ariznawlll
    Collaborator

    关闭说明(按分支拆分跟踪)

    本 issue 跟踪的 4.2-dev 场景已在 e8fd84b331f168eafd0ec28149b043eaebc7e39d 验证通过:streaming spill 的 FileSinker.Sink panic 后,on/off-heap、100/8192 行均在 recover + Sinker.Close() 后回到 mpool 基线;相关上游 Go 回归和独立复跑均通过。

    补充验证在 main e1160015bb5895c1677d5fc1496c4bee440592b3 上发现的同类 panic 泄漏仍成立(4 种组合各残留 98,304 字节),但按研发安排,main 相关问题已另开 issue 跟踪,不再包含在本 4.2-dev issue 的范围内。

    因此本 issue 按 4.2-dev 的验证结果以 COMPLETED 关闭;main 的实测反例保留在上一条 comment,后续在新 main issue 继续验收,不代表 main 问题已修复。

  5. Ariznawlll commented on Nov 17, 2026

    @Ariznawlll
    Collaborator

    重新打开:此前关闭流程不符合“先完成对应 motr 回归,再关闭”的要求。本 issue 在关闭时没有对应的 motr 用例 PR;已有 TKE 验证或研发 Go 测试不能替代本次要求的 motr 交付。现恢复 Open,保持跟踪,待补齐回归交付后再给出关闭结论。

  6. Ariznawlll commented on Nov 17, 2026

    @Ariznawlll
    Collaborator

    验证与 motr 回归交付完成

    已创建 4.2-dev 专用回归 PR:matrixorigin/motr#357,当前 OPEN、尚未合入。最新 head e17a86b15d0371d98e7def5ea23aa505b0b1eecd 的 Python 3.10/3.12/3.13 与 Go 四项 CI 全部通过。

    • 固定 MatrixOne 4.2-dev@e8fd84b331f168eafd0ec28149b043eaebc7e39d,真实无空格物理源码路径。
    • 用例及 baseline:script/14_issue_regression/issue_32154_streaming_spill_buffer_ownership.py 与对应 .out。
    • include/motr_go_regression.py 实际执行并检查 TestStreamingSpillFailureBufferOwnership、TestStreamingSpillReleasesMergeBuffer、TestStreamingRealCompressBufRejection 三个 root test,覆盖 panic/recover、merge buffer 所有权和真实 compress buffer 拒绝。
    • 最终两轮 motr 定向复跑均通过,无 SKIP/FAIL;每个指定 root test 必须同时有 RUN 和 PASS 记录。
    • 分支发现数量与 compatibility/4.2-dev.cases 白名单已同步为 548,未通过显式命名绕过目标分支约束。

    当前 main 没有与 4.2-dev 相同的 panic-ownership fixture,因此没有把本结果冒充 main 覆盖;main 同类问题由未指派给我的 #32156 跟踪,不在本次验证范围。

    依据上述 4.2-dev 实测、真实 baseline、复跑和 motr 交付证据,现关闭本 issue。物理多节点、长稳与 main 同类问题不在本次关闭结论内。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

ai-easykind/bugneeds-triage

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions