Skip to content

[Bug]: parallel LOAD workers data-race on the shared tree.ExternParam in External.Prepare #31483

Closed

Description

@iamlinjunhong

Is there an existing issue for the same bug?

Branch Name

main

Commit ID

baa83f4 (local workspace HEAD, tested 2026-10-27)

Other Environment Information

  • Hardware parameters: Apple Silicon (arm64), macOS; Go unit test only, no mo-service needed
  • OS type: darwin/arm64, go1.27.1, CGO enabled (third-party headers from thirdparties/install, the standard make cgo layout)

Actual Behavior

For one LOAD DATA statement, compile builds one statement-level *tree.ExternParam and embeds it by pointer into every External operator:

  • pkg/sql/compile/operator.go:1432 — constructExternal stores Extern: param into every operator it builds. It is called once per fan-out scope: whole-file multi-file fanout (compileExternScanWholeFileFanout, compile.go:4134-4187, one scope per file at compile.go:4166), Parquet/Arrow/Hive whole-file fanouts, the serial reader, and the byte-range parallel coordinator.
  • pkg/sql/compile/operator.go:461 — dupOperatorWithContext (the vm.External case) carries Extern: t.Es.Extern into every parallel worker dup created by newParallelScope (scope.go:1480) for single-file byte-range parallel loads (compileExternScanParallelReadWrite, compile.go:5061-5167).

Fan-out scopes and parallel dups each run their pipeline's Prepare in their own goroutine, and External.Prepare writes into that shared struct:

// pkg/sql/colexec/external/external.go
126:  if param.Extern.FileService == nil {
130:      param.Extern.FileService = proc.Base.FileService  // write to shared struct
131:  }
...
171:  param.Ctx = proc.Ctx
172:  if param.Extern.ScanType != tree.INLINE && !param.Extern.Local && param.ForeignScan == nil {
173:      param.Ctx = process.SQLFileAccessContext(proc.Ctx, proc)
174:  }
175:  param.Extern.Ctx = param.Ctx                          // write to shared struct

Two consequences, both reproduced by the unit test below:

  1. Data race / undefined behavior. go test -race reports two DATA RACEs between concurrently preparing workers: a read (external.go:126) racing a previous write (external.go:130) on Extern.FileService, and a write/write pair on Extern.Ctx (both at external.go:175). Under the Go memory model the program is undefined once the race fires; interface values are two words, so torn reads are possible in principle. Any race-enabled build or unit test that prepares more than one External worker concurrently (multi-file parallel LOAD, or single-file parallel LOAD with mcpu > 1) trips this.

  2. Last-writer-wins context binding. Deterministically, without -race: after worker 1 prepares, the ctx object stored in the shared Extern.Ctx is worker 1's, not worker 0's — worker 0's earlier binding has been silently overwritten. Extern.Ctx is consumed on the reader side (for example newCSVParserFromReader sets the JSONLINE parser's cancellation context from it via config.Context = extern.Ctx). Today the per-worker values coincide in the common local topology (workers derive from one statement context, and fileservice.WithSQLFileAccess returns the parent unchanged when an identical policy is already attached), which is why nothing visibly breaks — but the shared overwrite is real, -race fails, and any per-shard context derivation introduced later (per-scope timeouts, per-scope cancellation) silently binds a worker's parser to a foreign cancellation context.

Expected Behavior

A worker's Prepare must not mutate statement-level shared configuration. The per-operator Es.Ctx (already populated at external.go:171-174) is the right home for the per-worker context, and the FileService installation for remote-decoded parameters (the stated purpose of the nil check, external.go:127-129) can be done once at decode time instead of on every Prepare. Recommended fix: keep tree.ExternParam read-only per scope and store the per-worker ctx in the per-operator ExternalParam, pointing reader-side consumers at param.Ctx. An equally valid alternative is deep-copying the *tree.ExternParam per operator, the way the dependent-source path already does (pkg/sql/compile/dependent_external.go:77-81 makes a per-operator copy — the pattern is proven in-repo). With either fix, concurrently preparing workers touch only their own state.

Steps to Reproduce

  1. Save the test file below as pkg/sql/colexec/external/loom_test_extern_ctx_race_test.go in a MatrixOne checkout. It uses only library packages (testutil, tree, plan, process) — no other test-file helpers needed.

  2. Run with the race detector — expects FAIL with two DATA RACE reports (read external.go:126 vs write external.go:130 on Extern.FileService; write/write at external.go:175 on Extern.Ctx):

cd <matrixone-repo>
CGO_ENABLED=1 CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" \
  go test -count=1 -race -run 'TestLoomParallelPrepareWritesSharedExternCtx' -v \
  ./pkg/sql/colexec/external/
  1. Run without -race — expects PASS; Phase A of the test then deterministically asserts the last-writer-wins overwrite of the shared Extern.Ctx:
cd <matrixone-repo>
CGO_ENABLED=1 CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" \
  go test -count=1 -run 'TestLoomParallelPrepareWritesSharedExternCtx' -v \
  ./pkg/sql/colexec/external/

Test source (constructs exactly what compile builds for parallel workers: a fresh per-worker ExternalParam whose Extern is the shared pointer, mirroring operator.go:446-481 / 1424-1453):

// Copyright 2026 Matrix Origin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package external

import (
	"testing"

	"github.com/matrixorigin/matrixone/pkg/pb/plan"
	"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
	"github.com/matrixorigin/matrixone/pkg/testutil"
	"github.com/matrixorigin/matrixone/pkg/vm/process"
	"github.com/stretchr/testify/require"
)

// newSharedExternParam mimics pkg/sql/compile operator construction: the
// compile-owned *tree.ExternParam for one LOAD/statement is stored by POINTER
// into every External operator built for the statement -- constructExternal
// embeds it via `Extern: param` (pkg/sql/compile/operator.go:1432), and
// dupOperatorWithContext carries the pointer into every parallel worker dup
// via `Extern: t.Es.Extern` (operator.go:461).
func newSharedExternParam() *tree.ExternParam {
	return &tree.ExternParam{
		ExParamConst: tree.ExParamConst{
			Format: tree.CSV,
			Tail:   &tree.TailParameter{},
		},
		ExParam: tree.ExParam{
			ExternType: int32(plan.ExternType_LOAD),
			Parallel:   true,
		},
	}
}

// newWorkerLikeCompile mirrors operator.go:446-481 (vm.External dup) and
// operator.go:1424-1453 (constructExternal): a fresh per-worker ExternalParam
// whose Extern is the SHARED *tree.ExternParam pointer.
func newWorkerLikeCompile(t *testing.T, shared *tree.ExternParam, idx int) (*External, *process.Process) {
	t.Helper()
	proc := testutil.NewProcess(t)
	es := &ExternalParam{
		ExParamConst: ExParamConst{
			Extern:        shared,
			Idx:           idx,
			StrictSqlMode: true,
		},
		ExParam: ExParam{
			Filter:    &FilterParam{},
			Fileparam: &ExFileparam{},
		},
	}
	return NewArgument().WithEs(es), proc
}

// TestLoomParallelPrepareWritesSharedExternCtx proves two things about
// External.Prepare writing the *tree.ExternParam it only borrows:
//
//  1. Deterministically (sequential): every worker's Prepare overwrites the
//     SHARED Extern.Ctx (external.go:175 `param.Extern.Ctx = param.Ctx`),
//     so after any later worker prepares, an earlier worker's per-worker
//     context (the parser's cancellation/context binding) is replaced by
//     the last writer's -- last-writer-wins on shared state.
//  2. Under `go test -race`: workers preparing concurrently (the exact
//     construction compile uses for multi-file fanout scopes and
//     single-file byte-range parallel dups, which run each scope's pipeline
//     Prepare in its own goroutine) produce unsynchronized data races on the
//     shared interface fields Extern.Ctx and Extern.FileService.
func TestLoomParallelPrepareWritesSharedExternCtx(t *testing.T) {
	// ---- Phase A: sequential overwrite semantics ----
	sharedA := newSharedExternParam()
	op0, proc0 := newWorkerLikeCompile(t, sharedA, 0)
	op1, proc1 := newWorkerLikeCompile(t, sharedA, 1)
	defer op1.Free(proc1, false, nil)
	defer op0.Free(proc0, false, nil)

	require.NoError(t, op0.Prepare(proc0))
	worker0Ctx := op0.Es.Ctx
	require.Equal(t, worker0Ctx, sharedA.Ctx,
		"worker 0's prepare binds the shared extern to its own ctx")

	require.NoError(t, op1.Prepare(proc1))
	require.False(t, op0.Es.Ctx == sharedA.Ctx,
		"worker 1's prepare has overwritten the ctx object that worker 0's reader will bind (same shape, different object)")
	require.True(t, op1.Es.Ctx == sharedA.Ctx,
		"the shared field now holds worker 1's ctx: last writer wins")

	// ---- Phase B: concurrent prepare, as compile runs fanout/dup scopes ----
	sharedB := newSharedExternParam()
	const workers = 4
	ops := make([]*External, workers)
	procs := make([]*process.Process, workers)
	for i := 0; i < workers; i++ {
		ops[i], procs[i] = newWorkerLikeCompile(t, sharedB, i)
		defer ops[i].Free(procs[i], false, nil)
	}
	errCh := make(chan error, workers)
	start := make(chan struct{})
	for i := 0; i < workers; i++ {
		go func(i int) {
			<-start
			errCh <- ops[i].Prepare(procs[i])
		}(i)
	}
	close(start)
	for i := 0; i < workers; i++ {
		require.NoError(t, <-errCh)
	}
	t.Log("all concurrent prepares done; run with -race to see the data race on Extern.Ctx/Extern.FileService")
}

Additional information

  • Production trigger paths (all intra-CN; remote-decoded scopes rebuild their own extern from the wire message at remoterun.go:1770-1816, so cross-CN sharing is not involved):
    • Multi-file parallel LOAD: compileExternScanWholeFileFanout (compile.go:4134-4187) builds one scope per file, each via constructExternal (compile.go:4166); scopes run concurrently (MergeRun → ants goroutines, scope.go:610-628), each scope pipeline calling Prepare in its own goroutine.
    • Single-file byte-range parallel LOAD (LOAD DATA ... PARALLEL 'true' on a large uncompressed CSV/JSONLINE): compileExternScanParallelReadWrite (compile.go:5061-5167) → at runtime buildLoadParallelRun → newParallelScope → dupOperatorRecursivelyWithContext → vm.External case (operator.go:446-481) shares t.Es.Extern (operator.go:461) with every worker dup.
  • Why values usually coincide today (and why it is still a bug): parallel workers derive from one statement context; fileservice.WithSQLFileAccess (pkg/fileservice/sql_file_access.go:34-35) returns the parent context unchanged when the attached policy is equal, so all workers often store the very same context object. The race is a Go-memory-model violation regardless, the deterministic overwrite (Phase A) turns into a wrong cancellation-context binding the moment per-scope context derivation is introduced, and race-enabled builds/tests fail today.
  • Fix locations: External.Prepare (pkg/sql/colexec/external/external.go:126-131 and 171-175) plus the pointer-sharing construction sites (pkg/sql/compile/operator.go:1432, operator.go:461). The per-operator Es.Ctx already carries the per-worker value for readers to consume.
Full reproduction, exactly as Loom ran it
Save as pkg/sql/colexec/external/loom_test_extern_ctx_race_test.go and run:

# with race detector (expected: FAIL, two DATA RACE reports on shared Extern.Ctx / Extern.FileService):
cd <matrixone-repo>
CGO_ENABLED=1 CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" \
  go test -count=1 -race -run 'TestLoomParallelPrepareWritesSharedExternCtx' -v \
  ./pkg/sql/colexec/external/

# without -race (expected: PASS; Phase A asserts the last-writer-wins overwrite):
CGO_ENABLED=1 CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" \
  go test -count=1 -run 'TestLoomParallelPrepareWritesSharedExternCtx' -v \
  ./pkg/sql/colexec/external/

--- file: pkg/sql/colexec/external/loom_test_extern_ctx_race_test.go ---
// Copyright 2026 Matrix Origin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package external

import (
	"testing"

	"github.com/matrixorigin/matrixone/pkg/pb/plan"
	"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
	"github.com/matrixorigin/matrixone/pkg/testutil"
	"github.com/matrixorigin/matrixone/pkg/vm/process"
	"github.com/stretchr/testify/require"
)

// newSharedExternParam mimics pkg/sql/compile operator construction: the
// compile-owned *tree.ExternParam for one LOAD/statement is stored by POINTER
// into every External operator built for the statement -- constructExternal
// embeds it via `Extern: param` (pkg/sql/compile/operator.go:1432), and
// dupOperatorWithContext carries the pointer into every parallel worker dup
// via `Extern: t.Es.Extern` (operator.go:461).
func newSharedExternParam() *tree.ExternParam {
	return &tree.ExternParam{
		ExParamConst: tree.ExParamConst{
			Format: tree.CSV,
			Tail:   &tree.TailParameter{},
		},
		ExParam: tree.ExParam{
			ExternType: int32(plan.ExternType_LOAD),
			Parallel:   true,
		},
	}
}

// newWorkerLikeCompile mirrors operator.go:446-481 (vm.External dup) and
// operator.go:1424-1453 (constructExternal): a fresh per-worker ExternalParam
// whose Extern is the SHARED *tree.ExternParam pointer.
func newWorkerLikeCompile(t *testing.T, shared *tree.ExternParam, idx int) (*External, *process.Process) {
	t.Helper()
	proc := testutil.NewProcess(t)
	es := &ExternalParam{
		ExParamConst: ExParamConst{
			Extern:        shared,
			Idx:           idx,
			StrictSqlMode: true,
		},
		ExParam: ExParam{
			Filter:    &FilterParam{},
			Fileparam: &ExFileparam{},
		},
	}
	return NewArgument().WithEs(es), proc
}

// TestLoomParallelPrepareWritesSharedExternCtx proves two things about
// External.Prepare writing the *tree.ExternParam it only borrows:
//
//  1. Deterministically (sequential): every worker's Prepare overwrites the
//     SHARED Extern.Ctx (external.go:175 `param.Extern.Ctx = param.Ctx`),
//     so after any later worker prepares, an earlier worker's per-worker
//     context (the parser's cancellation/context binding) is replaced by
//     the last writer's -- last-writer-wins on shared state.
//  2. Under `go test -race`: workers preparing concurrently (the exact
//     construction compile uses for multi-file fanout scopes and
//     single-file byte-range parallel dups, which run each scope's pipeline
//     Prepare in its own goroutine) produce unsynchronized data races on the
//     shared interface fields Extern.Ctx and Extern.FileService.
func TestLoomParallelPrepareWritesSharedExternCtx(t *testing.T) {
	// ---- Phase A: sequential overwrite semantics ----
	sharedA := newSharedExternParam()
	op0, proc0 := newWorkerLikeCompile(t, sharedA, 0)
	op1, proc1 := newWorkerLikeCompile(t, sharedA, 1)
	defer op1.Free(proc1, false, nil)
	defer op0.Free(proc0, false, nil)

	require.NoError(t, op0.Prepare(proc0))
	worker0Ctx := op0.Es.Ctx
	require.Equal(t, worker0Ctx, sharedA.Ctx,
		"worker 0's prepare binds the shared extern to its own ctx")

	require.NoError(t, op1.Prepare(proc1))
	require.False(t, op0.Es.Ctx == sharedA.Ctx,
		"worker 1's prepare has overwritten the ctx object that worker 0's reader will bind (same shape, different object)")
	require.True(t, op1.Es.Ctx == sharedA.Ctx,
		"the shared field now holds worker 1's ctx: last writer wins")

	// ---- Phase B: concurrent prepare, as compile runs fanout/dup scopes ----
	sharedB := newSharedExternParam()
	const workers = 4
	ops := make([]*External, workers)
	procs := make([]*process.Process, workers)
	for i := 0; i < workers; i++ {
		ops[i], procs[i] = newWorkerLikeCompile(t, sharedB, i)
		defer ops[i].Free(procs[i], false, nil)
	}
	errCh := make(chan error, workers)
	start := make(chan struct{})
	for i := 0; i < workers; i++ {
		go func(i int) {
			<-start
			errCh <- ops[i].Prepare(procs[i])
		}(i)
	}
	close(start)
	for i := 0; i < workers; i++ {
		require.NoError(t, <-errCh)
	}
	t.Log("all concurrent prepares done; run with -race to see the data race on Extern.Ctx/Extern.FileService")
}

Found by Loom bug hunt (module: custom-de41a00730; tests: unit, white-box, concurrency; severity: S1)

Activity

  1. added
    kind/bug
    severity/s1
    on Oct 27, 2026
  2. XuPeng-SH commented on Oct 28, 2026

    @XuPeng-SH
    Contributor

    QA status for merged main f97056d1107a89854bfac2c06202698e3aafd41e (#31496): this environment has not run the affected external package or the original concurrent Prepare race reproduction. Available headroom under the existing guard is insufficient for a safe large link. The PR reports focused and full package race tests by its author; they are not local results here. Per-worker context/FileService isolation, cancellation and race behavior remain pending independent verification. Assignee unchanged.

  3. added
    ai-easy
    on Oct 28, 2026
  4. Ariznawlll commented on Oct 28, 2026

    @Ariznawlll
    Collaborator

    结论

    测试通过。并行 LOAD 的 External worker 在准备和读取阶段不再共享、覆盖彼此的运行时上下文及 FileService;原共享模板保持不变。

    关键证据

    • 官方 main@4808a7befd38cc877606f1c7ceda41ff387b212e,包含合入修复 #31496 的 d3c8cf62fffc3f38e153d354af609e6fbd5729ab;macOS arm64、Go 1.27.1,隔离工作树执行组件原内部路径。
    • TestExternalPrepareIsolatesWorkers 模拟编译器传入同一 Extern 模板,两个 worker 并发 Prepare,分别校验各自 context、FileService 和真实 JSONLINE 读取值 1/2,模板未改写;取消一个 parser 不影响另一个,Reset/重新 Prepare 也不污染兄弟 worker。显式 FileService 与按 worker 补全两种情况均覆盖。
    • 上述场景与非法配置不污染模板、解码配置恢复的测试一起,常规重复 3 次、-race 重复 10 次均通过;完整 pkg/sql/colexec/external 包运行一次通过。原缺陷是组件内部共享状态和 race,已有 Go 回归直接覆盖,不用公共 SQL 伪装该 race。
    • 修复 PR CI 的 UT、SCA、PROXY 和多 CN pessimistic BVT 通过;排队规则单项显示失败,其他禁用项为 skipped。本轮未自行运行整套产品 CI。

    待解决点

    无;本次独立验证为内部路径与组件包测试,未另行启动多进程生产规模 LOAD。

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

Metadata

Metadata

Assignees

Labels

ai-easykind/bugseverity/s1

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions