Repository navigation
Description
Is there an existing issue for the same bug?
- I have searched issues and open PRs (keywords: "External.Prepare race", "constructExternal shared", "load fanout data race", "ExternParam", "Extern.Ctx", "is:pr is:open external Prepare", "is:pr is:open fix load data race"). The closest hits are different defects: [Bug]: JSONLINE truncated-record holdover aliases a reused parser buffer, so record continuation never works #31280 (JSONLINE holdover buffer aliasing), [Bug]: JSONLINE truncated-record holdover grows prevStr past LargestEntryLimit with no size bound #31304 (unbounded JSONLINE holdover size), [Bug]: ReadFileOffset boundary fixtures omit SQL file access policy and fail UT/coverage #30436 (ReadFileOffset fixture coverage), fix(sql): preserve LOAD locality during primary-key validation #30527 / fix(moerr): keep cancellation identity through ConvertGoError and RPC #29316 (unrelated). No issue or open PR reports shared mutable
*tree.ExternParamwrites racing across concurrently preparing LOAD workers.
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 standardmake cgolayout)
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—constructExternalstoresExtern: paraminto 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) carriesExtern: t.Es.Externinto every parallel worker dup created bynewParallelScope(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 structTwo consequences, both reproduced by the unit test below:
-
Data race / undefined behavior.
go test -racereports two DATA RACEs between concurrently preparing workers: a read (external.go:126) racing a previous write (external.go:130) onExtern.FileService, and a write/write pair onExtern.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-fileparallelLOAD with mcpu > 1) trips this. -
Last-writer-wins context binding. Deterministically, without -race: after worker 1 prepares, the ctx object stored in the shared
Extern.Ctxis worker 1's, not worker 0's — worker 0's earlier binding has been silently overwritten.Extern.Ctxis consumed on the reader side (for examplenewCSVParserFromReadersets the JSONLINE parser's cancellation context from it viaconfig.Context = extern.Ctx). Today the per-worker values coincide in the common local topology (workers derive from one statement context, andfileservice.WithSQLFileAccessreturns the parent unchanged when an identical policy is already attached), which is why nothing visibly breaks — but the shared overwrite is real,-racefails, 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
-
Save the test file below as
pkg/sql/colexec/external/loom_test_extern_ctx_race_test.goin a MatrixOne checkout. It uses only library packages (testutil,tree,plan,process) — no other test-file helpers needed. -
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 onExtern.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/- 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 viaconstructExternal(compile.go:4166); scopes run concurrently (MergeRun → ants goroutines, scope.go:610-628), each scope pipeline callingPreparein 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 runtimebuildLoadParallelRun→newParallelScope→dupOperatorRecursivelyWithContext→ vm.External case (operator.go:446-481) sharest.Es.Extern(operator.go:461) with every worker dup.
- Multi-file parallel LOAD:
- 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-operatorEs.Ctxalready 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
fix(external): isolate parallel worker runtime parameters (#31496)
XuPeng-SH commentedon Oct 28, 2026
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.Ariznawlll commentedon Oct 28, 2026
结论
测试通过。并行 LOAD 的 External worker 在准备和读取阶段不再共享、覆盖彼此的运行时上下文及 FileService;原共享模板保持不变。
关键证据
main@4808a7befd38cc877606f1c7ceda41ff387b212e,包含合入修复 #31496 的d3c8cf62fffc3f38e153d354af609e6fbd5729ab;macOS arm64、Go 1.27.1,隔离工作树执行组件原内部路径。-race重复 10 次均通过;完整pkg/sql/colexec/external包运行一次通过。原缺陷是组件内部共享状态和 race,已有 Go 回归直接覆盖,不用公共 SQL 伪装该 race。待解决点
无;本次独立验证为内部路径与组件包测试,未另行启动多进程生产规模 LOAD。