Repository navigation
Description
Branch Name
main
Commit ID
Other Environment Information
- Hardware parameters: Apple Silicon (arm64, macOS), Go unit test only
- OS type: darwin/arm64
- Go version: go1.27.1
- Reproduced as Go unit tests against
pkg/objectio/ioutil(Sinker + BatchFreeList); no server or mocked fileservice needed. This is exactly the CN insert / multi_update memory-pressure failure path: LOAD/INSERT spills staged blocks to storage, and the spill can fail on an S3 write error or an mpool allocation error under memory pressure.
Actual Behavior
Two deterministic manifestations of one broken ownership contract when a spill fails:
-
Sinker.WritefillscurrtoBlockMaxRows, callspushStaged(ctx, curr)— which transfers ownership by appendingcurrtostaged.inMemory(sinker.go:657) — and thentrySpillfails (storage write error here).trySpill's deferredcleanupInMemoryStaged()(sinker.go:751, 670-679) puts every staged batch, includingcurr, back into the buffer freelist.Writethen returns the error, and its own deferred handler (sinker.go:1031-1035) puts the SAMEcurrback AGAIN. The freelist (BatchFreeList.Putback, pkg/vm/engine/tae/containers/freelist.go:71-77) blindly appends, so the pool now contains one pointer twice. The freelist length after a single failed Write is 2 although only one buffer was ever created, and twoFetch()calls hand the SAME batch to two owners. -
Sinker.WriteOwnedreturns(owned bool, err error);owned=trueplus a non-nil error means "the transfer happened and the sinker owns the batch". On the direct-push path (sinker.go:1115-1116,return true, sinker.pushStaged(ctx, data)), a failed spill makescleanupInMemoryStagedput the CALLER-OWNED batch into the sinker's private freelist, yet the call returnsowned=true. The production callerpkg/sql/colexec/multi_update/s3writer_delegate.go:697-713keepsbats[i]and cleans it itself on the error path (it only nils the entry whenwriteErr == nil), so after the failure the same live batch is owned by the caller AND sits in the sinker's freelist:sinker.Close()/freelist.Close()willClean(mp)the caller's batch, and any fetch in between hands a caller-owned (eventually freed) batch to a new owner throughfetchBuffer(sinker.go:598-612).
Concrete observed values from the repro below (objectio.BlockMaxRows-row input, WithMemorySizeThreshold(1), a FileSinker that always fails):
observed freelist length after one failed Write: 2
observed: b1==b2? true, pool len before fetches: 2
Error: the failed Write returned its buffer to the freelist twice; the pool now hands the same batch to two owners
observed: transferred=true, fetched==owned? true, freelist len after fetch: 0
Error: after the failed WriteOwned the sinker's freelist holds the caller-owned batch
Both tests fail on current main reproducibly (run 3+ times, also with -race, fully deterministic).
Expected Behavior
The buffer freelist must never contain the same batch twice, and a sinker's freelist must never contain a batch owned by its caller:
- A failed
Sinker.Writemay return its buffer to the pool ONCE (or clean it), but must not double-put it: twoFetch()calls must return distinct batches. - A failed
Sinker.WriteOwnedmust not leave the caller's batch inside the sinker's private freelist: aFetch()after the failure must not return the batch passed in by the caller.
Basis: the freelist is documented as the sinker's private buffer pool ("It is released when the owning sinker calls Close", freelist.go:26-27); pushStaged is documented "takes the ownership of the bat" (sinker.go:649); WriteOwned's contract is "The caller transfers ownership: the sinker will clean the batch later" (sinker.go:1080-1083) — with owned=false on error meaning the caller retains the batch (see sinker.go:1107-1108, where exactly this contract is used by the production caller to decide whether it must clean).
Steps to Reproduce
Add pkg/objectio/ioutil/loom_test_sinker_ownership_test.go (contents in the repro field) and run:
go test ./pkg/objectio/ioutil/ -run 'TestLoomSinker' -count=1 -v
Both tests fail on main: each first logs the observed state (duplicate freelist entries / caller batch in pool) and then fails the NotSame assertion.
Additional information
Root cause — ownership transfer happens before the operation that can fail, so both sides believe they own the batch:
Write:pushStagedappendscurrtostaged.inMemory(sinker.go:657) and only then can fail viatrySpill(sinker.go:660). Every trySpill failure route (sort failure sinker.go:747-749, merge/sink/sync failures sinker.go:804-812, beforePersist hook failure) funnels into the deferredcleanupInMemoryStaged, whichputBackBuffers all staged batches (sinker.go:670-679) — including the just-pushedcurr.Write's owndefer(sinker.go:1031-1035) then putscurrback again becausecurrwas not set to nil on the failure return paths (sinker.go:1064-1065, 1073-1074 setcurr = nilonly on success).WriteOwned: the direct pathreturn true, sinker.pushStaged(ctx, data)(sinker.go:1115-1116) returnsowned=trueunconditionally while the failed spill's cleanup has already recycled the caller's batch into the sinker's freelist. (Theowned=true+errpair is also ambiguous in itself; the safest contract here is to returnowned=falsewhen the sinker did not durably accept the batch.)BatchFreeList.Putbackdoes not deduplicate (freelist.go:71-77) andfetchBuffer/fetch-buffers... FetchWithSchema(freelist.go:52-65) hands whatever is next in the pool. (NoteClean/CleanOnlyDataare nil-guarded, so today's sinkerCloseon a dangling pool does not panic — the harm is the duplicate/cross-owner buffer, not an immediate crash.)
Suggested minimal fix: make pushStaged (or trySpill) never recycle a failing batch twice — e.g. clear the caller's curr reference / set curr = nil before returning the trySpill error from pushStaged's call sites in Write, and make WriteOwned return owned=false when pushStaged fails (or pop the pushed batch back out before returning it to the caller). A stronger fix is an ownership linter in cleanupInMemoryStaged (panic on duplicate putback in debug builds).
Related but separate defects noticed in the same audit (NOT covered by this report, may deserve their own follow-up): fetchBuffer leaks the just-fetched batch when PreExtend fails (sinker.go:608-610); cleanupInMemoryStaged never decrements staged.inMemStats (sinker.go:670-679, counters drift upward after failed spills); failed statements drop staged.persisted/unpublished object names at Close/Reset without deletion (reported as separate already-open issue #29257).
duplicates_checked: 29257, 29260, 30125, 31166, 24129 (all different: object cleanup / metadata / serialization bounds)
Full reproduction, exactly as Loom ran it
Test file: pkg/objectio/ioutil/loom_test_sinker_ownership_test.go
```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 ioutil
import (
"context"
"testing"
"github.com/matrixorigin/matrixone/pkg/common/moerr"
"github.com/matrixorigin/matrixone/pkg/common/mpool"
"github.com/matrixorigin/matrixone/pkg/container/batch"
"github.com/matrixorigin/matrixone/pkg/container/types"
"github.com/matrixorigin/matrixone/pkg/container/vector"
"github.com/matrixorigin/matrixone/pkg/fileservice"
"github.com/matrixorigin/matrixone/pkg/objectio"
"github.com/matrixorigin/matrixone/pkg/vm/engine/tae/containers"
"github.com/stretchr/testify/require"
)
// loomFailFileSinker fails every Sink call, modeling a storage write error
// in the middle of a spill.
type loomFailFileSinker struct{}
func (loomFailFileSinker) Sink(context.Context, *batch.Batch) error {
return moerr.NewInternalErrorNoCtx("loom injected storage write failure")
}
func (loomFailFileSinker) Sync(context.Context) (*objectio.ObjectStats, error) {
return nil, nil
}
func (loomFailFileSinker) Reset() {}
func (loomFailFileSinker) Close() error { return nil }
func loomNewLoomFailFactory() FileSinkerFactory {
return func(*mpool.MPool, fileservice.FileService) FileSinker {
return loomFailFileSinker{}
}
}
// After a failed Write the freelist must hold at most the one buffer Write
// created; two Fetch() calls must return distinct batches.
func TestLoomSinkerFailedWritePutsBufferBackTwice(t *testing.T) {
attrs := []string{"a"}
typs := []types.Type{types.T_int32.ToType()}
mp, err := mpool.NewMPool("loom_sinker_test", 0, mpool.NoFixed)
require.NoError(t, err)
sinker := NewSinker(
-1, // no sort key, sync (non-pipeline) spill path
attrs, typs,
loomNewLoomFailFactory(),
mp, nil,
WithMemorySizeThreshold(1), // spill on every push
)
defer func() { require.NoError(t, sinker.Close()) }()
src := containers.MockBatch(typs, objectio.BlockMaxRows, 0, nil)
defer func() { src.Close() }()
err = sinker.Write(context.Background(), containers.ToCNBatch(src))
require.ErrorContains(t, err, "loom injected storage write failure")
if got := sinker.buf.buffers.Len(); got != 1 {
t.Logf("observed freelist length after one failed Write: %d", got)
}
b1 := sinker.buf.buffers.Fetch()
b2 := sinker.buf.buffers.Fetch()
defer func() {
b1.Clean(mp)
if b1 != b2 {
b2.Clean(mp)
}
}()
t.Logf("observed: b1==b2? %v", b1 == b2)
require.NotSame(t, b1, b2,
"the failed Write returned its buffer to the freelist twice; the pool now hands the same batch to two owners")
}
// After a failed WriteOwned the sinker's freelist must not contain the
// caller-owned batch.
func TestLoomSinkerFailedWriteOwnedStealsCallerBatch(t *testing.T) {
attrs := []string{"a"}
typs := []types.Type{types.T_int32.ToType()}
mp, err := mpool.NewMPool("loom_sinker_test_owned", 0, mpool.NoFixed)
require.NoError(t, err)
sinker := NewSinker(
-1,
attrs, typs,
loomNewLoomFailFactory(),
mp, nil,
WithMemorySizeThreshold(1),
)
defer func() { require.NoError(t, sinker.Close()) }()
owned := batch.NewWithSchema(false, attrs, typs)
defer func() { owned.Clean(mp) }()
for i := 0; i < objectio.BlockMaxRows; i++ {
require.NoError(t, vector.AppendFixed(owned.Vecs[0], int32(i), false, mp))
}
owned.SetRowCount(objectio.BlockMaxRows)
transferred, err := sinker.WriteOwned(context.Background(), owned)
require.ErrorContains(t, err, "loom injected storage write failure")
b := sinker.buf.buffers.Fetch()
defer func() {
if b != owned {
b.Clean(mp)
}
}()
t.Logf("observed: transferred=%v, fetched==owned? %v", transferred, b == owned)
require.NotSame(t, b, owned,
"after the failed WriteOwned the sinker's freelist holds the caller-owned batch; a later fetch hands the caller's (potentially freed) batch to a new owner")
}
```
Run (from repo root):
go test ./pkg/objectio/ioutil/ -run 'TestLoomSinker' -count=1 -v
Expected on a fixed build: both PASS.
Observed on 861a2c4cb6: both FAIL.
1) freelist len 2 after one failed Write, b1==b2 → NotSame fails
2) transferred=true and fetched==owned → NotSame fails
Deterministic; reproduced 3+ runs, also with -race.Found by Loom bug hunt (module: custom-de41a00730; tests: unit, white-box, concurrency; severity: S1)
Activity
MatrixAdventurer commentedon Oct 29, 2026
I reproduced both ownership problems and prepared the following patch against main at
7597f979e7904cf37ff077c94ffad191367d4d89.pushStagedtakes ownership before it can return a spill error. ClearWrite's local reference before each transfer, so its error cleanup cannot return the same batch to the pool a second time. Buffers that fail before transfer remain the local cleanup's responsibility.WriteOwnedmay returnowned=truewith an error after the batch was transferred and possibly recycled. Document that contract and make the multi-update caller clear its reference wheneverownedis true, before handling the error. Returningowned=falseafter this transfer would leave the caller believing it still owns a batch the sinker may already have recycled.WriteOwnedtransfer and copy fallback, cleanup accounting, and the actual multi-update writer with an injected persistence failure and a shared pool.Before the fix on
95341b4fffab4d080dca7e7335657d9e6ffd290a, all threeWritecases returned two pool entries instead of one, and the multi-update test observed that the caller had cleaned the transferred batch. With the patch applied to the newer base above, both full packages pass, including race detection on Linux/amd64 with Go 1.27.1:gofmt,git diff --check, and a cleangit apply --check --whitespace=erroralso passed. The failures were injected through a test FileSinker and a before-persist hook using the disk-backed test file service; this did not exercise a real S3 service.Save the complete diff below as a
.patchfile and apply it withgit apply:fix: preserve sinker batch ownership on write failures (#31647)
XuPeng-SH commentedon Oct 29, 2026
QA handoff for merged #31647 (
4343b4f921caf7ce45e3c703924ec29b8c512e61): this isolated QA run inspected the source and issue history but did not run current-head functional tests or live SQL because the existing resource guard left insufficient headroom. Please verify failed Write/WriteOwned ownership transfer, single recycling and MultiUpdate error paths. Author-reported PR tests are separate evidence and are not results of this QA run.Ariznawlll commentedon Oct 30, 2026
结论
测试通过。写入失败时,已转交的批次不再重复归还;
WriteOwned成功转交与转交前拒绝两种错误路径的调用方所有权均正确。关键证据
main@f6feb84343e4cb949b8ee8063853f86ac99801c6;修复 PR fix: preserve sinker batch ownership on write failures #31647 合并提交4343b4f921caf7ce45e3c703924ec29b8c512e61在该版本祖先链中。隔离源码目录,macOS arm64、Go 1.27.1;原问题为内部 Go 所有权路径,无需启动服务。-race -count=3全部通过。-race -count=3均通过。pkg/objectio/ioutil、pkg/sql/colexec/multi_update两个完整包分别以-race -count=1通过。待解决点