Merge pull request #238 from seaweedfs/fix/cut-single-upload-retry

storage: retry individual cut uploads within a shared deadline
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-19 05:19:26 -08:00
commit be320d34c5
7 files changed
+624 -15

No files matched your search

+2 -2
View File
@@ -1012,7 +1012,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error {
u := uploads[i]
return l.remote.Put(ctx, u.key, u.c.data)
return l.putCaptured(ctx, u.key, u.c.data)
}); err != nil {
l.abortCut(all)
l.dropIntents(ctx, intents)
@@ -1731,7 +1731,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint
intents = append(intents, id)
if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error {
u := uploads[i]
return l.remote.Put(ctx, u.key, u.data)
return l.putCaptured(ctx, u.key, u.data)
}); err != nil {
return nil, intents, fmt.Errorf("storage: capture stage upload: %w: %w", errChunkRemoteUnavailable, err)
}
@@ -1,10 +1,52 @@
package storage
import (
"bytes"
"context"
"errors"
"sync"
"time"
)
// putCaptured retries one immutable object, never a whole batch or HEAD CAS.
// A lost binding reply can turn the next attempt into KeyExists: only exact
// bytes read from that binding prove completion; a collision is terminal.
// Bound attempts per object, without imposing a deadline on legitimate work
// across the whole cut. All attempts still obey the caller's context.
func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byte) error {
backoff := 100 * time.Millisecond
var lastErr error
for attempt := 1; ; attempt++ {
if err := ctx.Err(); err != nil {
return errors.Join(lastErr, err)
}
err := l.remote.Put(ctx, key, data)
if err == nil {
return nil
}
lastErr = err
// Resolve a possibly committed binding before replaying the Put.
got, readErr := l.remote.Get(ctx, key)
if readErr == nil {
if bytes.Equal(got, data) {
return nil
}
return errChunkKeyExists
}
if attempt == 3 {
return lastErr
}
timer := time.NewTimer(backoff)
select {
case <-ctx.Done():
timer.Stop()
return errors.Join(lastErr, ctx.Err())
case <-timer.C:
}
backoff = min(2*time.Second, 2*backoff)
}
}
// uploadBatch owns and joins all Put calls before its caller settles intents.
// No storage/publication lock is acquired by workers. Cancellation stops new
// admission; a remote ignoring cancellation remains joined, never declared done.
@@ -0,0 +1,88 @@
package storage
import (
"context"
"errors"
"testing"
"time"
)
func TestChunkUploadOutageSettlesBeforeQueuedBASE(t *testing.T) {
s, f, l := mappedBASELayerV3(t)
if _, err := s.Write(5, blk(0x31)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
entered, release := holdPuts(t, f)
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
cutDone := make(chan error, 1)
cutJoined := make(chan struct{})
var baseJoined chan struct{}
t.Cleanup(func() {
cancel()
release()
select {
case <-cutJoined:
case <-time.After(5 * time.Second):
t.Error("cut not joined")
}
if baseJoined != nil {
select {
case <-baseJoined:
case <-time.After(5 * time.Second):
t.Error("BASE worker not joined")
}
}
})
start := time.Now()
go func() { defer close(cutJoined); _, err := l.Cut(ctx); cutDone <- err }()
waitKey(t, entered, "cooperative cut upload")
attempted := make(chan struct{})
l.testBaseTransitionBeforeLock = func() { close(attempted) }
baseJoined = make(chan struct{})
type result struct {
h InstallHandle
err error
}
baseDone := make(chan result, 1)
go func() { defer close(baseJoined); h, err := s.BeginBaseInstall(7, idA); baseDone <- result{h, err} }()
select {
case <-attempted:
case <-time.After(5 * time.Second):
t.Fatal("BASE did not reach cut drain")
}
select {
case err := <-cutDone:
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("cut deadline: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("cooperative cut not settled")
}
var got result
select {
case got = <-baseDone:
case <-time.After(5 * time.Second):
t.Fatal("BASE did not proceed after cut settlement")
}
if got.err != nil {
t.Fatal(got.err)
}
if time.Since(start) >= 5*time.Second {
t.Fatal("single queued BASE exceeded sub-5s target")
}
if len(f.installedHeads()) != 0 {
t.Fatal("failed upload published HEAD")
}
select {
case <-baseJoined:
case <-time.After(5 * time.Second):
t.Fatal("BASE begin worker not joined")
}
l.testBaseTransitionBeforeLock = nil
if err := got.h.MarkBaseComplete(); err != nil {
t.Fatal(err)
}
}
@@ -0,0 +1,150 @@
package storage
import (
"bytes"
"context"
"errors"
"sync"
"testing"
"time"
)
type cutBudgetRemote struct {
*fakeChunkRemote
mu sync.Mutex
keys []string
deadlines []time.Time
held chan struct{}
once sync.Once
healthy bool
}
func (r *cutBudgetRemote) Put(ctx context.Context, key string, data []byte) error {
r.mu.Lock()
if r.healthy {
r.mu.Unlock()
return r.fakeChunkRemote.Put(ctx, key, data)
}
r.keys = append(r.keys, key)
d, ok := ctx.Deadline()
if !ok {
d = time.Time{}
}
r.deadlines = append(r.deadlines, d)
n := len(r.keys)
r.mu.Unlock()
if n >= 3 {
r.once.Do(func() { close(r.held) })
<-ctx.Done()
return ctx.Err()
}
return r.fakeChunkRemote.Put(ctx, key, data)
}
func TestChunkCutCallerBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
r := &cutBudgetRemote{fakeChunkRemote: f, held: make(chan struct{})}
cfg := ctConfig(1)
cfg.FreshFromHead = true
cfg.BarrierBound = 1
cfg.UploadConcurrency = 2
l := mustAttach(t, s, r, cfg).(*chunkLayerImpl)
for i := 0; i < 3; i++ {
if _, err := s.Write(uint32(i*ctChunkBlocks), makeBlock(ctBlockSize, byte(0x41+i))); err != nil {
t.Fatal(err)
}
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
done := make(chan error, 1)
joined := make(chan struct{})
t.Cleanup(func() {
cancel()
select {
case <-joined:
case <-time.After(5 * time.Second):
t.Error("cut worker not joined")
}
})
start := time.Now()
go func() { defer close(joined); _, err := l.Cut(ctx); done <- err }()
select {
case <-r.held:
case <-time.After(5 * time.Second):
t.Fatal("did not reach staged then final upload")
}
r.mu.Lock()
deadlines := append([]time.Time(nil), r.deadlines...)
r.mu.Unlock()
if len(deadlines) != 3 {
t.Fatalf("want two staged and one final upload: %v", deadlines)
}
wantDeadline, _ := ctx.Deadline()
if !deadlines[0].Equal(wantDeadline) {
t.Fatalf("cut replaced caller's deadline: %v, want %v", deadlines[0], wantDeadline)
}
for _, d := range deadlines {
if !d.Equal(deadlines[0]) {
t.Fatal("stage/worker received a reset budget")
}
}
writeDone := make(chan error, 1)
writeJoined := make(chan struct{})
t.Cleanup(func() {
cancel()
select {
case <-writeJoined:
case <-time.After(5 * time.Second):
t.Error("ordinary write not joined")
}
})
go func() {
defer close(writeJoined)
_, err := s.Write(3*ctChunkBlocks, makeBlock(ctBlockSize, 0x44))
if err == nil {
_, err = s.Sync()
}
writeDone <- err
}()
select {
case err := <-writeDone:
if err != nil {
t.Fatal(err)
}
case err := <-done:
t.Fatalf("ordinary write waited for remote cut settlement: %v", err)
case <-time.After(5 * time.Second):
t.Fatal("ordinary write blocked")
}
select {
case err := <-done:
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("lost caller deadline: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("cooperative cut did not settle")
}
if time.Since(start) >= 5*time.Second {
t.Fatal("cut exceeded sub-5s target")
}
if len(f.installedHeads()) != 0 {
t.Fatal("outage published HEAD")
}
r.mu.Lock()
r.healthy = true
r.mu.Unlock()
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
heads := f.installedHeads()
if len(heads) != 1 {
t.Fatal("retry did not publish exactly once")
}
want := make([]byte, ctNumBlocks*ctBlockSize)
for i := 0; i < 4; i++ {
copy(want[i*ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, byte(0x41+i)))
}
if !bytes.Equal(f.imageOf(t, heads[0]), want) {
t.Fatal("shared-budget abort lost pending/concurrent bytes")
}
}
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
@@ -105,22 +106,32 @@ type unjoinedUploadRemote struct {
second chan struct{}
failed chan struct{}
release chan struct{}
settled chan struct{}
}
func (r *unjoinedUploadRemote) Put(ctx context.Context, key string, data []byte) error {
if r.calls.Add(1) == 1 {
<-r.second
switch r.calls.Add(1) {
case 1:
select {
case <-r.second:
case <-ctx.Done():
return ctx.Err()
}
close(r.failed)
return errFakeRemoteDown
case 2:
close(r.second)
defer close(r.settled)
default:
return errFakeRemoteDown
}
close(r.second)
<-r.release
return r.fakeChunkRemote.Put(context.Background(), key, data)
}
func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
r := &unjoinedUploadRemote{fakeChunkRemote: f, second: make(chan struct{}), failed: make(chan struct{}), release: make(chan struct{})}
r := &unjoinedUploadRemote{fakeChunkRemote: f, second: make(chan struct{}), failed: make(chan struct{}), release: make(chan struct{}), settled: make(chan struct{})}
cfg := ctConfig(1)
cfg.FreshFromHead = true
cfg.UploadConcurrency = 2
@@ -128,29 +139,52 @@ func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) {
w := newWriteLog()
w.write(t, s, 0, 0x21)
w.write(t, s, ctChunkBlocks, 0x22)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { _, err := l.Cut(context.Background()); done <- err }()
joined := make(chan struct{})
var once sync.Once
release := func() { once.Do(func() { close(r.release) }) }
t.Cleanup(func() {
cancel()
release()
select {
case <-joined:
case <-time.After(5 * time.Second):
t.Error("cut worker not joined")
}
select {
case <-r.second:
select {
case <-r.settled:
case <-time.After(5 * time.Second):
t.Error("owned upload not joined")
}
default:
}
})
go func() { defer close(joined); _, err := l.Cut(ctx); done <- err }()
select {
case <-r.failed:
cancel() // retries are now allowed; terminate this cut explicitly
case <-time.After(time.Second):
close(r.release)
<-done
t.Fatal("uploads did not overlap")
}
select {
case err := <-done:
close(r.release)
t.Fatalf("returned with owned upload still active: %v", err)
case <-time.After(20 * time.Millisecond):
}
if len(liveIntents(t, f)) == 0 {
close(r.release)
<-done
t.Fatal("intent removed before join")
}
close(r.release)
if err := <-done; !errors.Is(err, errFakeRemoteDown) {
t.Fatalf("lost upload failure: %v", err)
release()
select {
case err := <-done:
if !errors.Is(err, errFakeRemoteDown) {
t.Fatalf("lost upload failure: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("cut completion not joined")
}
if f.stats().cas != 0 {
t.Fatal("failed batch published")
@@ -0,0 +1,227 @@
package storage
import (
"bytes"
"context"
"errors"
"path/filepath"
"sync"
"testing"
"time"
)
// Faults sit at the remote seam; all captures, intents, hashes and HEADs use
// the real layer and the write-once fake remote.
type retryUploadRemote struct {
*fakeChunkRemote
mu sync.Mutex
mode string
calls map[string]int
values map[string]byte
}
func (r *retryUploadRemote) Put(ctx context.Context, key string, data []byte) error {
r.mu.Lock()
r.calls[key]++
if r.values == nil {
r.values = map[string]byte{}
}
if len(data) > 0 {
r.values[key] = data[0]
}
n, mode := r.calls[key], r.mode
r.mu.Unlock()
if mode == "down" || mode == "transient" && n == 1 || mode == "mixed" && n == 1 && len(data) > 0 && data[0] == 0x42 {
return errFakeRemoteDown
}
if mode == "lost" && n == 1 {
if err := r.fakeChunkRemote.Put(ctx, key, data); err != nil {
return err
}
return errFakeRemoteDown // binding committed, response lost
}
if mode == "collision" {
bad := bytes.Repeat([]byte{0xff}, len(data))
if err := r.fakeChunkRemote.Put(ctx, key, bad); err != nil {
return err
}
return errChunkKeyExists
}
return r.fakeChunkRemote.Put(ctx, key, data)
}
func TestChunkCutMixedSuccessDoesNotReplaySuccessfulKey(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
r := &retryUploadRemote{fakeChunkRemote: f, mode: "mixed", calls: map[string]int{}}
l := mustAttach(t, s, r, ctConfig(1))
w := newWriteLog()
w.write(t, s, 0, 0x41)
w.write(t, s, ctChunkBlocks, 0x42)
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if len(f.installedHeads()) != 1 {
t.Fatal("must publish once")
}
r.mu.Lock()
defer r.mu.Unlock()
if len(r.calls) != 2 {
t.Fatalf("changed immutable keys: %v", r.calls)
}
seen := map[byte]bool{}
for key, n := range r.calls {
value := r.values[key]
want := 1
if value == 0x42 {
want = 2
}
if value != 0x41 && value != 0x42 {
t.Fatalf("unexpected payload %x", value)
}
if n != want {
t.Fatalf("payload %x attempted %d times, want %d", value, n, want)
}
seen[value] = true
}
if len(seen) != 2 {
t.Fatal("did not exercise success and retry")
}
assertEveryHeadIsPrefixImage(t, f, w)
}
func TestChunkCutRetriesOnlyTheFailedUpload(t *testing.T) {
for _, mode := range []string{"transient", "lost"} {
t.Run(mode, func(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
r := &retryUploadRemote{fakeChunkRemote: f, mode: mode, calls: map[string]int{}}
layer := mustAttach(t, s, r, ctConfig(1))
w := newWriteLog()
w.write(t, s, 0, 0x41)
w.write(t, s, ctChunkBlocks, 0x42)
if _, err := layer.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if len(f.installedHeads()) != 1 {
t.Fatal("cut did not publish exactly one HEAD")
}
assertEveryHeadIsPrefixImage(t, f, w)
r.mu.Lock()
defer r.mu.Unlock()
if len(r.calls) != 2 {
t.Fatalf("new key generated on retry: %v", r.calls)
}
for key, n := range r.calls {
want := 2
if mode == "lost" {
want = 1
}
if n != want {
t.Fatalf("key %s attempted %d times, want %d", key, n, want)
}
}
})
}
}
func TestChunkCutUploadCollisionNeverPublishes(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
r := &retryUploadRemote{fakeChunkRemote: f, mode: "collision", calls: map[string]int{}}
layer := mustAttach(t, s, r, ctConfig(1))
w := newWriteLog()
w.write(t, s, 0, 0x41)
if _, err := layer.Cut(ctTimeout(t)); err == nil {
t.Fatal("published mismatching existing key")
}
if len(f.installedHeads()) != 0 {
t.Fatal("HEAD moved after collision")
}
}
func TestChunkCutUploadRetryHonorsDeadlineAndRetainsDirt(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
r := &retryUploadRemote{fakeChunkRemote: f, mode: "down", calls: map[string]int{}}
layer := mustAttach(t, s, r, ctConfig(1))
w := newWriteLog()
w.write(t, s, 0, 0x41)
ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
defer cancel()
if _, err := layer.Cut(ctx); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("deadline lost: %v", err)
}
if len(f.installedHeads()) != 0 {
t.Fatal("HEAD moved during outage")
}
r.mu.Lock()
r.mode = "ok"
r.mu.Unlock()
if _, err := layer.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
assertEveryHeadIsPrefixImage(t, f, w)
}
func TestChunkCutUploadAttemptBoundRetainsDirt(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
r := &retryUploadRemote{fakeChunkRemote: f, mode: "down", calls: map[string]int{}}
layer := mustAttach(t, s, r, ctConfig(1))
w := newWriteLog()
w.write(t, s, 0, 0x51)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := layer.Cut(ctx); err == nil {
t.Fatal("persistent upload outage published")
}
r.mu.Lock()
if len(r.calls) != 1 {
t.Fatalf("retry changed object keys: %v", r.calls)
}
for _, n := range r.calls {
if n != 3 {
t.Errorf("single object attempted %d times, want bounded 3", n)
}
}
r.mode = "ok"
r.mu.Unlock()
if len(f.installedHeads()) != 0 {
t.Fatal("failed object published HEAD")
}
if _, err := layer.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
assertEveryHeadIsPrefixImage(t, f, w)
}
func TestChunkCutRetrySustainedWritesPastWALWithFlush(t *testing.T) {
const walBytes = 64 * 1024
s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), ctNumBlocks, ctBlockSize, walBytes, WModeStrict, ctChunkBlocks)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { closeBounded(t, s) })
f := newFakeChunkRemote()
r := &retryUploadRemote{fakeChunkRemote: f, mode: "transient", calls: map[string]int{}}
layer := mustAttach(t, s, r, ctConfig(1))
w := newWriteLog()
for i := 0; i < 96; i++ {
w.write(t, s, uint32(i%ctNumBlocks), byte(i+1))
if (i+1)%4 == 0 {
mustSyncFlush(t, s)
}
if (i+1)%16 == 0 {
if _, err := layer.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
}
}
assertEveryHeadIsPrefixImage(t, f, w)
if len(f.installedHeads()) != 6 {
t.Fatalf("published %d HEADs", len(f.installedHeads()))
}
t.Logf("payload=%d > WAL=%d; 24 periodic flushes; 6 cuts with transient upload faults", 96*ctBlockSize, walBytes)
}
@@ -0,0 +1,68 @@
package storage
import (
"bytes"
"context"
"testing"
"time"
)
type slowSuccessfulUploadRemote struct{ *fakeChunkRemote }
func (r *slowSuccessfulUploadRemote) Put(ctx context.Context, key string, data []byte) error {
timer := time.NewTimer(600 * time.Millisecond)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return r.fakeChunkRemote.Put(ctx, key, data)
}
}
func TestChunkCutLegitimateUploadsExceedTwoSeconds(t *testing.T) {
for _, detach := range []bool{false, true} {
name := "cut"
if detach {
name = "detach"
}
t.Run(name, func(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
r := &slowSuccessfulUploadRemote{f}
cfg := ctConfig(1)
cfg.UploadConcurrency = 1
l := mustAttach(t, s, r, cfg).(*chunkLayerImpl)
want := make([]byte, ctNumBlocks*ctBlockSize)
for i := 0; i < 5; i++ {
data := makeBlock(ctBlockSize, byte(0x41+i))
if _, err := s.Write(uint32(i*ctChunkBlocks), data); err != nil {
t.Fatal(err)
}
copy(want[i*ctChunkBlocks*ctBlockSize:], data)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
start := time.Now()
var err error
if detach {
_, err = l.Detach(ctx)
} else {
_, err = l.Cut(ctx)
}
if err != nil {
t.Fatalf("legitimate multi-object work canceled: %v", err)
}
if time.Since(start) <= 2*time.Second {
t.Fatal("fixture did not exceed the former whole-cut limit")
}
heads := f.installedHeads()
if len(heads) != 1 || !bytes.Equal(f.imageOf(t, heads[0]), want) {
t.Fatal("slow successful cut did not publish the exact image once")
}
if detach && heads[0].State != ChunkHeadDetached {
t.Fatal("slow detach did not install detached proof")
}
})
}
}