Merge remote-tracking branch 'pr/348' into trial9b

This commit is contained in:
pingqiu committed 2026-11-21 06:20:13 -08:00
commit 650024bdbd
7 files changed
+517

No files matched your search

@@ -0,0 +1,102 @@
package durable
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
// TestAttachReadinessWaitFailsFastOnTerminalState pins that an I/O waiting for
// chunk attachment returns at once, without another readiness wait, when an
// observer install failed, readiness was withdrawn or a fence is seen.
func TestAttachReadinessWaitFailsFastOnTerminalState(t *testing.T) {
for _, tc := range []struct {
name string
// before runs before the read; afterRefusal runs between the first gate
// refusal and the wait; whileWaiting runs once the read is waiting.
before func(t *testing.T, b *StorageBackend)
afterRefusal func(b *StorageBackend)
whileWaiting func(b *StorageBackend)
want error
wantWaits int32
}{
{
name: "observer install failed",
before: func(t *testing.T, b *StorageBackend) {
if err := b.SetWriteObserver(refusingRebaser{}); err == nil {
t.Fatal("refused observer install reported success")
}
},
want: frontend.ErrNotReady,
},
{
name: "fence seen after the attach refusal",
afterRefusal: func(b *StorageBackend) {
b.mu.Lock()
b.chunkFenced = func() bool { return true }
b.mu.Unlock()
},
want: frontend.ErrStalePrimary,
},
{
name: "readiness withdrawn while waiting",
whileWaiting: func(b *StorageBackend) { b.SetOperational(false, "host drain") },
want: frontend.ErrNotReady,
wantWaits: 1,
},
} {
t.Run(tc.name, func(t *testing.T) {
b := precopyTestBackend(newHeldReadStore())
b.setChunkAttachPending("attachment pending")
if tc.before != nil {
tc.before(t, b)
}
if tc.afterRefusal != nil {
b.testAfterAttachRefusal = func() { tc.afterRefusal(b) }
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var waits atomic.Int32
waiting, resume := make(chan struct{}), make(chan struct{})
b.testBeforeReadReadyWait = func() {
if waits.Add(1) == 1 && tc.whileWaiting != nil {
close(waiting)
<-resume
return
}
// A wait the rule forbids: end it now instead of after 3 s.
cancel()
}
result := make(chan error, 1)
go func() {
_, err := b.Read(ctx, 0, make([]byte, 4096))
result <- err
}()
if tc.whileWaiting != nil {
select {
case <-waiting:
case <-time.After(3 * time.Second):
t.Fatal("read never waited for attachment readiness")
}
tc.whileWaiting(b)
close(resume)
}
var err error
select {
case err = <-result:
case <-time.After(5 * time.Second):
t.Fatal("read did not return")
}
if got := waits.Load(); got != tc.wantWaits {
t.Fatalf("read waited %d times for readiness, want %d (err=%v)", got, tc.wantWaits, err)
}
if !errors.Is(err, tc.want) {
t.Fatalf("err=%v, want %v", err, tc.want)
}
})
}
}
@@ -0,0 +1,20 @@
package durable
import (
"errors"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
// TestPlainDetachStopRefusesClosedBackend pins that the plain-detach stop of a
// closed backend returns ErrBackendClosed instead of reporting a clean stop.
func TestPlainDetachStopRefusesClosedBackend(t *testing.T) {
b := precopyTestBackend(newHeldReadStore())
if err := b.Close(); err != nil {
t.Fatal(err)
}
if err := b.stopPlainDetachIfIdle(); !errors.Is(err, frontend.ErrBackendClosed) {
t.Fatalf("plain-detach stop of a closed backend: %v", err)
}
}
@@ -0,0 +1,162 @@
package durable
import (
"context"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// heldReadStore parks each ReadContext call on its LBA until the test releases
// that LBA, so every Read stays an admitted I/O for as long as the test needs.
type heldReadStore struct {
storage.LogicalStorage
entered chan uint32
release map[uint32]chan struct{}
}
func newHeldReadStore(lbas ...uint32) *heldReadStore {
s := &heldReadStore{entered: make(chan uint32, len(lbas)), release: make(map[uint32]chan struct{}, len(lbas))}
for _, lba := range lbas {
s.release[lba] = make(chan struct{})
}
return s
}
func (s *heldReadStore) ReadContext(ctx context.Context, lba uint32) ([]byte, error) {
s.entered <- lba
select {
case <-s.release[lba]:
return make([]byte, 4096), nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (s *heldReadStore) Read(lba uint32) ([]byte, error) {
return s.ReadContext(context.Background(), lba)
}
func (s *heldReadStore) NextLSN() uint64 { return 1 }
// precopyTestBackend is an operational backend over store with a matching
// healthy projection, so admission depends only on the state under test.
func precopyTestBackend(store storage.LogicalStorage) *StorageBackend {
id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1}
b := &StorageBackend{storage: store, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}}
b.SetOperational(true, "serving")
return b
}
// startHeldReads starts one Read per LBA and returns once every one of them is
// admitted and parked inside storage. Cleanup releases and joins them.
func startHeldReads(t *testing.T, b *StorageBackend, store *heldReadStore, lbas ...uint32) <-chan error {
t.Helper()
done := make(chan error, len(lbas))
for _, lba := range lbas {
go func(off int64) {
_, err := b.Read(context.Background(), off, make([]byte, 4096))
done <- err
}(int64(lba) * 4096)
}
t.Cleanup(func() {
for _, ch := range store.release {
select {
case <-ch:
default:
close(ch)
}
}
_ = b.Close()
})
for range lbas {
select {
case <-store.entered:
case <-time.After(3 * time.Second):
t.Fatal("read never reached storage")
}
}
return done
}
// installedPause waits until BeginPrecopyPause has installed its pause and
// returns the pause's drain channel.
func installedPause(t *testing.T, b *StorageBackend) <-chan struct{} {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for {
b.mu.Lock()
p := b.precopy
b.mu.Unlock()
if p != nil {
return p.drained
}
if time.Now().After(deadline) {
t.Fatal("pre-copy pause was never installed")
}
time.Sleep(time.Millisecond)
}
}
type pauseResult struct {
resume func()
err error
}
func beginPauseAsync(ctx context.Context, b *StorageBackend) <-chan pauseResult {
out := make(chan pauseResult, 1)
go func() {
resume, err := b.BeginPrecopyPause(ctx)
out <- pauseResult{resume, err}
}()
return out
}
// TestPrecopyDrainWaitsForEveryAdmittedIO pins that a pre-copy pause reports
// its drain done only after every I/O admitted before it has finished, not
// when the first of several completes.
func TestPrecopyDrainWaitsForEveryAdmittedIO(t *testing.T) {
store := newHeldReadStore(0, 1)
b := precopyTestBackend(store)
reads := startHeldReads(t, b, store, 0, 1)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pause := beginPauseAsync(ctx, b)
drained := installedPause(t, b)
close(store.release[0])
if err := <-reads; err != nil {
t.Fatalf("first admitted read: %v", err)
}
// The first read has returned, so its admission release has run.
select {
case <-drained:
t.Fatal("drain reported done while a second admitted I/O is still in flight")
default:
}
select {
case r := <-pause:
t.Fatalf("pause returned while a second admitted I/O is still in flight: err=%v", r.err)
default:
}
close(store.release[1])
if err := <-reads; err != nil {
t.Fatalf("second admitted read: %v", err)
}
select {
case r := <-pause:
if r.err != nil {
t.Fatalf("drain after the last admitted I/O: %v", r.err)
}
r.resume()
case <-time.After(3 * time.Second):
t.Fatal("drain not reported done after the last admitted I/O finished")
}
if _, err := b.Read(context.Background(), 0, nil); err != nil {
t.Fatalf("resume did not reopen admission: %v", err)
}
}
@@ -0,0 +1,80 @@
package durable
import (
"context"
"testing"
"time"
)
// TestPrecopyDrainEndsWithErrorOnReadinessLossOrClose pins that a pre-copy
// drain still pending when the backend loses readiness or is closed ends with
// an error and never reports a clean drain.
func TestPrecopyDrainEndsWithErrorOnReadinessLossOrClose(t *testing.T) {
for _, tc := range []struct {
name string
// bound is the drain's caller context, as the pre-copy caller gives it.
bound time.Duration
spoil func(b *StorageBackend)
}{
{"readiness lost", 3 * time.Second, func(b *StorageBackend) { b.SetOperational(false, "host drain") }},
// Close does not signal the drain; the waiter ends at its own bound.
{"closed", 200 * time.Millisecond, func(b *StorageBackend) { _ = b.Close() }},
} {
t.Run(tc.name, func(t *testing.T) {
store := newHeldReadStore(0)
b := precopyTestBackend(store)
reads := startHeldReads(t, b, store, 0)
ctx, cancel := context.WithTimeout(context.Background(), tc.bound)
defer cancel()
pause := beginPauseAsync(ctx, b)
installedPause(t, b)
tc.spoil(b)
close(store.release[0])
<-reads
select {
case r := <-pause:
if r.err == nil {
r.resume()
t.Fatal("drain reported clean after the backend became unusable")
}
case <-time.After(tc.bound + 3*time.Second):
t.Fatal("drain waiter did not end")
}
b.mu.Lock()
left := b.precopy
b.mu.Unlock()
if left != nil {
t.Fatal("failed drain left its pause installed")
}
})
}
}
// TestPrecopyFinalStopRefusedAfterReadinessLossOrClose pins that the final
// pre-copy stop refuses to commit a freeze when the backend lost readiness or
// was closed after the drain completed.
func TestPrecopyFinalStopRefusedAfterReadinessLossOrClose(t *testing.T) {
for _, tc := range []struct {
name string
spoil func(b *StorageBackend)
}{
{"readiness lost", func(b *StorageBackend) { b.SetOperational(false, "host drain") }},
{"closed", func(b *StorageBackend) { _ = b.Close() }},
} {
t.Run(tc.name, func(t *testing.T) {
b := precopyTestBackend(newHeldReadStore())
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
resume, err := b.BeginPrecopyPause(ctx)
if err != nil {
t.Fatal(err)
}
defer resume()
tc.spoil(b)
if b.TryStopIO("chunk pre-copy: final detached cut") {
t.Fatal("final stop committed a freeze on an unusable backend")
}
})
}
}
@@ -0,0 +1,81 @@
package durable
import (
"context"
"errors"
"testing"
"time"
)
type refusingRebaser struct{}
func (refusingRebaser) Observe(context.Context, uint32, uint64, []byte) error { return nil }
func (refusingRebaser) Sync(context.Context, uint64) error { return nil }
func (refusingRebaser) RebaseShipLSN(uint64) error {
return errors.New("injected: ship LSN cannot follow the store")
}
// TestPrecopyPauseRefusedOnUnusableBackend pins that a pre-copy pause never
// begins on a backend that is closed, not operational, has a failed observer
// install, or already has a pause installed.
func TestPrecopyPauseRefusedOnUnusableBackend(t *testing.T) {
for _, tc := range []struct {
name string
spoil func(t *testing.T, b *StorageBackend)
}{
{"observer install failed", func(t *testing.T, b *StorageBackend) {
if err := b.SetWriteObserver(refusingRebaser{}); err == nil {
t.Fatal("refused observer install reported success")
}
}},
{"closed", func(t *testing.T, b *StorageBackend) { _ = b.Close() }},
{"not operational", func(t *testing.T, b *StorageBackend) { b.SetOperational(false, "host drain") }},
} {
t.Run(tc.name, func(t *testing.T) {
b := precopyTestBackend(newHeldReadStore())
tc.spoil(t, b)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
resume, err := b.BeginPrecopyPause(ctx)
if err == nil {
resume()
t.Fatal("pre-copy pause began on an unusable backend")
}
b.mu.Lock()
left := b.precopy
b.mu.Unlock()
if left != nil {
t.Fatal("refused pause left a pause installed")
}
})
}
t.Run("already paused", func(t *testing.T) {
b := precopyTestBackend(newHeldReadStore())
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
resume, err := b.BeginPrecopyPause(ctx)
if err != nil {
t.Fatal(err)
}
defer resume()
b.mu.Lock()
first := b.precopy
b.mu.Unlock()
second, err := b.BeginPrecopyPause(ctx)
if err == nil {
second()
t.Fatal("second pre-copy pause began while one is installed")
}
b.mu.Lock()
current := b.precopy
b.mu.Unlock()
if current != first {
t.Fatal("refused second pause replaced the installed pause")
}
resume()
if _, err := b.Read(context.Background(), 0, nil); err != nil {
t.Fatalf("resume of the first pause did not reopen admission: %v", err)
}
})
}
@@ -0,0 +1,47 @@
package storage
import (
"errors"
"testing"
)
// TestPrecopyRoundLoopRetriesOnlyNamedErrors pins that a failed rolling
// pre-copy round starts another round only after a COW abort, an unavailable
// remote or a HEAD precondition failure; any other error ends the loop at once.
func TestPrecopyRoundLoopRetriesOnlyNamedErrors(t *testing.T) {
errNotPrimary := errors.New("test: not primary")
for _, tc := range []struct {
name string
first error
rounds int
}{
{"other error", errNotPrimary, 1},
{"COW aborted", errCutCOWAborted, 2},
{"remote unavailable", errChunkRemoteUnavailable, 2},
{"HEAD precondition", errChunkHeadPrecondition, 2},
} {
t.Run(tc.name, func(t *testing.T) {
_, _, l, _ := precopyLayer(t, 1024, 0)
// Every round fails at capture admission: the first with the error
// under test, any later one with an error that is never retried.
calls := 0
l.cfg.CaptureAllowed = func() error {
calls++
if calls == 1 {
return tc.first
}
return errNotPrimary
}
r, err := l.PrecopyDetach(ctTimeout(t), func() bool {
t.Error("refused rounds reached the final stop")
return true
})
if !errors.Is(err, errNotPrimary) {
t.Fatalf("err=%v, want the non-retried refusal", err)
}
if calls != tc.rounds || len(r.Precopy.Rounds) != tc.rounds {
t.Fatalf("rounds: admission calls=%d reported=%d, want %d", calls, len(r.Precopy.Rounds), tc.rounds)
}
})
}
}
@@ -0,0 +1,25 @@
package storage
import (
"testing"
"time"
)
// TestPrecopySampleHistoryKeepsNewest32 pins that the pre-copy cost sample
// history is bounded at 32 entries and keeps the newest ones.
func TestPrecopySampleHistoryKeepsNewest32(t *testing.T) {
l := &chunkLayerImpl{}
const taken = 40
for i := 1; i <= taken; i++ {
// The fixed cost carries the sample's order.
l.samplePrecopy(chunkCutStats{CASNs: 1}, int64(i))
}
if len(l.precopySamples) != 32 {
t.Fatalf("sample history holds %d entries, want 32", len(l.precopySamples))
}
for j, s := range l.precopySamples {
if want := time.Duration(taken - 32 + 1 + j); s.fixed != want {
t.Fatalf("sample %d has fixed=%s, want %s (newest 32 kept in order)", j, s.fixed, want)
}
}
}