Skip to content

[Bug]: shared broadcast HashBuild can be canceled by one probe's normal early completion #29642

Closed

Description

@XuPeng-SH

Is there an existing issue for the same bug?

  • I have checked the existing issues.

已检索 shared/build/cancel、HashBuild、broadcast 相关 issues。#26745 是真实 HashBuild 失败被 cancellation 掩盖,#26408 是 spill bucket 所有权问题;本 issue 是正常结束的单个消费者提前取消仍被其他消费者需要的共享 producer,与二者不同。

Branch Name

main

Commit ID

614ab46

Other Environment Information

  • 本地 macOS / arm64,Go 1.26.4;native CGo 按仓库流程构建。
  • 白盒拓扑:AP multi-CN 编译模式,同一个 CN 上两个 probe scopes,共享一个 broadcast HashBuild,JoinMapRefCnt = 2。
  • 未启用 spill;没有内存耗尽、用户取消或 query deadline。
  • 证据边界:已证明生产编译/执行组件组合下的生命周期缺陷;尚未确认完整 SQL planner 能生成测试中手工组合的外层 join 拓扑,也尚未证明 refactor(test): make planner fixture ownership explicit #29638 CI 与此机制同源。不能把下面白盒测试等同于端到端 SQL 复现。

Actual Behavior

共享 broadcast HashBuild 被挂在第一个 probe scope 的 PreScopes 下,并继承它的 pipeline context。第一个 probe 的外层 INNER HashJoin 因自己的 build 为空而正常提前结束;生产 Pipeline.Cleanup 取消该 probe 的 context,连带取消正在读取的共享 HashBuild。另一个消费者仍需要这个 build,且 query context 仍然有效,却收到 context canceled,输出 0 行。

诊断对照输出:

common_owner=false first_error=<nil> producer_error=<nil> build_cause=pipeline consumer finished second_error=context canceled query_error=<nil> rows=0
common_owner=true  first_error=<nil> producer_error=<nil> build_cause=pipeline consumer finished second_error=<nil> query_error=<nil> rows=3

第二行仅在测试中把 shared build 的 context parent 改为公共 query owner;数据、执行顺序和其他操作保持一致。build_cause 在运行完成后打印,正常 producer 自己的 Cleanup 也会设置正常停止原因,所以归因依赖屏障和对照,而非这一字段单独判断。

Expected Behavior

共享 producer 的生存期不能隶属于某一个消费者。一个消费者正常结束,只能退出自身的消费需求,不能中断其他仍存活消费者需要的 build。

仍须保持:

  • 真正的 build/read 错误向依赖者传播,不能将 cancellation 吞成成功空结果;
  • 用户取消、deadline、全部消费者退出时,producer 能及时结束并释放资源;
  • 不增加无界等待、无用后台计算或多余状态机。

Steps to Reproduce

  1. 在独立 worktree checkout 上述 main commit;按仓库流程执行 make -j8 cgo。
  2. 将下方完整测试保存为 pkg/sql/compile/diagnostic_shared_broadcast_lifetime_test.go。测试复用仓库已有 NewMockCompile 和 newLazyUnionAllInt8Batch fixture。
  3. 执行:
.agents/skills/mo-dev/scripts/mo-cgo-test -count=100 -v -timeout=60s -run '^TestDiagnosticCompilerSharedBroadcastBuildRetirement$' ./pkg/sql/compile
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=100 -v -timeout=120s -run '^TestDiagnosticCompilerSharedBroadcastBuildRetirement$' ./pkg/sql/compile
  1. 两个子用例分别验证当前缺陷和单变量反事实对照。当前缺陷用例断言第二消费者 cancellation / 0 行,对照断言成功 / 3 行;因此测试 PASS 是“现象被确认”,不是“生产问题已经修复”。

本地结果:普通运行 100/100 对用例符合上述结果;race 运行 100/100 对用例符合上述结果,未报告 data race。同步采用 channels 屏障,无 sleep;10 秒 timer 仅为实验 hang guard。缺陷路径没有手工调用取消,取消来自真实 empty-build early stop 后的 Pipeline.Cleanup。

完整白盒测试(放入 compile package)
package compile

import (
	"context"
	"testing"
	"time"

	"github.com/matrixorigin/matrixone/pkg/common/mpool"
	"github.com/matrixorigin/matrixone/pkg/container/batch"
	"github.com/matrixorigin/matrixone/pkg/container/types"
	planpb "github.com/matrixorigin/matrixone/pkg/pb/plan"
	"github.com/matrixorigin/matrixone/pkg/perfcounter"
	"github.com/matrixorigin/matrixone/pkg/sql/colexec"
	"github.com/matrixorigin/matrixone/pkg/sql/colexec/hashbuild"
	"github.com/matrixorigin/matrixone/pkg/sql/colexec/hashjoin"
	"github.com/matrixorigin/matrixone/pkg/sql/colexec/output"
	plan2 "github.com/matrixorigin/matrixone/pkg/sql/plan"
	"github.com/matrixorigin/matrixone/pkg/vm"
	"github.com/matrixorigin/matrixone/pkg/vm/engine"
	"github.com/matrixorigin/matrixone/pkg/vm/message"
	"github.com/matrixorigin/matrixone/pkg/vm/process"
	"github.com/stretchr/testify/require"
)

func TestDiagnosticCompilerSharedBroadcastBuildRetirement(t *testing.T) {
	for _, sharedOwner := range []bool{false, true} {
		name := "compiler_first_probe_owner"
		if sharedOwner {
			name = "common_owner_whitebox_control"
		}
		t.Run(name, func(t *testing.T) { diagnosticCompilerBroadcastRetirement(t, sharedOwner) })
	}
}

type diagnosticGatedBuildReader struct {
	*colexec.MockOperator
	started, release chan struct{}
	first            bool
}

func (r *diagnosticGatedBuildReader) Call(proc *process.Process) (vm.CallResult, error) {
	if !r.first {
		r.first = true
		close(r.started)
		select {
		case <-r.release:
		case <-proc.Ctx.Done():
		}
		if err := proc.Ctx.Err(); err != nil {
			return vm.CancelResult, err
		}
	}
	return r.MockOperator.Call(proc)
}

func diagnosticCompilerBroadcastRetirement(t *testing.T, sharedOwner bool) {
	c := NewMockCompile(t)
	c.counterSet = &perfcounter.CounterSet{}
	c.MessageBoard = message.NewMessageBoard()
	c.proc.SetMessageBoard(c.MessageBoard)
	c.addr = "cn1:6001"
	c.cnList = engine.Nodes{{Addr: c.addr, Mcpu: 1}, {Addr: "cn2:6001", Mcpu: 1}}
	c.execType = plan2.ExecTypeAP_MULTICN
	c.anal = &AnalyzeModule{qry: &planpb.Query{}}
	makeJoin := func(tag int32) *hashjoin.HashJoin {
		col := func(rel int32) *planpb.Expr {
			return &planpb.Expr{Typ: planpb.Type{Id: int32(types.T_int8)}, Expr: &planpb.Expr_Col{Col: &planpb.ColRef{RelPos: rel, ColPos: 0}}}
		}
		op := hashjoin.NewArgument()
		op.JoinType = planpb.Node_INNER
		op.JoinMapTag = tag
		op.EqConds = [][]*planpb.Expr{{col(0)}, {col(1)}}
		op.LeftTypes, op.RightTypes = []types.Type{types.T_int8.ToType()}, []types.Type{types.T_int8.ToType()}
		op.ResultCols = []colexec.ResultPos{{Rel: 0, Pos: 0}}
		return op
	}
	makeScope := func(op vm.Operator) *Scope {
		s := newScope(Remote)
		s.NodeInfo = engine.Node{Addr: c.addr, Mcpu: 1}
		s.Proc = c.proc.NewNoContextChildProc(0)
		s.RootOp = op
		return s
	}
	firstInner, secondInner := makeJoin(42), makeJoin(42)
	firstInner.AppendChild(colexec.NewMockOperator())
	secondInner.AppendChild(colexec.NewMockOperator().WithBatchs([]*batch.Batch{newLazyUnionAllInt8Batch(c, 1, 2, 3)}))
	probes := []*Scope{makeScope(firstInner), makeScope(secondInner)}
	source := makeScope(colexec.NewMockOperator())
	c.compileBuildSideForBroadcastJoin(&planpb.Node{Stats: &planpb.Stats{HashmapStats: &planpb.HashMapStats{}}}, probes, []*Scope{source})
	require.Len(t, probes[0].PreScopes, 2)
	require.Empty(t, probes[1].PreScopes)
	buildScope := probes[0].PreScopes[1]
	hb := buildScope.RootOp.(*hashbuild.HashBuild)
	require.Equal(t, int32(2), hb.JoinMapRefCnt)
	unusedMerge := hb.GetChildren(0)
	reader := &diagnosticGatedBuildReader{MockOperator: colexec.NewMockOperator().WithBatchs([]*batch.Batch{newLazyUnionAllInt8Batch(c, 1, 2, 3)}), started: make(chan struct{}), release: make(chan struct{})}
	hb.SetChildren([]vm.Operator{reader})
	defer unusedMerge.Release()
	// An enclosing INNER join whose own build is empty may end before calling
	// this inner join. This is production HashJoin's empty-build early stop.
	outer := makeJoin(43)
	outer.AppendChild(firstInner)
	probes[0].RootOp = outer
	rows := 0
	probes[1].setRootOperator(output.NewArgument().WithFunc(func(b *batch.Batch, _ *perfcounter.CounterSet) error {
		if b != nil {
			rows += b.RowCount()
		}
		return nil
	}))
	c.scopes = probes
	budget, err := c.proc.GetExecutionResourceBudget()
	require.NoError(t, err)
	registry, err := mpool.NewAllocationAccountRegistry(1, 64)
	require.NoError(t, err)
	account, err := registry.OpenWithController(1<<20, budget)
	require.NoError(t, err)
	owners, err := collectAllocationAccountOwners(probes)
	require.NoError(t, err)
	configured, err := configureAllocationAccountOwners(owners, account)
	require.NoError(t, err)
	defer func() {
		for _, s := range probes {
			s.FreeOperator(c)
		}
		// As in Compile.clear, destroy the board-owned unclaimed map before
		// completing the statement's allocation account.
		c.MessageBoard.Reset()
		for i := len(configured) - 1; i >= 0; i-- {
			require.NoError(t, configured[i].ClearAllocationAccount(account))
		}
		_, _, err := registry.CompleteTerminal(account)
		require.NoError(t, err)
		for _, s := range probes {
			s.release()
		}
		c.proc.Free()
	}()
	c.InitPipelineContextToExecuteQuery()
	if sharedOwner {
		buildScope.Proc.BuildPipelineContext(c.proc.Ctx)
	}
	query, _ := process.GetQueryCtxFromProc(c.proc)
	require.True(t, message.SendJoinMapResult(message.NewJoinMapResult(nil), 43, false, 0, c.MessageBoard))
	producerResult := make(chan error, 1)
	go func() { producerResult <- buildScope.Run(c) }()
	select {
	case <-reader.started:
	case err := <-producerResult:
		t.Fatalf("producer did not reach read: %v", err)
	case <-time.After(10 * time.Second):
		c.proc.Cancel(context.DeadlineExceeded)
		<-producerResult
		t.Fatal("read barrier not reached")
	}
	// No injected cancellation: running the real empty outer join performs
	// normal Pipeline.Cleanup on the compiler-selected producer parent.
	firstErr := probes[0].Run(c)
	close(reader.release)
	require.NoError(t, firstErr)
	var producerErr error
	select {
	case producerErr = <-producerResult:
	case <-time.After(10 * time.Second):
		c.proc.Cancel(context.DeadlineExceeded)
		<-producerResult
		t.Fatal("build not canceled by owner cleanup")
	}
	secondErr := probes[1].Run(c)
	t.Logf("common_owner=%v first_error=%v producer_error=%v build_cause=%v second_error=%v query_error=%v rows=%d", sharedOwner, firstErr, producerErr, context.Cause(buildScope.Proc.Ctx), secondErr, query.Err(), rows)
	require.NoError(t, query.Err())
	require.NoError(t, producerErr)
	if sharedOwner {
		require.NoError(t, secondErr)
		require.Equal(t, 3, rows)
	} else {
		require.ErrorIs(t, secondErr, context.Canceled)
		require.Zero(t, rows)
	}
}

Additional information

缺陷机制与职责归属

  1. compileBuildSideForBroadcastJoin 为同 CN 多个 probe 创建共享 HashBuild;附加到 tmp[0].PreScopes,而 JoinMapRefCnt 记录多个消费者。
  2. buildContextFromParentCtx 按 PreScopes 递归建立 context 父子树。用于调度/等待的依赖关系,由此也成为取消所有权关系;“共享依赖”被误当成“第一个消费者独占的子任务”。
  3. HashJoin empty-build early stop 可以在未调用 probe child 前正常结束。
  4. Pipeline.Cleanup 在正常结束时以 ErrPipelineStopped 取消当前 proc;context 继承让共享 build 一起结束。
  5. HashBuild.finalizeBuildFailure 将 read 返回的 cancellation 发布为依赖失败;normalizeScopeRunError 可以把正常停止的 producer scope 错误归一为 nil,但另一仍存活消费者正确地保留依赖错误。因此 producer 返回 nil 不意味着共享 build 成功。

核心不变量:共享数据依赖不是某一消费者独占的取消子树。 应优先在已有 scope/context/producer 所有权职责上统一生命周期,避免另建一套状态机或通过错误吞噬掩盖问题。

白盒构造范围

  • 两 probe / shared HashBuild / RefCnt = 2 / 第一个 probe 持有 PreScopes 的关系由真实编译函数建立。
  • 第一个 probe 外层空 build INNER join 由实验手工组合;成功的空 JoinMap 由测试发布。
  • 用屏障 reader 替代 HashBuild 原 Merge transport 输入,确定 build 正在读取时第一个消费者先结束;并按确定顺序调用真实 Scope.Run。未运行完整 SQL 编译到 MergeRun 的端到端计划。
  • 公共 owner 子用例只作因果对照,不是完整修复方案。原共享 source/dispatch 的取消所有权、全部消费者停止时的回收,以及调度/等待环仍需一起审视,不能直接把所有 producer 无条件挂在 query context 下。

与重复 CI 现象的关联边界

调查入口:PR #29638,Pessimistic multi-CN BVT failure。

该 CI 中 pub_sub4.sql:180 的订阅表 INFORMATION_SCHEMA.STATISTICS 预编译查询预期 3 条索引记录,实际 context canceled;:183 本地表查询预期 2 条,也 cancellation。Coverage 因 BVT 必需 profile 未完整发布随后失败,是下游结果。日志尚不能确认首个取消 owner 或完整物理拓扑。

#29638 在相关 compiler/hashbuild/hashjoin/process/pipeline 路径没有引入生产代码修改;不能据上述 CI 直接归咎于 PR。#29619 已修复将执行失败吞为成功空结果的独立问题,不等于证明取消来源已经修复。

同时,main 上完整原始 pub_sub4 黑盒 fixture 本地 122/122 通过;prepared subscription/local metadata 查询在双 CN、forced AP 开关及首次/重复执行的对照中也通过。这些检查没有黑盒复现该 CI。

后续验证与影响范围

  • 找到真实 SQL/完整物理计划可达的非对称 early-stop shared-build 拓扑,再验证 main fail / fix pass;核对 CI 失败计划是否满足同一条件。
  • 检查同类 shared source、dispatch 与 build 的取消所有权,避免只改 build parent 后把问题转移到输入依赖。
  • 正交验证单消费者结束、全部消费者结束、build 真失败、用户取消、deadline;检查 map/board/allocation account 清理、goroutine 退出和等待环。
  • 性能验证要覆盖成功 build 和早停场景,确认修复不会让全部消费者退出后仍持续扫描/构建。
  • 当前证据仅支持该白盒拓扑下的查询失败,未证明数据损坏、生产事件频率或所有 broadcast joins 受影响。不考虑混合版本滚动升级;持久化数据兼容性如有改动仍需验证。

Activity

  1. added
    kind/bug
    on Oct 6, 2026
  2. self-assigned this
    on Oct 6, 2026
  3. XuPeng-SH commented on Oct 6, 2026

    @XuPeng-SH
    ContributorAuthor

    Further white-box investigation found a directly supported consumer path and a narrower correction:

    • A broadcast CROSS JOIN compiles to Product on each probe partition, with the shared HashBuild/source scheduled under the first probe.
    • Before the correction, that Product entered End at local probe EOF without receiving its build terminal. Its normal pipeline cleanup canceled the shared producer; a real source → Dispatch → Merge → HashBuild → Product → MergeRun fixture returned nil error with incomplete output. The surviving peer should have returned nine rows.
    • The fix makes true local EOF receive the existing build terminal before End. It retains recursive-marker passthrough before publication and the current owner/cleanup/cancellation paths, without a new context tree or producer state machine.

    The deterministic post-fix matrix covers nonempty peer, all probes empty, empty build, build failure, query cancel, and ancestor normal stop. All six pass with the race detector repeated 100 times, including exact result/error checks and zero allocation-account usage after quiescent cleanup. Operator tests additionally cover typed deadline/error outcomes, empty batches, Reset/reuse and map reference release.

    Executed SQL controls on both embedded CNs cover ordinary CROSS JOIN, CROSS JOIN inside recursive members with a preceding CTE, empty anchor/build, LIMIT 0 and prepared empty/nonempty/empty reuse. They pass, but do not establish that those particular SQL fixtures force the exact gated schedule.

    Boundaries: the original hand-composed outer HashJoin example is a diagnostic ownership counterexample, not proof of a supported public SQL plan. This is a confirmed production defect in the Product path; attribution of the original #29638 CI failure to the same mechanism remains unproved. When all probe partitions are empty, the fix now waits for finite build completion; this is an explicit correctness cost, not a claimed universal performance improvement.

  4. Ariznawlll commented on Oct 8, 2026

    @Ariznawlll
    Collaborator

    在包含修复 #29666 的当前 main bab4b3286a0dd5683a9b291763817722233e586c 上补充了生命周期矩阵复核。

    白盒生产组件矩阵:

    • TestBroadcastProductSharedProducerOwnership
    • TestBroadcastHashJoinSharedProducerOwnership
    • TestBroadcastLoopJoinSharedProducerOwnership
    • HashJoin/LoopJoin remote source ownership
    • Product remote retirement before join
    • downstream placement
    • independent roots retire producer

    上述 8 组连续执行 20 轮通过,pkg/sql/compile 总运行 103.571s;随后使用 race detector 再执行 3 轮,18.315s 完成,没有 data race、重复释放或挂起。

    同时补充 SQL 控制:

    • prepared CROSS JOIN 在同一 handle 上按 empty → 9 rows → empty → 3 rows → 9 rows 复用,计数与 sum 均准确;
    • LIMIT 0 正常结束;
    • recursive CTE member 中 CROSS JOIN 得到 1,2,3;
    • probe 空表、build 空表均返回 0;恢复两侧数据后重新得到 9 行、sum=198。

    当前 main 未观察到一个消费者/空输入正常结束后影响后续共享 build 消费者的现象;普通与 race 矩阵也未发现 producer 清理回归。

  5. iamlinjunhong commented on Oct 9, 2026

    @iamlinjunhong
    Contributor

    CI evidence update for PR #29152 and run 37924039556:

    • Failed check: UT Coverage job 113799264820. The downstream Coverage job 113817861382 and CI Required job 113828348835 failed because the UT producer failed.
    • Stable signature: pkg/sql/compile / TestBroadcastHashJoinRemoteSourceOwnership/all_consumers_skipped, broadcast_product_lifetime_test.go:428: scheduler stopped before the empty consumer retired: <nil>.
    • Source PR/head: PR #29152, head f854ec8fe942ccaec856859808ee1afd3618dd6b at the failed run. The failing test is from the official main broadcast-product lifecycle fix and is not modified by this PR; the PR's compile changes are limited to Python UDF protocol admission/remote-expression paths.
    • Reproduction evidence: the exact test on the PR head passed in three consecutive runs; the same exact test on a clean current official up/main also passed in three consecutive runs. No code or test change was made for this unrelated lifecycle test.

    This records the failure as a non-PR flaky occurrence related to the shared broadcast producer lifecycle tracked here. The failed run will be rerun once after this evidence update.

  6. gouhongshen commented on Oct 10, 2026

    @gouhongshen
    Contributor

    CI evidence update for PR #29798 and run 38041641179:

    • Failed check: UT Coverage job 114183059618.
    • Stable signature: pkg/sql/compile / TestBroadcastHashJoinSharedProducerOwnership/all_consumers_skipped, broadcast_product_lifetime_test.go:428: scheduler stopped before the empty consumer retired: <nil>.
    • Source PR/head: PR #29798, head e3de6b6204380e6ae056f738e540e78f92a82b4f. This PR does not modify broadcast_product_lifetime_test.go or the broadcast producer/scheduler ownership path; its compile changes are limited to ALTER COPY lineage ordering/revalidation.
    • Reproduction evidence: the exact subtest passed three consecutive times on the PR head with .agents/skills/mo-dev/scripts/mo-cgo-test -count=3 -timeout=300s -run '^TestBroadcastHashJoinSharedProducerOwnership$/^all_consumers_skipped$' -v ./pkg/sql/compile; the full ./pkg/sql/compile package also passed on the same head.
    • No code or test change was made for this unrelated lifecycle failure. The failed run remains the source of truth; rerun will follow only after the parent run is terminal, per CI policy.
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