Repository navigation
Description
Is there an existing issue for the same bug?
- I have checked the existing issues.
Branch and commit
- Discovery branch:
fix/issue-26375-dedupjoin-cancellation - Discovery commit:
6d90f3ec88b744f26802329867c63e7f32536634 - The ownership behavior is also present in PR fix(dedupjoin): preserve parallel finalize failures #26393's base
8694a8d26dd8ef6e05ab0bdc133e4611c7430e1e; this is not introduced by that PR.
Code location
pkg/sql/colexec/dedupjoin/join.go:307-348, symbol:(*DedupJoin).buildpkg/vm/message/joinMapMsg.go:378-383, symbol:(*JoinMap).TakeSpillBuildFilespkg/sql/compile/scope.go:958-966, symbol:newParallelScopepkg/sql/compile/operator.go:2142, shared JoinMap ref count
Other Environment Information
- Hardware parameters: code-path review; no hardware dependency identified
- OS type: Darwin/arm64 review environment
- Others: discovered while reviewing PR fix(dedupjoin): preserve parallel finalize failures #26393
Actual Behavior
A non-shuffle parallel dedupjoin creates Mcpu operator copies, and HashBuild publishes one broadcast JoinMap pointer with ref count Mcpu. When that map is spilled, every dedupjoin clone calls the destructive, unsynchronized TakeSpillBuildFiles() on the same object.
Only one consumer is expected to receive the spill-file slice (and concurrent callers can race on the slice field). Other consumers initialize a SpillEngine with zero build buckets but still consume their own probe input. ScatterProbeTable creates probeFiles with len(e.buckets), so an empty-engine consumer retains none of its probe partition. Only the file-owning worker can have later spill rounds, while parallel finalization expects statuses from all workers per round.
Depending on which clone takes the files, the observable result can be incomplete dedup output, a later-round wait for participants that already exited, or termination that drops the file owner's remaining buckets.
Expected Behavior
Parallel spill execution must preserve every probe partition and have a consistent participant set for every spill round. Spill files/budget must have one explicit owner: either all probe partitions are routed through one spill consumer, or each worker receives an owned bucket representation that matches its round participation.
Steps to Reproduce
- Execute a non-shuffle dedupjoin plan with
Mcpu > 1. - Set/drive the hash-build spill threshold low enough that HashBuild publishes a spilled broadcast
JoinMap. - Let the parallel dedupjoin clones concurrently enter
(*DedupJoin).build. - Observe that they all receive the same JoinMap pointer and call
TakeSpillBuildFiles; only one engine owns buckets, while the others have an empty bucket queue and discard their probe partitions. - Continue into a later spill bucket and observe incomplete output or a finalize wait/early stop caused by the missing workers.
Evidence
Confirmed code facts
newParallelScopecreates exactlyMcpudedupjoin clones.constructHashBuildsetsJoinMapRefCnt = mcpu, and broadcast receivers return the sameJoinMappointer.TakeSpillBuildFilesmoves the slice out by reading the field and assigning nil without synchronization or cloning.- Every spilled dedupjoin clone executes this Take and initializes its own SpillEngine.
ScatterProbeTableretains probe files only for existinge.buckets.- No parallel + actual spilled JoinMap integration test exists in
pkg/sql/colexec/dedupjoin; the current round test manually gives every worker the same synthetic bucket sequence.
Inference
Under an actual parallel spilled build, consumer bucket sequences are not isomorphic. Probe rows processed by zero-bucket engines cannot contribute to output, and a file-owning merger can wait for workers that already exhausted their empty engines.
Impact
Parallel INSERT/REPLACE/UPDATE paths using dedupjoin under hash-build spill can return incomplete results, silently omit work, or fail to terminate until cancellation.
Unverified assumptions
- A complete SQL-level reproduction and the minimum row count/threshold have not yet been constructed.
- The exact owner winner is scheduler-dependent; validation should force ownership order deterministically.
Additional information
- Duplicate searches:
"TakeSpillBuildFiles" dedupjoin;parallel dedup join spill wrong result hangacross open and closed issues. - Reproduction status: code-path proof; no end-to-end SQL reproduction yet.
- Suggested validation: add a deterministic 2- or 3-worker integration test using one actual spilled broadcast JoinMap, distinct probe partitions, and at least two buckets; assert full output, bounded completion, and race-clean single ownership.
Follow-up audit: HashJoin and RightDedupJoin
Follow-up audit commit: 0ebba1c0c96bbcf0ff4091236e10df7b97e24a0c.
HashJoin: confirmed affected
The same ownership bug is reachable through normal non-shuffle broadcast HashJoin plans:
pkg/sql/compile/operator.go:214-241createsMcpuHashJoin copies for the broadcast probe side and designates copy 0 as merger.pkg/sql/compile/operator.go:2072-2151publishes one broadcastJoinMapwithJoinMapRefCnt = mcpu; all copies therefore receive the same pointer.pkg/sql/colexec/hashjoin/join.go:328-390makes every spilled HashJoin copy callTakeSpillBuildFiles()andTakeSpillBudget(), create a privateSpillEngine, and scatter its own probe partition.pkg/sql/colexec/spillutil/join_spill.go:1575-1662allocates probe files fromlen(e.buckets). A non-owner engine has zero buckets, consumes all child probe batches, and retains none of them.
For inner/left/semi/anti/single/mark joins, every non-owner probe partition is silently discarded, so only the worker that won the destructive Take can contribute rows.
For right/full/right-semi/right-anti/right-single joins, the shared bitmap finalization at pkg/sql/colexec/hashjoin/join.go:801-847 adds two failure modes:
- If the spill-file owner is the merger, it can wait for per-round bitmaps from zero-bucket workers that already exited; cancellation is the only bounded escape.
- If the owner is not the merger, the merger can finish before the owner completes all buckets, dropping remaining buckets and unmatched-build output; a late bitmap may remain buffered after the merger exits.
TakeSpillBuildFiles() and TakeSpillBudget() are also unsynchronized. A racy interleaving can let multiple workers observe the same spill files or budget. Shared *os.File offsets and independent engine cleanup then make duplicated ownership invalid even if more than one caller receives a non-empty value.
RightDedupJoin: currently protected by topology, but fragile
RightDedupJoin contains the same destructive Take pattern in pkg/sql/colexec/rightdedupjoin/join.go:192-262, but the audited normal SQL paths currently avoid shared ownership:
- The broadcast planner forces RightDedupJoin probe scopes to
Mcpu = 1atpkg/sql/compile/compile.go:4324-4334, so the broadcast HashBuild map has ref count 1. - In shuffle mode, each operator copy has a distinct
ShuffleIdx, and each shuffle HashBuild publishes a map with ref count 1.
Therefore RightDedupJoin is not confirmed as a currently reachable production bug. However, a manually constructed non-shuffle parallel topology, or a future removal of the Mcpu = 1 restriction, would expose the same loss. This topology invariant should be covered by regression tests.
Additional test gaps
- HashJoin's actual spill/re-spill integration coverage uses
IsShuffle = truewith one consumer; it does not exercise a shared broadcastJoinMap. - The zero-bucket HashJoin test only asserts that an empty engine returns no batch; it does not assert probe-row conservation.
- RightDedupJoin spill coverage also uses shuffle mode and ref count 1.
- There is no non-shuffle broadcast + actual spilled
JoinMap+Mcpu > 1integration test for HashJoin.
Suggested deterministic coverage:
- Use 2 or 3 HashJoin workers sharing one actual spilled broadcast
JoinMap, with distinct probe partitions and at least two buckets. - Force both ownership orders: merger owns the files, and a non-merger owns them.
- Cover an inner-family join and a right/full-family join; assert complete rows, bounded completion, and race-clean ownership.
- Add compile-topology tests that pin broadcast RightDedupJoin to
Mcpu/refcount = 1and shuffle RightDedupJoin to distinct refcount-1 maps.
A mutex around TakeSpillBuildFiles() alone is insufficient: it would remove the data race but preserve the data-loss topology. The fix needs either one spill coordinator that receives all probe partitions, or explicit independent/partitioned bucket ownership with probe conservation and per-bucket finalization coordination.
Activity
[-][Bug]: dedupjoin: parallel spill consumers lose bucket ownership or wait forever[/-][+][Bug]: parallel broadcast dedupjoin/hashjoin spill consumers lose bucket ownership or wait forever[/+]XuPeng-SH commentedon Jul 29, 2026
系统审计 / 第一性修复进展(2026-07-30)
1. 对原问题可达性的修正
正常 SQL 拓扑中,broadcast HashBuild 是
IsShuffle=false, JoinMapRefCnt=mcpu,而现有shouldSpillBatches对非 shuffle 恒为 false;shuffle HashBuild 才是IsShuffle=true, refCnt=1并可 spill。因此,#26408 描述的“共享 broadcast spill payload 被多个 consumer 分拆 Take”目前不是正常 SQL 可达路径,而是一个潜伏的所有权协议漏洞。真正可达且更严重的生产缺口是:broadcast join 完全没有 spill fallback。build 边即使超过阈值仍常驻内存;planner 又主要按行数/固定类型决定 broadcast/shuffle,而不是按估算 build bytes 和实际 spill 能力决定。大 VARCHAR、部分 dedup 模式尤其容易落入该缺口。
同时确认
TakeSpillBuildFiles模式不只在 hashjoin,也存在于 dedupjoin/rightdedupjoin;所以修复按共享协议处理,没有给单个 operator 打补丁。2. 当前本地实现已经收口的通用问题
Take/FreeMemory原子竞争且只能成功一次,拒绝空/混合/缺 budget/共享 refcount payload,consumer 失败后仍关闭已移动资源。Compile.Reset回收上一代生成的 scope,避免重复执行、关闭 channel 复用和 O(executions) 增长。RLIMIT_NOFILE动态收紧并保留 headroom,unsupported/采样失败时 fail closed。注意:它看不到进程实际非-spill FD 数量,因此只能降低 EMFILE 风险,不能保证物理 open 永远成功。3. 真实 unhappy case 与性能证据
已用真实 operator / mpool / spill 文件验证,而不只是 mock:
refCnt=2、极低阈值、真实 build rows:证明仍常驻且不会进入 spill(用于固定上述可达性结论)。RLIMIT_NOFILE=128与运行期重新采样;remote spill threshold0/4096/100001三类 join 往返。-race均通过;关键并发/取消/代际/RLIMIT 用例做了 20–100 次重复。compile 全包仅有 3 个 parquet fanout 测试失败,已在干净 HEAD0ebba1c0c9独立复现,与本改动无关;受影响 compile 用例及 race 通过。性能场景(8192 build / 9216 probe,包含首次 spill + re-spill):
appendScatterRecord约占 65.8MB(76.8%)。CPU 主要落在微文件 create,而不是 RLIMIT 采样。4. 尚未解决,不能过拟合进本 issue 的架构风险
+0/-0、NaN、JSON1/1.0、带 scale 的 FLOAT、长 VECF32+0/-0。应以 nested-loop oracle 做 resident/spill differential tests,而不是逐类型补 hash 特例。<=100000被解释为 rows,>100000被解释为 bytes,在 100000→100001 处非单调。需要 versioned{value, unit},保留 legacy rows 迁移层,内部统一 bytes。appendScatterRecord分配。结论:本轮关闭的是跨 join 的危险所有权协议及一批真实异常路径;#26408 暴露出的根因不应只归结为某个
TakeSpillBuildFiles调用。broadcast spill、typed equality、threshold unit、微文件 fanout 仍应作为后续独立设计项完成后再宣称系统性解决。XuPeng-SH commentedon Jul 29, 2026
已提交系统性修复与 deep review 结果(2026-07-30)
修复已提交到 draft PR #26412:#26412
137345c111— atomic spill ownership、generation lifecycle、error/cancellation/budget/FD closureca26c9ee68— physical-I/O cancellation、reduced-fanout conservation、reader corruption/cancellation、DedupJoin per-round terminationDeep review 新发现并已修复
os.File.Write之间缺少检查。现在 admission 前和 Write 前都检查;真实文件用例证明 canceled write 后 file size、spill bytes、spill rows 均为 0。ScatterProbeTable总按 32 buckets hash,但只 handofflen(build buckets)个 writer。真实 1-bucket build + 1,000 probe rows 会丢掉落到 writer 1..31 的行。现在只接受 1..32 的 2 次幂 fanout,并按 build payload 实际 fanout 分桶;1,000 行完全守恒,0/3/33 在消费 child 前失败。handledLast表示“历史上发过”,Reset 却把它当“本轮已发”。第一轮 ack 后 worker 若在第二 bucket 前被正常 early-stop,merger 会永久等。现在状态只表示“当前 round status 已发布且未 ack”;两轮 reproducer 证明 Reset 会给下一轮发 nil-error abort,同时保留 cancellation-after-publish 不重复发送的性质。io.ErrUnexpectedEOF并清 decoded batch/reservation。builder.Free。常量 key executor 在 Prepare 即拥有 mpool vector,测试证明 keep/skip 两支 cleanup 后CurrNB回基线且 memory/disk/FD ledger 全为 0。验证与性能
vm/message、vm/process、hashbuild、spillutil、hashjoin、dedupjoin、rightdedupjoin:full test 与 full-race全部通过。-race -json实测 T,再按N=clamp(floor(30/T),1,100)重复:RLIMIT 用例 26 次,其余 13 个各 100 次,全部通过。origin/main=2e68774061用同样 race 参数复现完全相同断言。go vet、go build、git diff --check通过。仍需独立 issues,不应塞进本 PR
建议按独立 owner/验收标准建 follow-up,而不是继续扩大 #26412:
PR 目前保持 draft;#26408 暂不关闭,等待 CI、review,以及确认上述 follow-up issue 的拆分/owner。
XuPeng-SH commentedon Jul 29, 2026
Final update from draft PR #26412:
683196b64a.GroupSelsmaps, matched and unmatched-finalize paths, result/NULL semantics, vector-owner restoration, and mpool=0.Follow-up work should be separate issues rather than extending #26408 indefinitely. Recommended decomposition:
#26408 should close with #26412 once CI/review is green; it should not wait for those architectural follow-ups. I have not created the new issues yet, to avoid duplicates and to keep ownership/prioritization explicit.
fix join spill ownership and lifecycle (#26412)
XuPeng-SH commentedon Jul 30, 2026
Follow-up issues created
The architectural follow-ups from the #26412 deep review are now tracked independently:
These issues link back to #26408/#26412 and have separate acceptance criteria. #26408 does not need to remain open for their completion once #26412 satisfies its own merge/closure criteria.
XuPeng-SH commentedon Aug 1, 2026
Roadmap decision: #26563. Re-review shows that the shared broadcast-spill topology described here is not reachable through normal SQL compilation: the
!IsShufflespill guard predates #26412. The supported contract is broadcast/shared = resident-only + hard-budget controlled failure; shuffle = single-consumer spill. Keep the move-only payload and cleanup hardening already merged, but do not extend a shared-consumer spill protocol. Any follow-up should only centralize/assert spill capability and prove that invalid multi-consumer shuffle fails before file/token side effects.Ariznawlll commentedon Aug 5, 2026
测试版本
mainace13bf4b43773dd962f03325b22f58ed31fee91embed.RunBaseClusterTests启动的嵌入式 CN 集群;通过 MySQL SQL 协议、单连接执行,max_dop=1、forceOneCN=1。原问题验证
原 issue 描述的是并行 broadcast/shared-build spill 消费者可能丢失 bucket 所有权或永久等待。重新核对维护者的 roadmap 结论 后,当前普通 SQL 编译不会生成该 shared broadcast-spill 拓扑:
!IsShufflespill guard 已在 #26412 之前存在;受支持的契约是 broadcast/shared 仅驻留执行并在硬预算下受控失败,shuffle 才进入单消费者 spill。因此本轮没有把“普通 SQL 直接复现 shared broadcast spill”作为通过条件,而是在最新 main 上运行已合入的 SQL 回归,覆盖可达且受支持的 shuffle spill 执行路径:
结果:3 轮均通过(本次总耗时 14.681s),无 panic、超时或遗留连接。用例源码见
issue_26408_join_spill_test.go。Happy Path 覆盖
cluster by k表;build 侧插入1..4096,probe 侧插入 4096 条相同 key7。该 probe 分布命中曾有风险的allBatchInOneRange边界。table_stats(..., 'patch', ...)固定统计信息,让优化器稳定选择shuffle: range(...);先设置@@join_spill_mem=0运行 resident 对照查询。@@join_spill_mem降至rows/128,运行同一等值 join。断言count(*)、两侧sum(payload)与 resident 对照完全一致。EXPLAIN (ANALYZE true)断言仍为shuffle: range(...),并且SpillRows、SpillSize为正值;同时断言 HashBuild 的第一层 spill 与第二层 re-spill 计数器均增加,避免仅验证“查询返回”而没有实际走 spill。Unhappy Path 覆盖
白盒验证
本次主验证是从 SQL 协议进入优化器、编译器和执行器的嵌入式集成测试;没有伪造共享 spill consumer。该用例直接观测
HashBuildSpillDepthCounter的 spill/re-spill 增量,并检查 EXPLAIN ANALYZE 中的实际 spill 统计。此前相关colexec生命周期包已执行-count=3和-race;本轮针对 #26408 再次执行了上述精确 SQL 用例 3 轮。回归测试
pkg/tests/issues/issue_26408_join_spill_test.go。测试证据
ace13bf4b43773dd962f03325b22f58ed31fee91go test -count=3 ./pkg/tests/issues -run '^TestIssue26408JoinSpillSQLRegression$'ok github.com/matrixorigin/matrixone/pkg/tests/issues 14.681spkg/tests/issues/issue_26408_join_spill_test.go测试结论
测试通过。
Ariznawlll commentedon Aug 12, 2026
关闭说明:维护者已确认原始 shared broadcast-spill 拓扑不会由普通 SQL 编译生成;当前受支持且可达的 shuffle spill/re-spill 路径已通过确定性 SQL 集成回归,resident/spilled 结果一致,实际 spill 指标为正,且无 panic、超时或资源清理异常。
扩大数据量无法覆盖不可达的 shared broadcast-spill 拓扑,因此本 issue 不需要 big-data 回归;极端倾斜、spill storage 和性能扩展已由独立 follow-up issues 跟踪。测试证据见:#26408 (comment)
fix join spill ownership and lifecycle (matrixorigin#26412)
fix join spill ownership and lifecycle (matrixorigin#26412)
fix join spill ownership and lifecycle (matrixorigin#26412)