Skip to content

[Bug]: failed Sinker.Write returns its buffer to the freelist twice; failed WriteOwned traps the caller's batch #31283

Closed

Description

@iamlinjunhong

Branch Name

main

Commit ID

861a2c4

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:

  1. Sinker.Write fills curr to BlockMaxRows, calls pushStaged(ctx, curr) — which transfers ownership by appending curr to staged.inMemory (sinker.go:657) — and then trySpill fails (storage write error here). trySpill's deferred cleanupInMemoryStaged() (sinker.go:751, 670-679) puts every staged batch, including curr, back into the buffer freelist. Write then returns the error, and its own deferred handler (sinker.go:1031-1035) puts the SAME curr back 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 two Fetch() calls hand the SAME batch to two owners.

  2. Sinker.WriteOwned returns (owned bool, err error); owned=true plus 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 makes cleanupInMemoryStaged put the CALLER-OWNED batch into the sinker's private freelist, yet the call returns owned=true. The production caller pkg/sql/colexec/multi_update/s3writer_delegate.go:697-713 keeps bats[i] and cleans it itself on the error path (it only nils the entry when writeErr == 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() will Clean(mp) the caller's batch, and any fetch in between hands a caller-owned (eventually freed) batch to a new owner through fetchBuffer (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.Write may return its buffer to the pool ONCE (or clean it), but must not double-put it: two Fetch() calls must return distinct batches.
  • A failed Sinker.WriteOwned must not leave the caller's batch inside the sinker's private freelist: a Fetch() 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: pushStaged appends curr to staged.inMemory (sinker.go:657) and only then can fail via trySpill (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 deferred cleanupInMemoryStaged, which putBackBuffers all staged batches (sinker.go:670-679) — including the just-pushed curr. Write's own defer (sinker.go:1031-1035) then puts curr back again because curr was not set to nil on the failure return paths (sinker.go:1064-1065, 1073-1074 set curr = nil only on success).
  • WriteOwned: the direct path return true, sinker.pushStaged(ctx, data) (sinker.go:1115-1116) returns owned=true unconditionally while the failed spill's cleanup has already recycled the caller's batch into the sinker's freelist. (The owned=true+err pair is also ambiguous in itself; the safest contract here is to return owned=false when the sinker did not durably accept the batch.)
  • BatchFreeList.Putback does not deduplicate (freelist.go:71-77) and fetchBuffer/fetch-buffers... FetchWithSchema (freelist.go:52-65) hands whatever is next in the pool. (Note Clean/CleanOnlyData are nil-guarded, so today's sinker Close on 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

  1. added
    kind/bug
    severity/s1
    on Oct 26, 2026
  2. MatrixAdventurer commented on Oct 29, 2026

    @MatrixAdventurer
    Contributor

    I reproduced both ownership problems and prepared the following patch against main at 7597f979e7904cf37ff077c94ffad191367d4d89.

    • pushStaged takes ownership before it can return a spill error. Clear Write'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.
    • A direct WriteOwned may return owned=true with an error after the batch was transferred and possibly recycled. Document that contract and make the multi-update caller clear its reference whenever owned is true, before handling the error. Returning owned=false after this transfer would leave the caller believing it still owns a batch the sinker may already have recycled.
    • The regression tests cover full, partial, and previously staged full batches, both WriteOwned transfer 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 three Write cases 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:

    go test -p 3 ./pkg/objectio/ioutil ./pkg/sql/colexec/multi_update -count=1 -timeout=5m
    go test -race -p 3 ./pkg/objectio/ioutil ./pkg/sql/colexec/multi_update -count=1 -timeout=10m

    gofmt, git diff --check, and a clean git apply --check --whitespace=error also 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 .patch file and apply it with git apply:

    diff --git a/pkg/objectio/ioutil/sinker.go b/pkg/objectio/ioutil/sinker.go
    index 31b4d28..b994846 100644
    --- a/pkg/objectio/ioutil/sinker.go
    +++ b/pkg/objectio/ioutil/sinker.go
    @@ -1034,6 +1034,12 @@ func (sinker *Sinker) Write(
     			sinker.putBackBuffer(curr)
     		}
     	}()
    +	// pushStaged takes ownership even if the ensuing spill fails.
    +	pushCurr := func() error {
    +		staged := curr
    +		curr = nil
    +		return sinker.pushStaged(ctx, staged)
    +	}
     	offset := 0
     	left := data.RowCount()
     	for left > 0 {
    @@ -1044,7 +1050,7 @@ func (sinker *Sinker) Write(
     					return
     				}
     			} else if curr.RowCount() == objectio.BlockMaxRows {
    -				if err = sinker.pushStaged(ctx, curr); err != nil {
    +				if err = pushCurr(); err != nil {
     					return
     				}
     				if curr, err = sinker.fetchBuffer(); err != nil {
    @@ -1062,16 +1068,15 @@ func (sinker *Sinker) Write(
     			return
     		}
     		if curr.RowCount() == objectio.BlockMaxRows {
    -			if err = sinker.pushStaged(ctx, curr); err != nil {
    +			if err = pushCurr(); err != nil {
     				return
     			}
    -			curr = nil
     		}
     		left -= toAdd
     		offset += toAdd
     	}
     	if curr != nil && curr.RowCount() > 0 {
    -		if err = sinker.pushStaged(ctx, curr); err != nil {
    +		if err = pushCurr(); err != nil {
     			return
     		}
     	}
    @@ -1079,7 +1084,8 @@ func (sinker *Sinker) Write(
     }
     
     // WriteOwned stages a full-block batch directly without copying. The caller
    -// transfers ownership: the sinker will clean the batch later.
    +// transfers ownership: the sinker will clean the batch later. When owned is
    +// true, ownership has transferred even if the returned error is non-nil.
     // If the batch is not exactly BlockMaxRows or there is a partially-filled
     // staged buffer, falls back to Write (which copies).
     func (sinker *Sinker) WriteOwned(
    diff --git a/pkg/sql/colexec/multi_update/s3writer_delegate.go b/pkg/sql/colexec/multi_update/s3writer_delegate.go
    index 65f2229..042a194 100644
    --- a/pkg/sql/colexec/multi_update/s3writer_delegate.go
    +++ b/pkg/sql/colexec/multi_update/s3writer_delegate.go
    @@ -698,12 +698,14 @@ func (writer *s3WriterDelegate) sortAndSyncOneTable(
     			owned, writeErr := process.MeasureFilesystemWait(analyzer, func() (bool, error) {
     				return s3Writer.WriteOwned(writeCtx, bats[i])
     			})
    +			if owned {
    +				bats[i] = nil
    +			}
     			if writeErr != nil {
     				err = writeErr
     				return
     			}
     			if owned {
    -				bats[i] = nil
     				continue
     			}
     			// WriteOwned returned false: data was already copied inside
    diff --git a/pkg/objectio/ioutil/sinker_write_ownership_test.go b/pkg/objectio/ioutil/sinker_write_ownership_test.go
    new file mode 100644
    index 0000000..f2876dd
    --- /dev/null
    +++ b/pkg/objectio/ioutil/sinker_write_ownership_test.go
    @@ -0,0 +1,131 @@
    +// 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"
    +	"errors"
    +	"testing"
    +
    +	"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"
    +)
    +
    +type ownershipFailSinker struct{ err error }
    +
    +func (f ownershipFailSinker) Sink(context.Context, *batch.Batch) error          { return f.err }
    +func (ownershipFailSinker) Sync(context.Context) (*objectio.ObjectStats, error) { return nil, nil }
    +func (ownershipFailSinker) Reset()                                              {}
    +func (ownershipFailSinker) Close() error                                        { return nil }
    +
    +func ownershipBatch(t *testing.T, mp *mpool.MPool, rows int) *batch.Batch {
    +	t.Helper()
    +	bat := batch.NewWithSchema(false, []string{"v"}, []types.Type{types.T_int32.ToType()})
    +	require.NoError(t, vector.AppendFixedList(bat.Vecs[0], make([]int32, rows), nil, mp))
    +	bat.SetRowCount(rows)
    +	return bat
    +}
    +
    +func TestSinkerFailedWriteTransfersBufferOnce(t *testing.T) {
    +	for _, tc := range []struct {
    +		name       string
    +		rows       int
    +		stagedFull bool
    +	}{
    +		{name: "full", rows: objectio.BlockMaxRows},
    +		{name: "partial", rows: 5},
    +		{name: "previously-staged-full", rows: 5, stagedFull: true},
    +	} {
    +		t.Run(tc.name, func(t *testing.T) {
    +			ctx := context.Background()
    +			mp := mpool.MustNewZero()
    +			attrs, typs := []string{"v"}, []types.Type{types.T_int32.ToType()}
    +			pool := containers.NewBatchFreeList(attrs, typs, false)
    +			injected := errors.New("injected spill failure")
    +			factory := func(*mpool.MPool, fileservice.FileService) FileSinker {
    +				return ownershipFailSinker{err: injected}
    +			}
    +			sinker := NewSinker(-1, attrs, typs, factory, mp, nil,
    +				WithMemorySizeThreshold(1<<30), WithBuffer(pool, false))
    +			t.Cleanup(func() {
    +				require.NoError(t, sinker.Close())
    +				pool.Close(mp)
    +				require.Zero(t, mp.CurrNB())
    +			})
    +			if tc.stagedFull {
    +				staged := ownershipBatch(t, mp, objectio.BlockMaxRows)
    +				owned, err := sinker.WriteOwned(ctx, staged)
    +				require.NoError(t, err)
    +				require.True(t, owned)
    +			}
    +			sinker.staged.memorySizeThreshold = 1
    +			input := ownershipBatch(t, mp, tc.rows)
    +			defer input.Clean(mp)
    +			require.ErrorIs(t, sinker.Write(ctx, input), injected)
    +			require.Equal(t, 1, pool.Len(), "the transferred batch must be recycled once")
    +			first, second := pool.Fetch(), pool.Fetch()
    +			defer first.Clean(mp)
    +			defer second.Clean(mp)
    +			require.NotSame(t, first, second, "independent fetches must not share a batch")
    +		})
    +	}
    +}
    +
    +func TestSinkerFailedWriteOwnedReportsTransferredOwnership(t *testing.T) {
    +	for _, tc := range []struct {
    +		name        string
    +		rows        int
    +		transferred bool
    +	}{
    +		{name: "full", rows: objectio.BlockMaxRows, transferred: true},
    +		{name: "partial-copy", rows: 5, transferred: false},
    +	} {
    +		t.Run(tc.name, func(t *testing.T) {
    +			mp := mpool.MustNewZero()
    +			attrs, typs := []string{"v"}, []types.Type{types.T_int32.ToType()}
    +			pool := containers.NewBatchFreeList(attrs, typs, false)
    +			injected := errors.New("injected spill failure")
    +			factory := func(*mpool.MPool, fileservice.FileService) FileSinker {
    +				return ownershipFailSinker{err: injected}
    +			}
    +			sinker := NewSinker(-1, attrs, typs, factory, mp, nil,
    +				WithMemorySizeThreshold(1), WithBuffer(pool, false))
    +			t.Cleanup(func() {
    +				require.NoError(t, sinker.Close())
    +				pool.Close(mp)
    +				require.Zero(t, mp.CurrNB())
    +			})
    +			input := ownershipBatch(t, mp, tc.rows)
    +			owned, err := sinker.WriteOwned(context.Background(), input)
    +			require.ErrorIs(t, err, injected)
    +			require.Equal(t, tc.transferred, owned)
    +			if owned {
    +				require.Equal(t, 1, pool.Len())
    +				recycled := pool.Fetch()
    +				defer recycled.Clean(mp)
    +				require.Same(t, input, recycled)
    +			} else {
    +				defer input.Clean(mp)
    +				require.Equal(t, tc.rows, input.RowCount())
    +			}
    +		})
    +	}
    +}
    diff --git a/pkg/sql/colexec/multi_update/s3writer_ownership_error_test.go b/pkg/sql/colexec/multi_update/s3writer_ownership_error_test.go
    new file mode 100644
    index 0000000..2b37657
    --- /dev/null
    +++ b/pkg/sql/colexec/multi_update/s3writer_ownership_error_test.go
    @@ -0,0 +1,94 @@
    +// 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 multi_update
    +
    +import (
    +	"context"
    +	"errors"
    +	"strings"
    +	"testing"
    +
    +	"github.com/matrixorigin/matrixone/pkg/container/types"
    +	"github.com/matrixorigin/matrixone/pkg/container/vector"
    +	"github.com/matrixorigin/matrixone/pkg/objectio"
    +	"github.com/matrixorigin/matrixone/pkg/objectio/ioutil"
    +	"github.com/matrixorigin/matrixone/pkg/sql/colexec"
    +	"github.com/matrixorigin/matrixone/pkg/util/fault"
    +	"github.com/matrixorigin/matrixone/pkg/vm/engine/tae/containers"
    +	"github.com/matrixorigin/matrixone/pkg/vm/process"
    +	"github.com/stretchr/testify/require"
    +)
    +
    +func TestSortAndSyncOneTableKeepsTransferredBatchOnWriteError(t *testing.T) {
    +	ctx := context.Background()
    +	enabledHere := fault.Enable()
    +	t.Cleanup(func() {
    +		_, _ = fault.RemoveFaultPoint(ctx, objectio.FJ_CNFlushSmallObjs)
    +		if enabledHere {
    +			fault.Disable()
    +		}
    +	})
    +	require.NoError(t, fault.AddFaultPoint(ctx, objectio.FJ_CNFlushSmallObjs,
    +		":::", "ECHO", 0, "test", false))
    +
    +	_, _, proc := prepareTestCtx(t, true)
    +	defer proc.Free()
    +	_, tableDef := getTestMainTable()
    +	update := &MultiUpdate{MultiUpdateCtx: []*MultiUpdateCtx{{TableDef: tableDef, InsertCols: []int{0, 1, 2, 3}}}}
    +	update.resetMultiUpdateCtxs()
    +	writer, err := newS3Writer(proc.GetService(), update)
    +	require.NoError(t, err)
    +	defer func() { require.NoError(t, writer.free(proc)) }()
    +
    +	// A full block larger than the injected threshold spills inside WriteOwned.
    +	bats, _ := prepareTestInsertBatchs(proc.Mp(), 2, objectio.BlockMaxRows, false, false)
    +	for _, bat := range bats {
    +		defer bat.Clean(proc.Mp())
    +	}
    +	input := bats[0]
    +	input.Vecs[1].Free(proc.Mp())
    +	input.Vecs[1] = vector.NewVec(types.T_varchar.ToType())
    +	value := []byte(strings.Repeat("v", 128))
    +	for i := 0; i < objectio.BlockMaxRows; i++ {
    +		require.NoError(t, vector.AppendBytes(input.Vecs[1], value, false, proc.Mp()))
    +	}
    +	require.Greater(t, input.Size(), colexec.FaultInjectedS3Threshold)
    +
    +	pool := containers.NewBatchFreeList(nil, nil, true)
    +	defer pool.Close(proc.Mp())
    +	injected := errors.New("injected persist failure")
    +	failedDuringWrite := false
    +	err = writer.sortAndSyncOneTable(proc, tableDef,
    +		process.NewAnalyzer(0, false, false, "ownership-error"), 0, false, bats, true,
    +		ioutil.WithBuffer(pool, false),
    +		ioutil.WithBeforePersist(func(context.Context, string) error {
    +			failedDuringWrite = bats[0] != nil
    +			return injected
    +		}),
    +	)
    +	require.ErrorIs(t, err, injected)
    +	require.True(t, failedDuringWrite, "failure must occur before WriteOwned returns")
    +	require.Nil(t, bats[0])
    +	require.NotNil(t, input.Vecs, "caller must not clean a batch already transferred to the sinker")
    +	var found bool
    +	for pool.Len() > 0 {
    +		bat := pool.Fetch()
    +		if bat == input {
    +			found = true
    +		}
    +		defer bat.Clean(proc.Mp())
    +	}
    +	require.True(t, found, "the transferred batch should remain reusable in the shared pool")
    +}
  3. added a commit that references this issue on Oct 29, 2026
    4343b4f
  4. XuPeng-SH commented on Oct 29, 2026

    @XuPeng-SH
    Contributor

    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.

  5. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    Collaborator

    结论

    测试通过。写入失败时,已转交的批次不再重复归还;WriteOwned 成功转交与转交前拒绝两种错误路径的调用方所有权均正确。

    关键证据

    • 版本:官方 main@f6feb84343e4cb949b8ee8063853f86ac99801c6;修复 PR fix: preserve sinker batch ownership on write failures #31647 合并提交 4343b4f921caf7ce45e3c703924ec29b8c512e61 在该版本祖先链中。隔离源码目录,macOS arm64、Go 1.27.1;原问题为内部 Go 所有权路径,无需启动服务。
    • Sinker 回归 注入 sink 写入失败,覆盖部分块、完整块和已有完整块三个场景;检查 staged 清空、空闲池仅归还一次,连续取出的批次不是同一对象。-race -count=3 全部通过。
    • MultiUpdate 调用方回归 使用内存文件服务与进程内模拟写入错误,分别验证转交后失败时调用方释放引用,以及转交前参数错误时保留所有权并最终清理;两项 -race -count=3 均通过。pkg/objectio/ioutil、pkg/sql/colexec/multi_update 两个完整包分别以 -race -count=1 通过。

    待解决点

    • 现有已合入 Go UT/race 直接覆盖本问题的内部故障及调用方路径,因此未新增 MOTR;未运行完整 MatrixOne 服务或整个项目 CI。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s1

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions