From dfffdd80887ead8c6e462d562837dddb3484679f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:12:13 -0800 Subject: [PATCH 01/13] test(storage): cut upload retry, ambiguous completion and cancellation --- .../core/storage/chunk_upload_retry_test.go | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_upload_retry_test.go diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go new file mode 100644 index 0000000000..d55ce37a22 --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -0,0 +1,113 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "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 +} + +func (r *retryUploadRemote) Put(ctx context.Context, key string, data []byte) error { + r.mu.Lock() + r.calls[key]++ + n, mode := r.calls[key], r.mode + r.mu.Unlock() + if mode == "down" || mode == "transient" && n == 1 { + 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 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 { + if n != 2 { + t.Fatalf("key %s attempted %d times, want 2", key, n) + } + } + }) + } +} + +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) +} From a9d24e425665eed1f542ef284db8e69843ebc655 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:14:03 -0800 Subject: [PATCH 02/13] storage: resolve lost upload replies before bounded single-object retries --- seaweed-block/core/storage/chunk_layer.go | 9 +++-- seaweed-block/core/storage/chunk_upload.go | 34 +++++++++++++++++++ .../core/storage/chunk_upload_retry_test.go | 8 +++-- 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index d8d56fc664..ffee0274f9 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -800,6 +800,11 @@ type stagedChunk struct { const chunkStageRounds = 3 func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) { + // Retries share one cut budget, shortened by the caller's own deadline. + // As with every remote operation, an implementation ignoring cancellation + // is still joined before buffers and intents are settled. + ctx, deadlineCancel := context.WithTimeout(ctx, 5*time.Minute) + defer deadlineCancel() done, err := l.register() if err != nil { return chunkCutResult{}, err @@ -1012,7 +1017,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) @@ -1662,7 +1667,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) } diff --git a/seaweed-block/core/storage/chunk_upload.go b/seaweed-block/core/storage/chunk_upload.go index b1e79b7b2f..f03fc831f9 100644 --- a/seaweed-block/core/storage/chunk_upload.go +++ b/seaweed-block/core/storage/chunk_upload.go @@ -1,10 +1,44 @@ package storage import ( + "bytes" "context" "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. +func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byte) error { + backoff := 100 * time.Millisecond + for { + if err := ctx.Err(); err != nil { + return err + } + err := l.remote.Put(ctx, key, data) + if err == nil { + return nil + } + // 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 + } + timer := time.NewTimer(backoff) + select { + case <-ctx.Done(): + timer.Stop() + return 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. diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index d55ce37a22..cbee7db935 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -65,8 +65,12 @@ func TestChunkCutRetriesOnlyTheFailedUpload(t *testing.T) { t.Fatalf("new key generated on retry: %v", r.calls) } for key, n := range r.calls { - if n != 2 { - t.Fatalf("key %s attempted %d times, want 2", key, n) + want := 2 + if mode == "lost" { + want = 1 + } + if n != want { + t.Fatalf("key %s attempted %d times, want %d", key, n, want) } } }) From 92f172006a595a15f3bf7225430e4b083faa1a13 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:18:34 -0800 Subject: [PATCH 03/13] docs: record bounded cut-upload retry and unchanged publication guards --- seaweed-block/docs/design/agent-workspace-design.md | 1 + seaweed-block/docs/design/invariants.md | 10 +++++++++- seaweed-block/docs/spec/CutPipeline.tla | 5 +++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 48b9ca7a58..bef22a0ab8 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -126,6 +126,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto 5. **LSN guard:** if H is below HEAD's `RemoteLSN`, refuse (`lsn_behind`). 6. **Diff:** upload only chunks whose SHA-256 differs from HEAD; drop all-zero chunks from the map. 7. **Intent first:** write an intent naming every key, then upload in parallel (`UploadConcurrency`, `--chunk-upload-concurrency`, default 8, 1 to 64). + Failed chunk uploads retry the same immutable key and captured bytes with 100 ms exponential backoff capped at 2 s. Resolve a possibly committed binding by exact-byte read-back before replay; a mismatch refuses the cut. All retries share a five-minute cut execution budget, shortened by the caller deadline. Queued lock wait and a remote ignoring cancellation are not forcibly terminated: workers remain joined before buffers/intents settle. Failure preserves dirt. HEAD CAS is never blindly replayed by this upload retry. 8. **Manifest:** build segments; new segments are also covered by an intent before upload (`PrepareManifest`). 9. **Re-admit** right before the CAS; fence if a superseding holder owns HEAD (`supersededBy`). 10. **CAS** HEAD on `{gen, epoch}` with `RemoteLSN = H`. On success, drop the intents and settle unchanged owned-map versions, keeping post-cut dirt. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b032a37af0..e9dcfa760e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -194,6 +194,8 @@ stateDiagram-v2 Aborted --> Refused: drain owners, cleanup, merge candidates Copy --> Refused: H below HEAD RemoteLSN Closed --> Upload: drain and cleanup; intent durable first + Upload --> Upload: retry one immutable key after backoff + Upload --> Refused: shared deadline/cancel or mismatching binding Upload --> Manifest Manifest --> Readmit Readmit --> Fenced: superseding HEAD @@ -213,7 +215,7 @@ stateDiagram-v2 | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read into buffers; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | -| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after a durable intent names them | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | +| Upload | upload changed chunks after a durable intent names their write-once keys; retry one key under the shared five-minute cut execution deadline (or shorter caller deadline); resolve ambiguous bindings by exact-byte read-back before replay | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | | Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | | No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | | Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | @@ -469,6 +471,12 @@ Notes: |---|---|---|---|---|---|---| | `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | +### Cut upload retry + +| ID | Status | Invariant | Enforced in | Tests | Model | +|---|---|---|---|---|---| +| INV-CUT-UPLOAD-RETRY-001 | ACTIVE | A failed chunk upload retries the same key and captured bytes, keeps its intent, and cannot advance HEAD before completion; cancellation preserves dirt. | `chunk_upload.go` `putCaptured`; `chunk_layer.go` `captureLocked` | `TestChunkCutRetriesOnlyTheFailedUpload`, `TestChunkCutUploadCollisionNeverPublishes`, `TestChunkCutUploadRetryHonorsDeadlineAndRetainsDirt` | M5; retry stutters in abstract `CutPipeline`; timing and ambiguity are qualified by native tests. | + ## Part C. Change rules How a fix or a feature is calibrated against this model: diff --git a/seaweed-block/docs/spec/CutPipeline.tla b/seaweed-block/docs/spec/CutPipeline.tla index 40367a642d..166f466a8f 100644 --- a/seaweed-block/docs/spec/CutPipeline.tla +++ b/seaweed-block/docs/spec/CutPipeline.tla @@ -13,6 +13,11 @@ (* chunk is compared against HEAD; cuts are refused ("reconciling") *) (* until the compare finishes (chunk_layer.go:95); *) (* - a crash before the root CAS leaves only orphan uploads. *) +(* Per-object upload retries retain the same key/bytes and intent. Failed *) +(* attempts make no abstract state change (Spec permits stuttering); the *) +(* atomic Cut below still requires all objects before HEAD publication. *) +(* Backoff/deadline timing and ambiguous-reply byte checks are qualified *) +(* by native TestChunkCut*Upload* controls, not by this abstraction. *) (* Chunk content = the LSN of the write it holds. *) (***************************************************************************) EXTENDS Integers, FiniteSets, Sequences, TLC From b47b40fadf00f049d53403c2fc9f952543d93cb1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:20:47 -0800 Subject: [PATCH 04/13] storage: retain the remote cause when a retry budget ends --- seaweed-block/core/storage/chunk_upload.go | 7 +++++-- .../core/storage/chunk_upload_parallel_test.go | 13 ++++++++++--- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/storage/chunk_upload.go b/seaweed-block/core/storage/chunk_upload.go index f03fc831f9..7a623ac315 100644 --- a/seaweed-block/core/storage/chunk_upload.go +++ b/seaweed-block/core/storage/chunk_upload.go @@ -3,6 +3,7 @@ package storage import ( "bytes" "context" + "errors" "sync" "time" ) @@ -12,14 +13,16 @@ import ( // bytes read from that binding prove completion; a collision is terminal. func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byte) error { backoff := 100 * time.Millisecond + var lastErr error for { if err := ctx.Err(); err != nil { - return err + 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 { @@ -32,7 +35,7 @@ func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byt select { case <-ctx.Done(): timer.Stop() - return ctx.Err() + return errors.Join(lastErr, ctx.Err()) case <-timer.C: } backoff = min(2*time.Second, 2*backoff) diff --git a/seaweed-block/core/storage/chunk_upload_parallel_test.go b/seaweed-block/core/storage/chunk_upload_parallel_test.go index c843ccee54..3cad929a6c 100644 --- a/seaweed-block/core/storage/chunk_upload_parallel_test.go +++ b/seaweed-block/core/storage/chunk_upload_parallel_test.go @@ -108,12 +108,16 @@ type unjoinedUploadRemote struct { } func (r *unjoinedUploadRemote) Put(ctx context.Context, key string, data []byte) error { - if r.calls.Add(1) == 1 { + switch r.calls.Add(1) { + case 1: <-r.second close(r.failed) return errFakeRemoteDown + case 2: + close(r.second) + default: + return errFakeRemoteDown } - close(r.second) <-r.release return r.fakeChunkRemote.Put(context.Background(), key, data) } @@ -128,10 +132,13 @@ 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()) + defer cancel() done := make(chan error, 1) - go func() { _, err := l.Cut(context.Background()); done <- err }() + go func() { _, 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 From 62813dc9a87dcc206f4a79bbfb34a0912c2ee9b6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:23:37 -0800 Subject: [PATCH 05/13] test(storage): exercise upload retries beyond the WAL with periodic flushes --- .../core/storage/chunk_upload_retry_test.go | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index cbee7db935..a03441690c 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "path/filepath" "sync" "testing" "time" @@ -115,3 +116,33 @@ func TestChunkCutUploadRetryHonorsDeadlineAndRetainsDirt(t *testing.T) { } 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) +} From 19195503eb5d4b77cc9217bc8a90a11a024d16df Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:57:17 -0800 Subject: [PATCH 06/13] chore: keep public PR changes to implementation and tests --- seaweed-block/docs/design/agent-workspace-design.md | 1 - seaweed-block/docs/design/invariants.md | 10 +--------- seaweed-block/docs/spec/CutPipeline.tla | 5 ----- 3 files changed, 1 insertion(+), 15 deletions(-) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index bef22a0ab8..48b9ca7a58 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -126,7 +126,6 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto 5. **LSN guard:** if H is below HEAD's `RemoteLSN`, refuse (`lsn_behind`). 6. **Diff:** upload only chunks whose SHA-256 differs from HEAD; drop all-zero chunks from the map. 7. **Intent first:** write an intent naming every key, then upload in parallel (`UploadConcurrency`, `--chunk-upload-concurrency`, default 8, 1 to 64). - Failed chunk uploads retry the same immutable key and captured bytes with 100 ms exponential backoff capped at 2 s. Resolve a possibly committed binding by exact-byte read-back before replay; a mismatch refuses the cut. All retries share a five-minute cut execution budget, shortened by the caller deadline. Queued lock wait and a remote ignoring cancellation are not forcibly terminated: workers remain joined before buffers/intents settle. Failure preserves dirt. HEAD CAS is never blindly replayed by this upload retry. 8. **Manifest:** build segments; new segments are also covered by an intent before upload (`PrepareManifest`). 9. **Re-admit** right before the CAS; fence if a superseding holder owns HEAD (`supersededBy`). 10. **CAS** HEAD on `{gen, epoch}` with `RemoteLSN = H`. On success, drop the intents and settle unchanged owned-map versions, keeping post-cut dirt. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e9dcfa760e..b032a37af0 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -194,8 +194,6 @@ stateDiagram-v2 Aborted --> Refused: drain owners, cleanup, merge candidates Copy --> Refused: H below HEAD RemoteLSN Closed --> Upload: drain and cleanup; intent durable first - Upload --> Upload: retry one immutable key after backoff - Upload --> Refused: shared deadline/cancel or mismatching binding Upload --> Manifest Manifest --> Readmit Readmit --> Fenced: superseding HEAD @@ -215,7 +213,7 @@ stateDiagram-v2 | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read into buffers; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | -| Upload | upload changed chunks after a durable intent names their write-once keys; retry one key under the shared five-minute cut execution deadline (or shorter caller deadline); resolve ambiguous bindings by exact-byte read-back before replay | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | +| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after a durable intent names them | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | | Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | | No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | | Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | @@ -471,12 +469,6 @@ Notes: |---|---|---|---|---|---|---| | `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | -### Cut upload retry - -| ID | Status | Invariant | Enforced in | Tests | Model | -|---|---|---|---|---|---| -| INV-CUT-UPLOAD-RETRY-001 | ACTIVE | A failed chunk upload retries the same key and captured bytes, keeps its intent, and cannot advance HEAD before completion; cancellation preserves dirt. | `chunk_upload.go` `putCaptured`; `chunk_layer.go` `captureLocked` | `TestChunkCutRetriesOnlyTheFailedUpload`, `TestChunkCutUploadCollisionNeverPublishes`, `TestChunkCutUploadRetryHonorsDeadlineAndRetainsDirt` | M5; retry stutters in abstract `CutPipeline`; timing and ambiguity are qualified by native tests. | - ## Part C. Change rules How a fix or a feature is calibrated against this model: diff --git a/seaweed-block/docs/spec/CutPipeline.tla b/seaweed-block/docs/spec/CutPipeline.tla index 166f466a8f..40367a642d 100644 --- a/seaweed-block/docs/spec/CutPipeline.tla +++ b/seaweed-block/docs/spec/CutPipeline.tla @@ -13,11 +13,6 @@ (* chunk is compared against HEAD; cuts are refused ("reconciling") *) (* until the compare finishes (chunk_layer.go:95); *) (* - a crash before the root CAS leaves only orphan uploads. *) -(* Per-object upload retries retain the same key/bytes and intent. Failed *) -(* attempts make no abstract state change (Spec permits stuttering); the *) -(* atomic Cut below still requires all objects before HEAD publication. *) -(* Backoff/deadline timing and ambiguous-reply byte checks are qualified *) -(* by native TestChunkCut*Upload* controls, not by this abstraction. *) (* Chunk content = the LSN of the write it holds. *) (***************************************************************************) EXTENDS Integers, FiniteSets, Sequences, TLC From 3579e6dd42b0a03b34c00d87d20668df4783d488 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:56:33 -0800 Subject: [PATCH 07/13] test: distinguish successful key from failed upload retry --- .../core/storage/chunk_upload_retry_test.go | 53 +++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index a03441690c..b553613f6f 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -14,14 +14,21 @@ import ( // the real layer and the write-once fake remote. type retryUploadRemote struct { *fakeChunkRemote - mu sync.Mutex - mode string - calls map[string]int + 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 { @@ -43,6 +50,46 @@ func (r *retryUploadRemote) Put(ctx context.Context, key string, data []byte) er 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) + } + assertEveryHeadIsPrefixImage(t, f, w) + 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") + } +} + func TestChunkCutRetriesOnlyTheFailedUpload(t *testing.T) { for _, mode := range []string{"transient", "lost"} { t.Run(mode, func(t *testing.T) { From 9536ab0dd2d34cf70e70e2b5fd28e8c660d18587 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:57:51 -0800 Subject: [PATCH 08/13] test: bound shared staged cut budget and ordinary write progress --- .../core/storage/chunk_upload_budget_test.go | 149 ++++++++++++++++++ .../core/storage/chunk_upload_retry_test.go | 2 +- 2 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/storage/chunk_upload_budget_test.go diff --git a/seaweed-block/core/storage/chunk_upload_budget_test.go b/seaweed-block/core/storage/chunk_upload_budget_test.go new file mode 100644 index 0000000000..db6e60ef26 --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_budget_test.go @@ -0,0 +1,149 @@ +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 TestChunkCutDefaultBudgetSharedAcrossStagesAndWritesProgress(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.WithCancel(context.Background()) + 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) + } + if deadlines[0].IsZero() || deadlines[0].Sub(start) > 4*time.Second { + t.Fatalf("default cut budget exceeds sub-5s target: %v", deadlines[0].Sub(start)) + } + 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 default 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") + } +} diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index b553613f6f..c243b2aee8 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -31,7 +31,7 @@ func (r *retryUploadRemote) Put(ctx context.Context, key string, data []byte) er } n, mode := r.calls[key], r.mode r.mu.Unlock() - if mode == "down" || mode == "transient" && n == 1 { + if mode == "down" || mode == "transient" && n == 1 || mode == "mixed" && n == 1 && len(data) > 0 && data[0] == 0x42 { return errFakeRemoteDown } if mode == "lost" && n == 1 { From d67368a9899f71c73800bdec53edf75894db30ae Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:59:12 -0800 Subject: [PATCH 09/13] fix: shorten shared cut retry budget and bound test worker cleanup --- seaweed-block/core/storage/chunk_layer.go | 2 +- .../storage/chunk_upload_parallel_test.go | 51 ++++++++++++++----- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index ffee0274f9..f9d8e20733 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -803,7 +803,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // Retries share one cut budget, shortened by the caller's own deadline. // As with every remote operation, an implementation ignoring cancellation // is still joined before buffers and intents are settled. - ctx, deadlineCancel := context.WithTimeout(ctx, 5*time.Minute) + ctx, deadlineCancel := context.WithTimeout(ctx, 2*time.Second) defer deadlineCancel() done, err := l.register() if err != nil { diff --git a/seaweed-block/core/storage/chunk_upload_parallel_test.go b/seaweed-block/core/storage/chunk_upload_parallel_test.go index 3cad929a6c..7bb842c9f2 100644 --- a/seaweed-block/core/storage/chunk_upload_parallel_test.go +++ b/seaweed-block/core/storage/chunk_upload_parallel_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "sync" "sync/atomic" "testing" "time" @@ -105,16 +106,22 @@ 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 { switch r.calls.Add(1) { case 1: - <-r.second + 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 } @@ -124,7 +131,7 @@ func (r *unjoinedUploadRemote) Put(ctx context.Context, key string, data []byte) 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 @@ -133,31 +140,51 @@ func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) { w.write(t, s, 0, 0x21) w.write(t, s, ctChunkBlocks, 0x22) ctx, cancel := context.WithCancel(context.Background()) - defer cancel() done := make(chan error, 1) - go func() { _, err := l.Cut(ctx); 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") From 953d2795b846789245bda4c30047c3aaa9e65a87 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:01:02 -0800 Subject: [PATCH 10/13] test: qualify BASE waiting behind an interrupted upload --- .../storage/chunk_upload_base_budget_test.go | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_upload_base_budget_test.go diff --git a/seaweed-block/core/storage/chunk_upload_base_budget_test.go b/seaweed-block/core/storage/chunk_upload_base_budget_test.go new file mode 100644 index 0000000000..1e0d8ff462 --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_base_budget_test.go @@ -0,0 +1,82 @@ +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") + } + if err := got.h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } +} From 42d30e06274d1de7c607874db927c0c9a8e52963 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:04:46 -0800 Subject: [PATCH 11/13] test: retire BASE begin hook before completion transition --- seaweed-block/core/storage/chunk_upload_base_budget_test.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/seaweed-block/core/storage/chunk_upload_base_budget_test.go b/seaweed-block/core/storage/chunk_upload_base_budget_test.go index 1e0d8ff462..f52f4d8ea1 100644 --- a/seaweed-block/core/storage/chunk_upload_base_budget_test.go +++ b/seaweed-block/core/storage/chunk_upload_base_budget_test.go @@ -76,6 +76,12 @@ func TestChunkUploadOutageSettlesBeforeQueuedBASE(t *testing.T) { 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) } From aea5f5d88bf1d849293c8a91045c8bbd2852096c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:15:38 -0800 Subject: [PATCH 12/13] test: observe mixed-arm counts before the generic overwrite oracle --- seaweed-block/core/storage/chunk_upload_retry_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index c243b2aee8..f946ca0be0 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -61,7 +61,6 @@ func TestChunkCutMixedSuccessDoesNotReplaySuccessfulKey(t *testing.T) { if _, err := l.Cut(ctTimeout(t)); err != nil { t.Fatal(err) } - assertEveryHeadIsPrefixImage(t, f, w) if len(f.installedHeads()) != 1 { t.Fatal("must publish once") } @@ -88,6 +87,7 @@ func TestChunkCutMixedSuccessDoesNotReplaySuccessfulKey(t *testing.T) { if len(seen) != 2 { t.Fatal("did not exercise success and retry") } + assertEveryHeadIsPrefixImage(t, f, w) } func TestChunkCutRetriesOnlyTheFailedUpload(t *testing.T) { From d9e5f7c9fa3894e78d5a832fbf55dacfc336cbde Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:42:23 -0800 Subject: [PATCH 13/13] fix: bound individual upload retries without timing out whole cuts --- seaweed-block/core/storage/chunk_layer.go | 5 -- seaweed-block/core/storage/chunk_upload.go | 7 +- .../core/storage/chunk_upload_budget_test.go | 11 +-- .../core/storage/chunk_upload_retry_test.go | 32 +++++++++ .../storage/chunk_upload_slow_cut_test.go | 68 +++++++++++++++++++ 5 files changed, 112 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_upload_slow_cut_test.go diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index f9d8e20733..3f508fed75 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -800,11 +800,6 @@ type stagedChunk struct { const chunkStageRounds = 3 func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) { - // Retries share one cut budget, shortened by the caller's own deadline. - // As with every remote operation, an implementation ignoring cancellation - // is still joined before buffers and intents are settled. - ctx, deadlineCancel := context.WithTimeout(ctx, 2*time.Second) - defer deadlineCancel() done, err := l.register() if err != nil { return chunkCutResult{}, err diff --git a/seaweed-block/core/storage/chunk_upload.go b/seaweed-block/core/storage/chunk_upload.go index 7a623ac315..ff71412b44 100644 --- a/seaweed-block/core/storage/chunk_upload.go +++ b/seaweed-block/core/storage/chunk_upload.go @@ -11,10 +11,12 @@ import ( // 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 { + for attempt := 1; ; attempt++ { if err := ctx.Err(); err != nil { return errors.Join(lastErr, err) } @@ -31,6 +33,9 @@ func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byt } return errChunkKeyExists } + if attempt == 3 { + return lastErr + } timer := time.NewTimer(backoff) select { case <-ctx.Done(): diff --git a/seaweed-block/core/storage/chunk_upload_budget_test.go b/seaweed-block/core/storage/chunk_upload_budget_test.go index db6e60ef26..836b7a9275 100644 --- a/seaweed-block/core/storage/chunk_upload_budget_test.go +++ b/seaweed-block/core/storage/chunk_upload_budget_test.go @@ -41,7 +41,7 @@ func (r *cutBudgetRemote) Put(ctx context.Context, key string, data []byte) erro return r.fakeChunkRemote.Put(ctx, key, data) } -func TestChunkCutDefaultBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) { +func TestChunkCutCallerBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() r := &cutBudgetRemote{fakeChunkRemote: f, held: make(chan struct{})} @@ -55,7 +55,7 @@ func TestChunkCutDefaultBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) t.Fatal(err) } } - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) done := make(chan error, 1) joined := make(chan struct{}) t.Cleanup(func() { @@ -79,8 +79,9 @@ func TestChunkCutDefaultBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) if len(deadlines) != 3 { t.Fatalf("want two staged and one final upload: %v", deadlines) } - if deadlines[0].IsZero() || deadlines[0].Sub(start) > 4*time.Second { - t.Fatalf("default cut budget exceeds sub-5s target: %v", deadlines[0].Sub(start)) + 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]) { @@ -118,7 +119,7 @@ func TestChunkCutDefaultBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) select { case err := <-done: if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("lost default deadline: %v", err) + t.Fatalf("lost caller deadline: %v", err) } case <-time.After(5 * time.Second): t.Fatal("cooperative cut did not settle") diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go index f946ca0be0..d8d2419af6 100644 --- a/seaweed-block/core/storage/chunk_upload_retry_test.go +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -164,6 +164,38 @@ func TestChunkCutUploadRetryHonorsDeadlineAndRetainsDirt(t *testing.T) { 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) diff --git a/seaweed-block/core/storage/chunk_upload_slow_cut_test.go b/seaweed-block/core/storage/chunk_upload_slow_cut_test.go new file mode 100644 index 0000000000..7f2fd7e4be --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_slow_cut_test.go @@ -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") + } + }) + } +}