Skip to content

[Bug]: CSV OUTFILE finalizer spins indefinitely after cancellation drops a conversion result #30737

Closed

Description

@XuPeng-SH

Summary

CSV SELECT ... INTO OUTFILE finalization can busy-spin indefinitely when request cancellation causes an asynchronous conversion worker to exit without publishing its result. The finalizer continues waiting for that sequence number and does not observe cancellation.

Confirmed with white-box tests calling the real frontend package functions on 4.2-dev, without modifying production code. This is a separate failure from Merge/Dispatch losing upstream completion notifications.

Revisions and validation scope

  • Confirmed real-package white-box reproduction: 4.2-dev, 7eba89b210cb5c0f8b5d1102ad450084b65c9c88.
  • Same code defect by inspection, plus extracted-function reproduction only: main, 838cc78aa1efe46693876a48c05c202979047b7b. Real-package/SQL verification on main is pending.
  • Linux amd64, Go 1.27.1; repository CGo test wrapper, native libmo rebuilt from the tested 4.2-dev tree.
  • Real SQL black-box reachability of the timing window is not yet reproduced on these branches. This report does not assert a production incident or a hotfix-branch reproduction.

Root cause and reachable timing window

  1. ExportConfig.Write increments Index and starts asynchronous constructByte conversion.
  2. runner.Run can complete successfully while conversion results remain pending; executeStatusStmt proceeds to exportAllDataFromBatches.
  3. Cancellation occurs before a pending conversion starts, or while it is delivering its result. constructByte checks the context and can clean its batch and return without publishing that index. sendExportBatchByte can also select ctx.Done() instead of sending.
  4. exportAllDataFromBatches still requires WriteIndex == Index. Its nonblocking channel receive and missing-index continue never check cancellation. The departed worker cannot publish the missing index, and no independent path advances it.
  5. The loop never reaches the subsequent pipe close or enclosing statement cleanup. An I/O error cannot interrupt iterations that never reach a write.

Source at the verified revision:

White-box reproduction

Use a package-local frontend test with one offheap int64 row (42), an ordinary CSV ExportConfig, and the existing backSession/mpool fixture. Call the original functions directly.

Case A: cancellation before pending worker starts

ep.init()
ep.Index.Store(1) // one submitted conversion; WriteIndex remains 0
ctx, cancel := context.WithCancel(context.Background())
ep.ctx = ctx
cancel()
constructByte(ctx, ses, bat, 1, ep.ByteChan, ep)
// Actual: worker returns, mp.CurrNB() == 0, len(ep.ByteChan) == 0.
err := exportAllDataFromBatches(ep) // does not return

Case B: cancellation after finalizer starts waiting

  • Gate the real conversion worker before calling constructByte.
  • Start the real exportAllDataFromBatches and observe its frame in a runtime goroutine stack before cancelling (no sleep-based phase assumption).
  • Cancel the request and release the gated worker.
  • Join the worker and assert mpool zero and an empty result channel.
  • Finalizer still does not return.

Both cases run in child test processes with a two-second test timeout, so the diagnostic cannot leave a spinning goroutine in the parent process. A twelve-second outer process guard also bounds the harness.

Normal control: uncancelled real conversion plus finalization returns successfully, produces exactly 42\n, clears the export map/channel, and releases the worker mpool. Only the normal control's disk Write callback is replaced with an in-memory output collector; production cancellation/finalizer functions are unchanged.

Command (with disk-backed TMPDIR/GOTMPDIR):

.agents/skills/mo-dev/scripts/mo-cgo-test -p=2 -count=1 -timeout=90s -v \
  -run '^TestQACSVFinalizer(Normal|Cancellation)$' ./pkg/frontend

Observed results:

--- PASS: TestQACSVFinalizerNormal (0.00s)
real canceled constructByte returned, mpool=0, no result for pending index=1
panic: test timed out after 2s

finalizer entered before cancel; real worker exited without result; mpool=0
panic: test timed out after 2s

--- FAIL: TestQACSVFinalizerCancellation (4.10s)
    --- FAIL: TestQACSVFinalizerCancellation/before-worker (2.05s)
    --- FAIL: TestQACSVFinalizerCancellation/while-finalizer-waits (2.05s)

Both timeout stacks contain:

goroutine [...] [runnable]:
github.com/matrixorigin/matrixone/pkg/frontend.exportAllDataFromBatches(...)
    pkg/frontend/export.go:887

Impact and expected behavior

  • A cancelled export can keep a CPU-spinning finalizer and retain its outer request/export state.
  • Worker batch leakage was not observed: the tested real worker cleans its offheap batch and mpool returns to zero. Request-state retention behind a nonterminating finalizer is a distinct concern.
  • Cancellation should return the cancellation/error outcome, with no missing-result wait, and release pipe/async writer/conversion resources on all exits.

Fix direction and acceptance checks

Use the existing export ownership boundary: make finalization observe cancellation while waiting for ordered results, return the correct error, and ensure terminal cleanup covers pipe, async writing and pending conversion results. Avoid adding a second terminal state machine or relying on every cancelled worker publishing a value.

Verify cancellation before conversion and during finalization, ordinary/empty exports, conversion and disk-write failures, live KILL/disconnect, exact successful output, and heap/offheap cleanup. Add real SQL evidence for the phase window separately. Track main and 4.2-dev fixes independently.

Related

Activity

  1. self-assigned this
    on Oct 21, 2026
  2. added
    kind/bug
    and removed on Oct 21, 2026
  3. added a commit that references this issue on Oct 21, 2026
    df656e8
  4. XuPeng-SH commented on Oct 21, 2026

    @XuPeng-SH
    ContributorAuthor

    转测记录(2026-10-22,4.2-dev):修复 PR #30742 已合入 release 分支。代码复核确认 CSV/JSON 转换 worker、顺序写入器、文件 pipe 和 cleanup 被放到同一取消/等待边界;PR 记录了前端包 normal/race、SQL 生命周期及取消压力覆盖。该 PR 描述注明更新 revision 的远端 CI 仍 pending,本地也缺 Go/mo-service/Docker,无法在本轮独立实跑。已保留 XuPeng-SH 并添加 Ariznawlll;复测请覆盖取消后不再忙循环、主错误保留、sink/worker 全部退出,以及同一 session 随后的查询仍可用。

  5. added a commit that references this issue on Oct 21, 2026
    3b5ccf1
  6. removed their assignment
    on Oct 21, 2026
  7. Ariznawlll commented on Oct 22, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 官方 main:a949c88af0ed2cc4fe98e2ac32f0732a1235bd85,修复 PR fix(frontend): terminate CSV export reliably on cancellation #30741 的 merge commit 3b5ccf1da2539b844b95fe33fcb85dd224c6d3be 已确认是其祖先。
    • 官方 4.2-dev:26d3a200cb13f4be3b5f64d489bac75d8dcc5814,backport PR [4.2-dev] fix: finalize exports safely and clean up S3 uploads #30742 的 merge commit df656e8c9bd00071c514c71dbdf24a625ec0aafd 已确认是其祖先。
    • 部署方式:两个独立、干净的本地 worktree;macOS arm64;嵌入式隔离集群为 1 LogService / 1 TN / 1 CN,经真实 MySQL 协议执行公开 SQL。未使用共享 TKE,也未修改主工作区。
    • 测试日期:2026-10-22。

    原问题验证

    本问题是内部异步转换结果丢失后的 finalizer 忙循环,不能靠随机 SQL 取消碰运气判断是否进入精确窗口。用前端包真实函数的永久 Go 用例,以 synctest 明确控制 worker 启动前取消和 finalizer 已等待时取消 两种时序;两种时序同时覆盖 CSV 与 JSONLINE,要求 exportAllDataFromBatches 返回 context.Canceled,finish 保留该主错误,worker 退出,mpool.CurrNB()==0,结果 channel / batch map 释放。main 和 4.2-dev 的定向普通测试各 -count=3 通过;两个分支各自的五组取消/顺序/pipe 定向测试 -race -count=10 通过。

    额外在 4.2-dev 嵌入式集群进行真实协议 SELECT SLEEP(2) INTO OUTFILE + KILL QUERY 压力探针,10/10 次返回 ERROR 1105 (HY000): context canceled,均未挂住,且同一连接后续 SELECT 1 均返回 1。该公开 SQL 探针证明取消后的有界返回和会话可用,但不声称它每次都落在“runner 结束后、转换结果未发布”的精确窗口;该窗口由上述确定性 Go 时序用例验证。

    Happy Path 覆盖

    1. main 与 4.2-dev 的 TestExportLifecyclePublicSQL -count=3 均通过:真实 MySQL 协议 SELECT id,note ... INTO OUTFILE 产生恰好两行 1,a、2,b,CSV 解析值正确,测试库/文件完成清理。
    2. 两分支 TestExportOrderedFinalization、TestExportSplitAndEmptyFileCleanup 等各 -count=3 通过:异步乱序结果最终按序输出 42\ntail\n,空文件/分片文件和 worker mpool 清理正确。

    Unhappy Path 覆盖

    1. 转换前取消、finalizer 等待中取消、结果通道提前关闭、sink/reader/writer/header/late-close 错误、转换失败:两分支定向普通测试各 3 次通过;对应主要取消/pipe 路径在两分支各 -race -count=10 通过,断言错误传播与 channel、pipe、worker、mpool 清理。
    2. 公开 SQL 的目标父路径是普通文件时,导出返回 not a directory;每轮两次拒绝后原表仍有 2 行,同连接可继续查询,main 和 4.2-dev 各 3 轮通过。
    3. 4.2-dev 真实协议 KILL QUERY 10/10:实际错误均为 context canceled,无超时,同一连接继续查询 SELECT 1 并返回 1。未执行外部节点故障或磁盘满注入;这些不属于本 issue 的原始触发机制。

    白盒验证

    • main:go test -race ./pkg/frontend -run '^TestExport(FinalizationCancellation|AbortJoinsBlockedConversions|OrderedFinalization|FinalizerClosedChannel|PipeCancellation)$' -count=10 -timeout=15m:PASS。
    • 4.2-dev:相同命令 -race -count=10:PASS;八组前端生命周期/失败/清理用例的普通运行各 -count=3:PASS。

    回归测试

    精确“worker 不发布结果 + finalizer 等待”阶段已有 MatrixOne 仓库的 前端 Go 回归;公开 SQL 成功/失败与会话复用已有 SQL 集成回归。这是内部确定性时序/资源所有权路径,按用户允许的 Go/race 回归方案,不向 MOTR #247 添加无法稳定卡住内部相位的重复 SQL 用例。本轮本地未运行整个仓库全套测试;main #30741 CI 和 4.2-dev #30742 CI 的相关 Linux UT、多 CN BVT 与 Required 检查均已通过。上述 CI 通过不被当作本轮 10 次 KILL 的替代。

    测试证据

    • 两个隔离工作树在上述完整 SHA 上独立运行;定向 Go/SQL 命令退出码均为 0。4.2-dev 的 10 次公开 KILL QUERY 探针每轮均输出 Error 1105 (HY000): context canceled 和 same-session select=1,最终 --- PASS: TestQA30737KillExportAndReuse (17.13s)。
    • 修复记录:main #30741、4.2-dev #30742。探针是隔离 QA 临时文件,运行后移除;仓库已有上述永久 Go 回归。

    测试结论

    测试通过。

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

Metadata

Metadata

Assignees

Labels

kind/bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions