From 22b53ce945a69ebdff717b1102e86209ab331c90 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 05:38:07 -0800 Subject: [PATCH 01/14] storage: capture-path intent schedules (RED) A cut that uploads writes an intent naming exactly its keys before the first upload and deletes its own intent after the confirmed CAS; no upload, no intent; a failed intent write uploads nothing; a failed upload or a refused CAS deletes the intent; an unknown CAS outcome keeps it until the next cut settles the proposal; a lost CAS response confirmed by re-read deletes it; a failed delete is retried at the next cut; other intents are untouched. The fake remote gains intent failure hooks and records written intents. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_fake_remote_test.go | 14 + .../core/storage/chunk_layer_intent_test.go | 309 ++++++++++++++++++ 2 files changed, 323 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_layer_intent_test.go diff --git a/seaweed-block/core/storage/chunk_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index ad9008eabc..c04c2de7ff 100644 --- a/seaweed-block/core/storage/chunk_fake_remote_test.go +++ b/seaweed-block/core/storage/chunk_fake_remote_test.go @@ -98,6 +98,10 @@ type fakeChunkRemote struct { afterCAS func(f *fakeChunkRemote) // runs once, under mu, after the next CAS is decided intents map[string]chunkIntent deferred []deferredCAS + + failPutIntent error // PutIntent fails without writing + failDeleteIntent int // the next N DeleteIntent calls fail without deleting + putIntents []chunkIntent // every intent written, in order } func newFakeChunkRemote() *fakeChunkRemote { @@ -117,14 +121,24 @@ func (f *fakeChunkRemote) PutIntent(ctx context.Context, in chunkIntent) (string in.ID, in.CreatedNs, in.Keys = id, time.Now().UnixNano(), append([]string(nil), in.Keys...) f.mu.Lock() defer f.mu.Unlock() + if f.failPutIntent != nil { + f.ops = append(f.ops, "putintent:fail") + return "", f.failPutIntent + } f.ops = append(f.ops, "putintent:"+id) f.intents[id] = in + f.putIntents = append(f.putIntents, in) return id, nil } func (f *fakeChunkRemote) DeleteIntent(ctx context.Context, id string) error { f.mu.Lock() defer f.mu.Unlock() + if f.failDeleteIntent > 0 { + f.failDeleteIntent-- + f.ops = append(f.ops, "deleteintent:fail:"+id) + return errors.New("fake remote: injected DeleteIntent failure") + } f.ops = append(f.ops, "deleteintent:"+id) delete(f.intents, id) return nil diff --git a/seaweed-block/core/storage/chunk_layer_intent_test.go b/seaweed-block/core/storage/chunk_layer_intent_test.go new file mode 100644 index 0000000000..ecbdb28bd7 --- /dev/null +++ b/seaweed-block/core/storage/chunk_layer_intent_test.go @@ -0,0 +1,309 @@ +package storage + +// The capture path's intents (W5): a cut that uploads chunks durably writes +// an intent naming exactly those keys before the first upload, and deletes +// only its own intent once the outcome is settled: after a confirmed HEAD +// CAS, or a clean abort. An uncertain CAS keeps the intent until a later +// HEAD read settles it. + +import ( + "context" + "errors" + "sort" + "strings" + "testing" +) + +// opsSince returns the remote ops recorded after mark. +func opsSince(f *fakeChunkRemote, mark int) []string { + return f.stats().ops[mark:] +} + +func indexOf(ops []string, pred func(string) bool) int { + for i, op := range ops { + if pred(op) { + return i + } + } + return -1 +} + +func liveIntents(t *testing.T, f *fakeChunkRemote) []chunkIntent { + t.Helper() + in, err := f.ListIntents(context.Background()) + if err != nil { + t.Fatal(err) + } + return in +} + +func lastPutIntent(t *testing.T, f *fakeChunkRemote) chunkIntent { + t.Helper() + f.mu.Lock() + defer f.mu.Unlock() + if len(f.putIntents) == 0 { + t.Fatal("no intent was written") + } + return f.putIntents[len(f.putIntents)-1] +} + +func uploadedKeys(ops []string) []string { + var keys []string + for _, op := range ops { + if k, ok := strings.CutPrefix(op, "put:"); ok { + keys = append(keys, k) + } + } + sort.Strings(keys) + return keys +} + +func TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + w.write(t, s, 9, 0x29) + + mark := len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + ops := opsSince(f, mark) + in := lastPutIntent(t, f) + iIntent := indexOf(ops, func(op string) bool { return op == "putintent:"+in.ID }) + iPut := indexOf(ops, func(op string) bool { return strings.HasPrefix(op, "put:") }) + iCAS := indexOf(ops, func(op string) bool { return op == "cas:ok" }) + iDel := indexOf(ops, func(op string) bool { return op == "deleteintent:"+in.ID }) + if iIntent < 0 || iPut < 0 || iIntent > iPut { + t.Fatalf("intent not written before the first upload: ops %q", ops) + } + if iCAS < 0 || iDel < iCAS { + t.Fatalf("intent not deleted after the confirmed CAS: ops %q", ops) + } + keys := append([]string(nil), in.Keys...) + sort.Strings(keys) + if got := uploadedKeys(ops); strings.Join(keys, ",") != strings.Join(got, ",") { + t.Fatalf("intent keys %q, uploaded keys %q", keys, got) + } + if in.Gen != 0 || in.Epoch != 1 || in.Holder != "host-a" { + t.Fatalf("intent gen %d epoch %d holder %q, want the cut's base gen 0, epoch 1, host-a", in.Gen, in.Epoch, in.Holder) + } + if live := liveIntents(t, f); len(live) != 0 { + t.Fatalf("intents left after a published cut: %+v", live) + } +} + +func TestChunkIntent_CutWithoutUploadWritesNoIntent(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + w.write(t, s, 2, 0x00) // the chunk is zero again: the cut only drops it + mark := len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + ops := opsSince(f, mark) + if indexOf(ops, func(op string) bool { return strings.HasPrefix(op, "putintent") }) >= 0 { + t.Fatalf("a cut with no upload wrote an intent: ops %q", ops) + } + if indexOf(ops, func(op string) bool { return op == "cas:ok" }) < 0 { + t.Fatalf("the dropping cut did not publish: ops %q", ops) + } +} + +func TestChunkIntent_FailedPutIntentUploadsNothing(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.failPutIntent = errors.New("injected PutIntent failure") + f.mu.Unlock() + mark := len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); err == nil { + t.Fatal("cut succeeded although its intent could not be written") + } + if got := uploadedKeys(opsSince(f, mark)); len(got) != 0 { + t.Fatalf("chunks uploaded without an intent: %q", got) + } + f.mu.Lock() + f.failPutIntent = nil + f.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatalf("cut after the intent store recovered: %v", err) + } + if heads := f.installedHeads(); len(heads) != 1 || len(heads[0].Chunks) != 1 { + t.Fatalf("the retried cut did not publish the write: %+v", heads) + } +} + +func TestChunkIntent_FailedUploadDeletesIntent(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.failPut = errors.New("injected upload failure") + f.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); err == nil { + t.Fatal("cut succeeded although its upload failed") + } + in := lastPutIntent(t, f) + if live := liveIntents(t, f); len(live) != 0 { + t.Fatalf("intent %s left after a cleanly aborted cut: %+v", in.ID, live) + } +} + +// HEAD is taken over before the CAS: the CAS is refused for good and the +// layer fences. Its uploads are orphans; its intent goes. +func TestChunkIntent_RefusedCASDeletesIntent(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.beforeCAS = func(f *fakeChunkRemote) { f.takeOverLocked("host-b") } + f.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerFenced) { + t.Fatalf("cut against a taken-over HEAD: %v; want fenced", err) + } + if live := liveIntents(t, f); len(live) != 0 { + t.Fatalf("intent left after a refused CAS: %+v", live) + } +} + +// The CAS outcome is unknown and HEAD still holds its base: the intent +// stays until the next cut settles the proposal, then goes. +func TestChunkIntent_UncertainCASKeepsIntentUntilSettled(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.casModes = []fakeCASMode{casUnknownNotApplied} + f.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { + t.Fatalf("cut with an unknown CAS outcome: %v", err) + } + in := lastPutIntent(t, f) + if live := liveIntents(t, f); len(live) != 1 || live[0].ID != in.ID { + t.Fatalf("intents while the CAS is unresolved: %+v; want only %s", live, in.ID) + } + mark := len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatalf("settling cut: %v", err) + } + ops := opsSince(f, mark) + iCAS := indexOf(ops, func(op string) bool { return op == "cas:ok" }) + iDel := indexOf(ops, func(op string) bool { return op == "deleteintent:"+in.ID }) + if iCAS < 0 || iDel < iCAS { + t.Fatalf("held intent not deleted after its proposal landed: ops %q", ops) + } + if live := liveIntents(t, f); len(live) != 0 { + t.Fatalf("intents left after settlement: %+v", live) + } +} + +// The CAS applied but its response was lost: the HEAD re-read confirms it, +// and the intent goes in the same cut. +func TestChunkIntent_LostCASResponseConfirmedDeletesIntent(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.casModes = []fakeCASMode{casAppliedLost} + f.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatalf("cut whose CAS response was lost: %v", err) + } + if live := liveIntents(t, f); len(live) != 0 { + t.Fatalf("intent left after a confirmed (re-read) CAS: %+v", live) + } +} + +// A failed DeleteIntent does not fail a published cut; the next cut deletes +// the leftover. +func TestChunkIntent_FailedDeleteIsRetriedNextCut(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.failDeleteIntent = 1 + f.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatalf("published cut reported the intent delete failure: %v", err) + } + first := lastPutIntent(t, f) + if live := liveIntents(t, f); len(live) != 1 || live[0].ID != first.ID { + t.Fatalf("intents after a failed delete: %+v", live) + } + w.write(t, s, 9, 0x29) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if live := liveIntents(t, f); len(live) != 0 { + t.Fatalf("leftover intent not retried: %+v", live) + } +} + +// A cut deletes only its own intent. +func TestChunkIntent_OtherIntentsUntouched(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + other, err := f.PutIntent(context.Background(), chunkIntent{Gen: 0, Epoch: 1, Holder: "snapshot-op", Keys: []string{"chunks/e1/c0/other-1"}}) + if err != nil { + t.Fatal(err) + } + w := newWriteLog() + w.write(t, s, 2, 0x22) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if live := liveIntents(t, f); len(live) != 1 || live[0].ID != other { + t.Fatalf("intents after the cut: %+v; want only %s", live, other) + } +} + +// Admission is refused at the final check right before the CAS: a clean +// abort, so the intent goes. +func TestChunkIntent_AdmissionRefusedBeforeCASDeletesIntent(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + calls := 0 + cfg.CaptureAllowed = func() error { + calls++ + if calls >= 2 { // the cut's start passes; the check before the CAS refuses + return errors.New("demoted") + } + return nil + } + layer := mustAttach(t, s, f, cfg) + w := newWriteLog() + w.write(t, s, 2, 0x22) + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) { + t.Fatalf("cut refused before its CAS: %v", err) + } + if n := f.stats().cas; n != 0 { + t.Fatalf("refused cut issued %d CAS", n) + } + if live := liveIntents(t, f); len(live) != 0 { + t.Fatalf("intent left after admission was refused: %+v", live) + } +} From 15e98ba7ee24a6904a824f6dfe0e56e0eb6fc2e3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 05:40:05 -0800 Subject: [PATCH 02/14] storage: the capture path writes an intent before uploading and settles it A cut that uploads chunks now writes one intent naming exactly the keys it will upload, at the cut's base HEAD generation with the layer's epoch and holder. The intent is durable before the first upload; if it cannot be written, nothing is uploaded. A cut that only drops chunks writes none. The cut deletes only its own intent, once its outcome is settled: - after the HEAD CAS succeeds, or a HEAD re-read confirms its proposal; - on a clean abort: a failed upload, a refused admission, a fence, or a HEAD that moved past the CAS's base. An unknown CAS outcome keeps the intent with the pending proposal. The next cut deletes it once that proposal is settled, whether it landed or can never land. A failed delete never fails a settled cut; the next cut retries it. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 98 +++++++++++++++---- .../core/storage/chunk_layer_intent_test.go | 8 +- 2 files changed, 85 insertions(+), 21 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 595c6013dc..2d5a8122ec 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -72,14 +72,20 @@ type chunkLayerImpl struct { // pendingBase is the version the unresolved CAS expected. While HEAD is // still at it, that CAS may still land, so a read alone never settles it. pendingBase chunkHeadVersion - remoteLSN uint64 - hdr chunkBitmapHeader // last header written or loaded - dirty map[uint64]bool // chunks dirtied since the cut in progress or the last HEAD - inflight map[uint64]bool // chunks captured by a cut whose HEAD is not yet installed - allDirty bool // a BASE block landed: every chunk is dirty - hashMode bool // the dirty set is unknown: compare every chunk by hash - cutLSN uint64 // H of the latest cut taken (in flight or installed) - keySeq uint64 + // pendingIntent is the intent of the unresolved proposal in pending; + // it is deleted once that proposal is settled. + pendingIntent string + // leftoverIntents are this layer's own intents whose delete failed + // after their cut was settled; every cut retries them. + leftoverIntents []string + remoteLSN uint64 + hdr chunkBitmapHeader // last header written or loaded + dirty map[uint64]bool // chunks dirtied since the cut in progress or the last HEAD + inflight map[uint64]bool // chunks captured by a cut whose HEAD is not yet installed + allDirty bool // a BASE block landed: every chunk is dirty + hashMode bool // the dirty set is unknown: compare every chunk by hash + cutLSN uint64 // H of the latest cut taken (in flight or installed) + keySeq uint64 // Test-only scheduling hooks; nil in production. testPresenceSnapshotHook func() // after a presence snapshot, before it is written @@ -557,6 +563,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC if err := l.resolvePending(ctx); err != nil { return chunkCutResult{}, err } + l.retryLeftoverIntents(ctx) // Quiesced cut. l.s.captureMu.Lock() @@ -628,6 +635,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC } var changed []uint64 newKeys := map[uint64]string{} + type upload struct { + c capturedChunk + key string + } + var uploads []upload for _, c := range captured { ref, had := baseHead.Chunks[c.idx] switch { @@ -638,14 +650,32 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC changed = append(changed, c.idx) continue } - key := l.newKey(c.idx) - if err := l.remote.Put(ctx, key, c.data); err != nil { - l.abortCut(all) - return chunkCutResult{}, fmt.Errorf("storage: capture upload chunk %d: %w: %w", c.idx, errChunkRemoteUnavailable, err) + uploads = append(uploads, upload{c: c, key: l.newKey(c.idx)}) + } + // The intent names every key this cut uploads and is durable before + // the first upload: GC treats it as a root until the cut is settled. + var intent string + if len(uploads) > 0 { + keys := make([]string, len(uploads)) + for i, u := range uploads { + keys[i] = u.key } - next.Chunks[c.idx] = chunkRef{Key: key, SHA256: c.sum} - newKeys[c.idx] = key - changed = append(changed, c.idx) + id, err := l.remote.PutIntent(ctx, chunkIntent{Gen: baseHead.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys}) + if err != nil { + l.abortCut(all) + return chunkCutResult{}, fmt.Errorf("storage: capture intent: %w: %w", errChunkRemoteUnavailable, err) + } + intent = id + } + for _, u := range uploads { + if err := l.remote.Put(ctx, u.key, u.c.data); err != nil { + l.abortCut(all) + l.dropIntent(ctx, intent) + return chunkCutResult{}, fmt.Errorf("storage: capture upload chunk %d: %w: %w", u.c.idx, errChunkRemoteUnavailable, err) + } + next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum} + newKeys[u.c.idx] = u.key + changed = append(changed, u.c.idx) } if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) { l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS @@ -653,10 +683,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC } if err := l.admit(); err != nil { // admission re-checked right before the CAS l.abortCut(all) + l.dropIntent(ctx, intent) return chunkCutResult{}, err } if l.supersededBy(baseHead) { l.abortCut(all) + l.dropIntent(ctx, intent) l.stMu.Lock() l.fenced = true l.stMu.Unlock() @@ -667,6 +699,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC if casErr == nil { next.Gen = gen l.finishCut(next, h, changed, newKeys) + l.dropIntent(ctx, intent) return l.cutDone(chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, detach), nil } // Precondition or unknown outcome: resolve by re-reading HEAD, never by @@ -676,6 +709,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC p := copyHead(next) l.pending = &p l.pendingDetach, l.pendingCut, l.pendingBase = detach, chunkCutResult{H: h, FullHash: all}, expected + l.pendingIntent = intent // kept until the proposal is settled l.stMu.Unlock() l.abortCut(all) } @@ -693,9 +727,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC } if sameProposal(cur, next) { l.finishCut(cur, h, changed, newKeys) + l.dropIntent(ctx, intent) return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil } + // HEAD moved past the CAS's base without it: it can never land. l.abortCut(all) + l.dropIntent(ctx, intent) if l.supersededBy(cur) { l.stMu.Lock() l.fenced = true @@ -776,7 +813,7 @@ func sameProposal(cur, next chunkHead) bool { // resolvePending re-reads HEAD when an earlier CAS outcome is unresolved. func (l *chunkLayerImpl) resolvePending(ctx context.Context) error { l.stMu.Lock() - pending, base := l.pending, l.pendingBase + pending, base, intent := l.pending, l.pendingBase, l.pendingIntent l.stMu.Unlock() if pending == nil { return nil @@ -806,9 +843,11 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) error { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown) } } + // Settled: the proposal landed or can never land. + l.dropIntent(ctx, intent) l.stMu.Lock() defer l.stMu.Unlock() - l.pending = nil + l.pending, l.pendingIntent = nil, "" wasDetach, cut := l.pendingDetach, l.pendingCut l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} switch { @@ -831,6 +870,31 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) error { return nil } +// dropIntent deletes this layer's own intent id (none if empty) once its +// cut is settled. A failed delete is kept and retried by the next cut; it +// never fails a cut whose outcome is already settled. +func (l *chunkLayerImpl) dropIntent(ctx context.Context, id string) { + if id == "" { + return + } + if err := l.remote.DeleteIntent(ctx, id); err != nil { + l.stMu.Lock() + l.leftoverIntents = append(l.leftoverIntents, id) + l.stMu.Unlock() + } +} + +// retryLeftoverIntents retries the deletes dropIntent could not make. +func (l *chunkLayerImpl) retryLeftoverIntents(ctx context.Context) { + l.stMu.Lock() + ids := l.leftoverIntents + l.leftoverIntents = nil + l.stMu.Unlock() + for _, id := range ids { + l.dropIntent(ctx, id) + } +} + // abortCut returns a failed cut's chunks to the dirty set. func (l *chunkLayerImpl) abortCut(all bool) { l.stMu.Lock() diff --git a/seaweed-block/core/storage/chunk_layer_intent_test.go b/seaweed-block/core/storage/chunk_layer_intent_test.go index ecbdb28bd7..1517f2cf30 100644 --- a/seaweed-block/core/storage/chunk_layer_intent_test.go +++ b/seaweed-block/core/storage/chunk_layer_intent_test.go @@ -128,8 +128,8 @@ func TestChunkIntent_FailedPutIntentUploadsNothing(t *testing.T) { f.failPutIntent = errors.New("injected PutIntent failure") f.mu.Unlock() mark := len(f.stats().ops) - if _, err := layer.Cut(ctTimeout(t)); err == nil { - t.Fatal("cut succeeded although its intent could not be written") + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkRemoteUnavailable) { + t.Fatalf("cut with a failed intent write: %v; want a remote-unavailable refusal", err) } if got := uploadedKeys(opsSince(f, mark)); len(got) != 0 { t.Fatalf("chunks uploaded without an intent: %q", got) @@ -154,8 +154,8 @@ func TestChunkIntent_FailedUploadDeletesIntent(t *testing.T) { f.mu.Lock() f.failPut = errors.New("injected upload failure") f.mu.Unlock() - if _, err := layer.Cut(ctTimeout(t)); err == nil { - t.Fatal("cut succeeded although its upload failed") + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkRemoteUnavailable) { + t.Fatalf("cut with a failed upload: %v; want a remote-unavailable refusal", err) } in := lastPutIntent(t, f) if live := liveIntents(t, f); len(live) != 0 { From d3de789471a600b7961d97a863a83dd6f1e293ba Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 09:01:13 -0800 Subject: [PATCH 03/14] test(gc): expose missing in-flight intent protection in initial collector candidate --- seaweed-block/core/frontend/chunkstore/gc.go | 247 ++++++++++++++++++ .../core/frontend/chunkstore/gc_test.go | 166 ++++++++++++ 2 files changed, 413 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/gc.go create mode 100644 seaweed-block/core/frontend/chunkstore/gc_test.go diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go new file mode 100644 index 0000000000..b584a822de --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -0,0 +1,247 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "net/url" + "path" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/protobuf/proto" +) + +const extGCDeleted = "swb.gc.deleted" + +// BlobDeleter deletes one immutable needle. Missing needles are success. +// Implementations must not reuse a deleted fid. +type BlobDeleter interface { + DeleteBlob(context.Context, string) error +} + +// GCConfig binds a collector to the authoritative blockmaster epoch reader. +// IssuedEpoch must read the highest epoch issued for this volume, never a +// lease expiry or a cached guess. Unknown authority retains the intent. +type GCConfig struct { + Grace, IntentTTL time.Duration + IssuedEpoch func(context.Context, string) (uint64, error) + Now func() time.Time +} + +type GCResult struct { + Volumes, Intents, ExpiredIntents, Candidates, Reclaimed int + // Pre-binding needles cannot be enumerated by this API. They are retained; + // UnknownUnbound is true rather than inventing a report-only count. + UnknownUnbound bool +} + +type gcCandidate struct { + since time.Time + digest [32]byte +} +type gcBinding struct { + volume, key string + entry *filerpb.Entry + digest [32]byte +} +type gcIntent struct { + remote *ChunkRemote + intent storage.ChunkIntent +} + +// Collector traces all catalog roots. Calls are serialized per collector; +// restarting loses candidates, which adds delay rather than authorizing a +// deletion. No WAL, publication or shard lock is held during remote I/O. +// Different collectors may duplicate idempotent blob deletes but cannot +// shorten either collector's independent two-mark grace requirement. +type Collector struct { + cat *Catalog + blobs BlobDeleter + cfg GCConfig + mu sync.Mutex + candidates map[string]gcCandidate + last time.Time +} + +func NewCollector(cat *Catalog, blobs BlobDeleter, cfg GCConfig) (*Collector, error) { + if cat == nil || blobs == nil || cfg.Grace <= cat.deadline() || cfg.IntentTTL <= 0 || cfg.IssuedEpoch == nil { + return nil, errors.New("chunkstore: GC requires catalog, blob deletion, grace > operation deadline, positive intent TTL and epoch authority") + } + if cfg.Now == nil { + cfg.Now = time.Now + } + return &Collector{cat: cat, blobs: blobs, cfg: cfg, candidates: map[string]gcCandidate{}}, nil +} + +// Run completes a mark before any chunk deletion. Any failed mark discards +// previous candidates. Roots include active and deleting snapshots until +// the catalog has actually removed them; this collector never infers their +// absence from an age or a retention label. +func (g *Collector) Run(ctx context.Context) (result GCResult, err error) { + g.mu.Lock() + defer g.mu.Unlock() + result.UnknownUnbound = true + defer func() { + if err != nil { + g.candidates = map[string]gcCandidate{} + } + }() + start := g.cfg.Now() + if !g.last.IsZero() && start.Before(g.last) { + return result, errors.New("chunkstore: GC clock moved backwards") + } + roots := map[string]bool{} + var bindings []gcBinding + var expired []gcIntent + volumes, err := g.cat.ListVolumes(ctx) + if err != nil { + return result, err + } + result.Volumes = len(volumes) + for _, vol := range volumes { + r, e := NewChunkRemote(g.cat.f, nilBlobs{}, path.Join(g.cat.base, vol)) + if e != nil { + return result, e + } + h, e := r.GetHead(ctx) + if e != nil { + return result, e + } + addHead := func(head storage.ChunkHead) error { + for _, ref := range head.Chunks { + dir, name, e := r.keyLocation(ref.Key) + if e != nil { + return e + } + roots[path.Join(dir, name)] = true + } + return nil + } + if e = addHead(h); e != nil { + return result, e + } + after := "" + for { + snaps, next, e := g.cat.ListSnapshots(ctx, vol, ListOptions{StartAfter: after, IncludeDeleting: true, Limit: maxListLimit}) + if e != nil { + return result, e + } + for _, snap := range snaps { + if e = addHead(snap.Head()); e != nil { + return result, e + } + } + if next == "" { + break + } + if next <= after { + return result, errors.New("chunkstore: non-advancing snapshot listing") + } + after = next + } + intents, e := r.ListIntents(ctx) + if e != nil { + return result, e + } + for _, in := range intents { + result.Intents++ + // Initial candidate intentionally retains all intents. The caller RED + // proves omitting these roots deletes a stalled cut's uploaded bytes. + _ = in + } + pageAfter := "" + for { + page, e := g.cat.f.ListEntries(ctx, r.keyDir(), "", pageAfter, listPage) + if e != nil { + return result, e + } + for _, entry := range page { + if entry.GetName() <= pageAfter || entry.GetIsDirectory() || len(entry.GetChunks()) != 0 || string(entry.Extended[extKind]) != kindChunkKey || len(entry.Extended[extFid]) == 0 || entry.Attributes == nil || entry.Attributes.Crtime <= 0 { + return result, fmt.Errorf("chunkstore: invalid GC binding %s/%s", r.keyDir(), entry.GetName()) + } + key, e := url.PathUnescape(entry.GetName()) + if e != nil { + return result, e + } + dir, name, e := r.keyLocation(key) + if e != nil || dir != r.keyDir() || name != entry.GetName() { + return result, errors.New("chunkstore: noncanonical GC binding") + } + raw, e := proto.MarshalOptions{Deterministic: true}.Marshal(entry) + if e != nil { + return result, e + } + bindings = append(bindings, gcBinding{vol, key, entry, sha256.Sum256(raw)}) + pageAfter = entry.GetName() + } + if len(page) < listPage { + break + } + } + } + if g.cfg.Now().Sub(start)+g.cat.deadline() >= g.cfg.Grace { + return result, errors.New("chunkstore: GC mark exceeded grace safety margin") + } + // An intent is retired only after the complete mark and confirmed fencing. + for _, x := range expired { + if err = x.remote.DeleteIntent(ctx, x.intent.ID); err != nil { + return result, err + } + result.ExpiredIntents++ + } + nextCandidates := map[string]gcCandidate{} + for _, b := range bindings { + p := path.Join(g.cat.base, b.volume, keysDir, b.entry.Name) + if roots[p] { + if string(b.entry.Extended[extGCDeleted]) == "1" { + return result, fmt.Errorf("chunkstore: root references reclaimed binding %s", p) + } + continue + } + created := time.Unix(b.entry.Attributes.Crtime, 0) + if !start.After(created.Add(g.cfg.Grace)) { + continue + } + candidate, seen := g.candidates[p] + if !seen || candidate.digest != b.digest { + candidate = gcCandidate{start, b.digest} + } + result.Candidates++ + if start.Sub(candidate.since) < g.cfg.Grace { + nextCandidates[p] = candidate + continue + } + // Preserve the immutable binding forever: removing it would allow Put + // to rebind a key that once existed. The tombstone also permits retry + // after a failed physical delete without losing the fid. + if string(b.entry.Extended[extGCDeleted]) != "1" { + e := proto.Clone(b.entry).(*filerpb.Entry) + e.Extended[extGCDeleted] = []byte("1") + expected := map[string][]byte{extKind: []byte(kindChunkKey), extFid: b.entry.Extended[extFid], extGCDeleted: nil} + if err = g.cat.f.UpdateEntry(ctx, path.Dir(p), e, expected); err != nil { + return result, err + } + } + if err = g.blobs.DeleteBlob(ctx, string(b.entry.Extended[extFid])); err != nil { + return result, err + } + result.Reclaimed++ + } + g.candidates = nextCandidates + g.last = start + return result, nil +} + +// nilBlobs is used only for read-only metadata traversal, never chunk I/O. +type nilBlobs struct{} + +func (nilBlobs) Put(context.Context, []byte) (string, error) { + return "", errors.New("chunkstore: metadata-only remote") +} +func (nilBlobs) Get(context.Context, string) ([]byte, error) { + return nil, errors.New("chunkstore: metadata-only remote") +} diff --git a/seaweed-block/core/frontend/chunkstore/gc_test.go b/seaweed-block/core/frontend/chunkstore/gc_test.go new file mode 100644 index 0000000000..0c214794b1 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/gc_test.go @@ -0,0 +1,166 @@ +package chunkstore + +import ( + "bytes" + "context" + "errors" + "path" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type gcBlobs struct{ *fakeBlobs } + +func (b gcBlobs) DeleteBlob(_ context.Context, fid string) error { + b.mu.Lock() + defer b.mu.Unlock() + delete(b.data, fid) + return nil +} + +type heldGCRemote struct { + *ChunkRemote + entered chan struct{} + release chan struct{} +} + +func (r *heldGCRemote) CASHead(ctx context.Context, v storage.ChunkHeadVersion, h storage.ChunkHead) (uint64, error) { + close(r.entered) + select { + case <-r.release: + case <-ctx.Done(): + return 0, ctx.Err() + } + return r.ChunkRemote.CASHead(ctx, v, h) +} + +func gcFixture(t *testing.T) (*fakeFiler, gcBlobs, *Catalog, *Collector, *time.Time) { + t.Helper() + f, b := newFakeFiler(), gcBlobs{newFakeBlobs()} + c := newCat(t, f) + if e := f.CreateEntry(context.Background(), catBase, &filerpb.Entry{Name: "v1", IsDirectory: true}, true); e != nil { + t.Fatal(e) + } + if _, e := c.EnsureVolume(context.Background(), "v1", catGeo); e != nil { + t.Fatal(e) + } + now := time.Now().Add(24 * time.Hour) + g, e := NewCollector(c, b, GCConfig{Grace: time.Hour, IntentTTL: time.Hour, Now: func() time.Time { return now }, IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }}) + if e != nil { + t.Fatal(e) + } + return f, b, c, g, &now +} + +func TestGC_StalledCutRemainsReadableAfterTwoMarks(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + remote, e := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if e != nil { + t.Fatal(e) + } + held := &heldGCRemote{remote, make(chan struct{}), make(chan struct{})} + p := filepath.Join(t.TempDir(), "volume") + s, e := storage.CreateWALStore(p, 64, 4096) + if e != nil { + t.Fatal(e) + } + defer s.Close() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + layer, e := storage.AttachChunkLayer(s, held, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", Bitmap: storage.NewFileChunkBitmapStore(p + ".bitmap")}) + if e != nil { + t.Fatal(e) + } + want := bytes.Repeat([]byte{0x71}, 4096) + if _, e = s.Write(0, want); e != nil { + t.Fatal(e) + } + done := make(chan error, 1) + go func() { _, e := layer.Capture(ctx); done <- e }() + select { + case <-held.entered: + case <-ctx.Done(): + t.Fatal("cut never reached post-upload CAS") + } + // Always release the owned cut before Close, including a failing assertion. + released := false + defer func() { + if !released { + close(held.release) + <-done + } + }() + for i := 0; i < 2; i++ { + result, e := g.Run(ctx) + if e != nil { + t.Fatal(e) + } + t.Logf("mark %d: %+v", i+1, result) + *now = now.Add(time.Hour + time.Second) + } + close(held.release) + released = true + if e := <-done; e != nil { + t.Fatal(e) + } + h, e := remote.GetHead(ctx) + if e != nil || h.Gen == 0 { + t.Fatalf("published HEAD: %+v %v", h, e) + } + for _, ref := range h.Chunks { + got, e := remote.Get(ctx, ref.Key) + if e != nil || !bytes.Equal(got[:min(len(got), 4096)], want) { + t.Fatalf("published HEAD references deleted or corrupt stalled-cut chunk: key=%q bytes=%d err=%v", ref.Key, len(got), e) + } + } +} + +func TestGC_UnreachableRequiresTwoMarksAndUploadAge(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if e := r.Put(ctx, "orphan", []byte("exact orphan")); e != nil { + t.Fatal(e) + } + if _, e := g.Run(ctx); e != nil { + t.Fatal(e) + } + *now = now.Add(time.Hour - time.Second) + if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 { + t.Fatalf("early second mark: %+v %v", result, e) + } + if _, e := r.Get(ctx, "orphan"); e != nil { + t.Fatal("orphan deleted before grace", e) + } + *now = now.Add(2 * time.Second) + result, e := g.Run(ctx) + if e != nil || result.Reclaimed != 1 { + t.Fatalf("old unreachable chunk was not reclaimed after grace-separated marks: %+v %v", result, e) + } + if _, e := r.Get(ctx, "orphan"); e == nil { + t.Fatal("reclaimed orphan remains readable") + } + fresh, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if e := fresh.Put(ctx, "orphan", []byte("reused")); !errors.Is(e, storage.ErrChunkKeyExists) { + t.Fatalf("immutable key reused after GC: %v", e) + } + // A freshly uploaded chunk cannot enter its first candidate mark yet. + *now = time.Now() + next, e := NewCollector(g.cat, b, g.cfg) + if e != nil { + t.Fatal(e) + } + if e := r.Put(ctx, "young", []byte("young")); e != nil { + t.Fatal(e) + } + if result, e := next.Run(ctx); e != nil || result.Candidates != 0 { + t.Fatalf("young upload admitted: %+v %v", result, e) + } +} From 68e211a5d9ad7664eb59eb34c54a242e6f88d70a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 09:01:38 -0800 Subject: [PATCH 04/14] fix(gc): root live upload intents and require authoritative epoch fencing for expiry --- seaweed-block/core/frontend/chunkstore/gc.go | 35 +++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index b584a822de..656cad1973 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -149,9 +149,28 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) { } for _, in := range intents { result.Intents++ - // Initial candidate intentionally retains all intents. The caller RED - // proves omitting these roots deletes a stalled cut's uploaded bytes. - _ = in + if in.CreatedNs <= 0 || in.CreatedNs > start.UnixNano() { + return result, errors.New("chunkstore: invalid intent creation time") + } + expire := false + if start.Sub(time.Unix(0, in.CreatedNs)) > g.cfg.IntentTTL { + issued, authorityErr := g.cfg.IssuedEpoch(ctx, vol) + // Both the authority and the actual CAS domain must have + // advanced. Mere lease loss, or issuance without takeover, + // cannot authorize expiry of a paused publisher's intent. + expire = authorityErr == nil && issued > in.Epoch && h.Epoch > in.Epoch && h.Epoch <= issued + } + if expire { + expired = append(expired, gcIntent{r, in}) + } else { + for _, key := range in.Keys { + dir, name, e := r.keyLocation(key) + if e != nil { + return result, e + } + roots[path.Join(dir, name)] = true + } + } } pageAfter := "" for { @@ -197,11 +216,14 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) { for _, b := range bindings { p := path.Join(g.cat.base, b.volume, keysDir, b.entry.Name) if roots[p] { - if string(b.entry.Extended[extGCDeleted]) == "1" { + if len(b.entry.Extended[extGCDeleted]) != 0 { return result, fmt.Errorf("chunkstore: root references reclaimed binding %s", p) } continue } + if string(b.entry.Extended[extGCDeleted]) == "done" { + continue + } created := time.Unix(b.entry.Attributes.Crtime, 0) if !start.After(created.Add(g.cfg.Grace)) { continue @@ -229,6 +251,11 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) { if err = g.blobs.DeleteBlob(ctx, string(b.entry.Extended[extFid])); err != nil { return result, err } + e := proto.Clone(b.entry).(*filerpb.Entry) + e.Extended[extGCDeleted] = []byte("done") + if err = g.cat.f.UpdateEntry(ctx, path.Dir(p), e, map[string][]byte{extFid: b.entry.Extended[extFid], extGCDeleted: []byte("1")}); err != nil { + return result, err + } result.Reclaimed++ } g.candidates = nextCandidates From 4ff1211d6ddf0e4aac3f56c3bc2c158aab604293 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 09:02:50 -0800 Subject: [PATCH 05/14] test(gc): cover fencing, snapshot roots, failed marks and restart safety --- .../core/frontend/chunkstore/gc_test.go | 138 ++++++++++++++++++ .../core/frontend/chunkstore/swfs.go | 29 ++++ 2 files changed, 167 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/gc_test.go b/seaweed-block/core/frontend/chunkstore/gc_test.go index 0c214794b1..05e49c95bb 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_test.go @@ -164,3 +164,141 @@ func TestGC_UnreachableRequiresTwoMarksAndUploadAge(t *testing.T) { t.Fatalf("young upload admitted: %+v %v", result, e) } } + +func TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence(t *testing.T) { + for _, tc := range []struct { + name string + issued, head uint64 + age time.Duration + authorityErr bool + expire bool + }{ + {"current-holder-old-intent", 1, 1, 2 * time.Hour, false, false}, + {"higher-issued-but-no-takeover", 2, 1, 2 * time.Hour, false, false}, + {"takeover-but-no-authority", 1, 2, 2 * time.Hour, false, false}, + {"unknown-authority", 2, 2, 2 * time.Hour, true, false}, + {"TTL-not-exceeded", 2, 2, time.Hour, false, false}, + {"higher-issued-and-fenced", 2, 2, time.Hour + time.Nanosecond, false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if e := r.Put(ctx, "inflight", []byte("protected")); e != nil { + t.Fatal(e) + } + id, e := r.PutIntent(ctx, storage.ChunkIntent{Gen: 0, Epoch: 1, Holder: "h1", Keys: []string{"inflight"}}) + if e != nil { + t.Fatal(e) + } + ins, e := r.ListIntents(ctx) + if e != nil || len(ins) != 1 { + t.Fatalf("intent: %+v %v", ins, e) + } + *now = time.Unix(0, ins[0].CreatedNs).Add(tc.age) + // A real remote HEAD fence. The publisher's original expected version + // can no longer install after epoch 2 was published. + if _, e = r.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: tc.head, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); e != nil { + t.Fatal(e) + } + g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { + if tc.authorityErr { + return 0, errors.New("authority unavailable") + } + return tc.issued, nil + } + result, e := g.Run(ctx) + if e != nil { + t.Fatal(e) + } + ins, e = r.ListIntents(ctx) + if e != nil { + t.Fatal(e) + } + if (len(ins) == 0) != tc.expire { + t.Fatalf("intent %s expired=%v want=%v; %+v", id, len(ins) == 0, tc.expire, result) + } + if result.Reclaimed != 0 { + t.Fatal("one mark reclaimed bytes") + } + if tc.expire { + _, e = r.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "h1"}) + if !errors.Is(e, storage.ErrChunkHeadPrecondition) { + t.Fatalf("expired publisher can still CAS: %v", e) + } + } + }) + } +} + +type failingGCListing struct { + Filer + fail bool +} + +func (f *failingGCListing) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + if f.fail { + return nil, errors.New("listing unavailable") + } + return f.Filer.ListEntries(ctx, dir, prefix, after, limit) +} +func TestGC_FailedMarkAndRestartNeverReuseCoverage(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if e := r.Put(ctx, "orphan", []byte("orphan")); e != nil { + t.Fatal(e) + } + wrapper := &failingGCListing{Filer: f} + c.f = wrapper + if _, e := g.Run(ctx); e != nil { + t.Fatal(e) + } + *now = now.Add(2 * time.Hour) + wrapper.fail = true + if _, e := g.Run(ctx); e == nil { + t.Fatal("failed listing accepted") + } + wrapper.fail = false + if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 { + t.Fatalf("failed mark preserved coverage: %+v %v", result, e) + } + fresh, e := NewCollector(c, b, g.cfg) + if e != nil { + t.Fatal(e) + } + *now = now.Add(2 * time.Hour) + if result, e := fresh.Run(ctx); e != nil || result.Reclaimed != 0 { + t.Fatalf("restart inferred prior mark: %+v %v", result, e) + } +} + +func TestGC_SnapshotAndQualifiedForkAreRoots(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x21)}) + if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); e != nil { + t.Fatal(e) + } + if _, e := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); e != nil { + t.Fatal(e) + } + if _, e := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); e != nil { + t.Fatal(e) + } + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if _, e := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1", Chunks: map[uint64]storage.ChunkRef{}}); e != nil { + t.Fatal(e) + } + for i := 0; i < 2; i++ { + if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 { + t.Fatalf("rooted data reclaimed: %+v %v", result, e) + } + *now = now.Add(2 * time.Hour) + } + for _, ref := range h.Chunks { + if got, e := r.Get(ctx, ref.Key); e != nil || !bytes.Equal(got, chunkBytes(0x21)) { + t.Fatalf("shared bytes: %v", e) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/swfs.go b/seaweed-block/core/frontend/chunkstore/swfs.go index d783b5745f..c3c375df50 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs.go +++ b/seaweed-block/core/frontend/chunkstore/swfs.go @@ -319,3 +319,32 @@ var ( _ Filer = (*SWFS)(nil) _ Blobs = (*SWFS)(nil) ) + +// DeleteBlob removes an immutable needle from every resolved replica. A +// partial/unknown result is an error, so GC retains its binding tombstone +// and retries later; no response body is used to infer success. +func (c *SWFS) DeleteBlob(ctx context.Context, fid string) error { + vid, needle, ok := strings.Cut(fid, ",") + if !ok || vid == "" || needle == "" || strings.ContainsAny(fid, "/\\?#% \r\n") { + return fmt.Errorf("chunkstore: bad deletion fid %q", fid) + } + urls, err := c.lookupVolume(ctx, vid) + if err != nil { + return err + } + for _, host := range urls { + req, err := http.NewRequestWithContext(ctx, http.MethodDelete, "http://"+host+"/"+fid, nil) + if err != nil { + return err + } + resp, err := c.http.Do(req) + if err != nil { + return err + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("chunkstore: delete %s: http %d", fid, resp.StatusCode) + } + } + return nil +} From 9206e11319cd3b8c4573906fbc929561dd9d6c62 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 09:03:00 -0800 Subject: [PATCH 06/14] test(gc): correct directory fixture create result --- seaweed-block/core/frontend/chunkstore/gc_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/chunkstore/gc_test.go b/seaweed-block/core/frontend/chunkstore/gc_test.go index 05e49c95bb..b727aaf6aa 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_test.go @@ -280,7 +280,7 @@ func TestGC_SnapshotAndQualifiedForkAreRoots(t *testing.T) { if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); e != nil { t.Fatal(e) } - if _, e := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); e != nil { + if e := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); e != nil { t.Fatal(e) } if _, e := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); e != nil { From 5198672a08d7a6356e2e44d7fc3749c812189ec3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 09:04:32 -0800 Subject: [PATCH 07/14] fix(gc): retain epochless catalog copy intents and validate blob deletion responses --- seaweed-block/core/frontend/chunkstore/gc.go | 15 +++-- .../core/frontend/chunkstore/gc_test.go | 58 +++++++++++++++++++ 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 656cad1973..fbcf731ad0 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -7,6 +7,7 @@ import ( "fmt" "net/url" "path" + "strings" "sync" "time" @@ -44,9 +45,9 @@ type gcCandidate struct { digest [32]byte } type gcBinding struct { - volume, key string - entry *filerpb.Entry - digest [32]byte + volume string + entry *filerpb.Entry + digest [32]byte } type gcIntent struct { remote *ChunkRemote @@ -153,9 +154,11 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) { return result, errors.New("chunkstore: invalid intent creation time") } expire := false - if start.Sub(time.Unix(0, in.CreatedNs)) > g.cfg.IntentTTL { + if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") && start.Sub(time.Unix(0, in.CreatedNs)) > g.cfg.IntentTTL { issued, authorityErr := g.cfg.IssuedEpoch(ctx, vol) - // Both the authority and the actual CAS domain must have + // Catalog copy intents are retained: their exclusive creates + // are not epoch-fenced. For a capture, both the authority + // and the actual CAS domain must have // advanced. Mere lease loss, or issuance without takeover, // cannot authorize expiry of a paused publisher's intent. expire = authorityErr == nil && issued > in.Epoch && h.Epoch > in.Epoch && h.Epoch <= issued @@ -194,7 +197,7 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) { if e != nil { return result, e } - bindings = append(bindings, gcBinding{vol, key, entry, sha256.Sum256(raw)}) + bindings = append(bindings, gcBinding{vol, entry, sha256.Sum256(raw)}) pageAfter = entry.GetName() } if len(page) < listPage { diff --git a/seaweed-block/core/frontend/chunkstore/gc_test.go b/seaweed-block/core/frontend/chunkstore/gc_test.go index b727aaf6aa..52b42feccf 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_test.go @@ -4,8 +4,11 @@ import ( "bytes" "context" "errors" + "net/http" + "net/http/httptest" "path" "path/filepath" + "strings" "testing" "time" @@ -302,3 +305,58 @@ func TestGC_SnapshotAndQualifiedForkAreRoots(t *testing.T) { } } } + +func TestGC_CopyIntentSurvivesTakeover(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + for _, holder := range []string{"snapshot:v1/s1/req", "fork:v1/req"} { + if _, e := r.PutIntent(ctx, storage.ChunkIntent{Gen: 0, Epoch: 1, Holder: holder, Keys: []string{"k"}}); e != nil { + t.Fatal(e) + } + } + if _, e := r.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 2, Holder: "new"}); e != nil { + t.Fatal(e) + } + g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil } + *now = now.Add(24 * time.Hour) + if result, e := g.Run(ctx); e != nil || result.ExpiredIntents != 0 { + t.Fatalf("epochless copy publication lost its protection: %+v %v", result, e) + } + intents, e := r.ListIntents(ctx) + if e != nil || len(intents) != 2 { + t.Fatalf("copy intents: %+v %v", intents, e) + } +} + +func TestSWFS_DeleteBlobStatusesAndExactPath(t *testing.T) { + for _, status := range []int{200, 204, 404, 401, 500} { + t.Run(http.StatusText(status), func(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + if r.Method != "DELETE" || r.URL.Path != "/7,01abcdef" { + t.Errorf("unexpected delete %s %s", r.Method, r.URL.Path) + } + w.WriteHeader(status) + })) + defer server.Close() + c := &SWFS{http: server.Client(), vidCache: map[string][]string{"7": {strings.TrimPrefix(server.URL, "http://")}}} + e := c.DeleteBlob(context.Background(), "7,01abcdef") + if (e == nil) != (status == 200 || status == 204 || status == 404) { + t.Fatalf("status %d: %v", status, e) + } + if calls != 1 { + t.Fatalf("calls %d", calls) + } + for _, bad := range []string{"7,../bad", "7,a?bad", "7,a%2fb", "", ",a"} { + if e := c.DeleteBlob(context.Background(), bad); e == nil { + t.Errorf("invalid fid accepted: %q", bad) + } + } + if calls != 1 { + t.Fatal("invalid fid dispatched HTTP") + } + }) + } +} From b26dcade9a9564589335f2ad6776473f26d4b44c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 09:06:07 -0800 Subject: [PATCH 08/14] docs(gc): record lock order, conservative retention and first-slice evidence limits --- seaweed-block/core/frontend/chunkstore/GC.md | 23 +++++++++++++++++++ .../core/frontend/chunkstore/gc_test.go | 19 +++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/GC.md diff --git a/seaweed-block/core/frontend/chunkstore/GC.md b/seaweed-block/core/frontend/chunkstore/GC.md new file mode 100644 index 0000000000..502402574e --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/GC.md @@ -0,0 +1,23 @@ +# Chunk garbage collection (W5, library slice) + +`NewCollector(catalog, blobDeleter, config).Run(ctx)` traces every volume returned by the catalog, every HEAD, every snapshot (including deleting snapshots), and every live upload/copy intent. Use a deadline-bound context. Supply `IssuedEpoch` from the authoritative blockmaster reader, not lease expiry or a host-local projection. There is no automatic scheduler or destructive CLI in this slice. + +A capture intent can expire only when its age strictly exceeds IntentTTL, the blockmaster has issued a higher epoch, and the actual remote HEAD has advanced to a higher epoch no greater than the issued one. Unknown authority retains it. Snapshot/fork copy intents are retained until the operation settles: their exclusive creates are not fenced by the remote HEAD epoch. This is intentionally conservative pending a shared publication fence for those operations. + +An immutable binding becomes a candidate only when its creation time is strictly older than Grace and no root names it. Reclamation requires another successful mark at least Grace after its first observation with the same binding bytes. A rooted candidate is forgotten; failed marks and collector restart discard coverage. Grace must exceed the catalog operation deadline plus the measured mark duration. Backward clock movement refuses the pass. + +Before physical deletion the binding receives a conditional `swb.gc.deleted=1` tombstone; after every resolved replica deletion succeeds it becomes `done`. Bindings are never removed or rebound. Failed/uncertain blob deletion returns an error and retains the fid for a conservative retry after fresh marks. The SeaweedFS adapter deletes the exact fid, accepts only HTTP 200/204/404, and propagates transport/other HTTP failures. Authenticated deployments must supply a BlobDeleter with their write authorization; this patch does not add an auth provisioning path. + +Unbound needles (upload succeeded but key binding never persisted) are RETAINED. The existing interfaces cannot enumerate/count them, so `UnknownUnbound=true` reports that limitation instead of a fabricated zero. No sweep is attempted. + +## Scope and follow-ups + +This first Draft implements the GC core and the real Capture/intent/HEAD caller regression. Retention (newest N plus logarithmic age buckets), removal of deleting snapshots, workspace tombstoning, CLI scheduling and a concrete blockmaster client binding remain follow-up W5 slices. Deleting snapshots continue to root their data until the catalog actually removes them. This is safe retention, not complete workspace lifecycle acceptance. + +## Lock order + +The new Collector mutex serializes its own passes and candidate state; it never enters WAL, publication, shard or chunk-layer locks. Remote calls execute only while holding that collector-local mutex. Producer Capture already uploads after releasing its capture/publication barrier, so GC adds no edge to the storage lock graph. The epoch-reader and BlobDeleter must not re-enter this Collector. Multiple collectors may repeat idempotent physical deletes, but each must independently satisfy the two-mark grace rule. + +## Evidence boundary + +The assertion RED is an initial GC candidate that already implemented HEAD/snapshot tracing and two marks but omitted intent roots; the base has no GC API to test. It is NOT claimed as a GC bug reproduced on unmodified main. The same test holds the shipping Capture before CAS after real immutable uploads, runs two GC marks, resumes CAS, and reads exact bytes through ChunkRemote. Filer/needle services are deterministic adapters; no SeaweedFS process, hardware, lab or cloud acceptance is claimed. diff --git a/seaweed-block/core/frontend/chunkstore/gc_test.go b/seaweed-block/core/frontend/chunkstore/gc_test.go index 52b42feccf..a0ade3fcde 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_test.go @@ -360,3 +360,22 @@ func TestSWFS_DeleteBlobStatusesAndExactPath(t *testing.T) { }) } } + +func TestGC_UnboundNeedleRetainedAndCountUnknown(t *testing.T) { + _, b, _, g, now := gcFixture(t) + ctx := context.Background() + fid, e := b.Put(ctx, []byte("pre-binding orphan")) + if e != nil { + t.Fatal(e) + } + for i := 0; i < 3; i++ { + result, e := g.Run(ctx) + if e != nil || !result.UnknownUnbound || result.Reclaimed != 0 { + t.Fatalf("unbound inventory claim: %+v %v", result, e) + } + *now = now.Add(2 * time.Hour) + } + if got, e := b.Get(ctx, fid); e != nil || string(got) != "pre-binding orphan" { + t.Fatalf("unbound orphan deleted: %q %v", got, e) + } +} From 68f98a0ff581eaca827d30aec27118aa95c3c669 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 09:49:43 -0800 Subject: [PATCH 09/14] test(gc): require permanent snapshot claim before releasing dead copy intent --- .../core/frontend/chunkstore/gc_copy.go | 7 ++ .../core/frontend/chunkstore/gc_copy_test.go | 66 +++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/gc_copy.go create mode 100644 seaweed-block/core/frontend/chunkstore/gc_copy_test.go diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy.go b/seaweed-block/core/frontend/chunkstore/gc_copy.go new file mode 100644 index 0000000000..233f846e14 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/gc_copy.go @@ -0,0 +1,7 @@ +package chunkstore + +import "context" + +// SweepCopies settles expired copy attempts using permanent publication +// target claims; it never expires them from a deadline alone. +func (g *Collector) SweepCopies(ctx context.Context) (int, error) { return 0, nil } diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go new file mode 100644 index 0000000000..fcf55f4836 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go @@ -0,0 +1,66 @@ +package chunkstore + +import ( + "context" + "path" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func snapshotDir(t *testing.T, f *fakeFiler, vol, name string) { + t.Helper() + if e := f.CreateEntry(context.Background(), path.Join(catBase, vol, snapsDir), &filerpb.Entry{Name: name, IsDirectory: true}, true); e != nil { + t.Fatal(e) + } +} + +func TestGC_CopySweepClaimsSnapshotAttemptBeforeRelease(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + c.SetClock(func() time.Time { return *now }) + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x31)}) + snapshotDir(t, f, "v1", "s1") + holdFirst(f, path.Join(catBase, "v1", snapsDir, "s1")+"/") + if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "dead"}, h); CodeOf(e) != CodeOutcomeUnknown { + t.Fatalf("held snapshot: %v", e) + } + oldPath := snapPath(t, f, "v1", "s1") + if count, e := g.SweepCopies(ctx); e != nil || count != 0 { + t.Fatalf("early sweep: %d %v", count, e) + } + *now = now.Add(DefaultOpDeadline + time.Second) + if count, e := g.SweepCopies(ctx); e != nil || count != 1 { + t.Fatalf("dead copy intent not settled by tombstone claim: count=%d err=%v", count, e) + } + if ins := intentsOf(t, f, "v1"); len(ins) != 0 { + t.Fatalf("intent retained after target claimed: %+v", ins) + } + e, err := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath)) + if err != nil || string(e.Extended[extSnapState]) != SnapAborted { + t.Fatalf("permanent claim missing: %v", err) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatal(err) + } + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "new"}, h); err != nil { + t.Fatal(err) + } + if p := snapPath(t, f, "v1", "s1"); p == oldPath { + t.Fatal("reused permanent attempt path") + } + if applied := f.releaseDeferredCreates(); applied != 0 { + t.Fatalf("late old snapshot insert landed after name reuse: %d", applied) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "newfork", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + // The new name resolves to its new published attempt, never old tombstone. + info, err := c.readSnap(ctx, "v1", "s1") + if err != nil || info.Head().Gen != h.Gen { + t.Fatalf("new snapshot: %+v %v", info, err) + } + _ = storage.ChunkHead{} +} From 0aa9344cfe23230153b34b5ee8f3640418b88046 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 09:50:45 -0800 Subject: [PATCH 10/14] feat(gc): settle dead copy intents through permanent final-target claims --- seaweed-block/core/frontend/chunkstore/gc.go | 9 + .../core/frontend/chunkstore/gc_copy.go | 179 +++++++++++++++++- .../core/frontend/chunkstore/gc_copy_test.go | 2 - 3 files changed, 185 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index fbcf731ad0..cd783ad7c9 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -144,6 +144,15 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) { } after = next } + attempts, e := g.snapshotAttemptHeads(ctx, vol, start) + if e != nil { + return result, e + } + for _, head := range attempts { + if e = addHead(head); e != nil { + return result, e + } + } intents, e := r.ListIntents(ctx) if e != nil { return result, e diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy.go b/seaweed-block/core/frontend/chunkstore/gc_copy.go index 233f846e14..1ef7bfa368 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy.go @@ -1,7 +1,180 @@ package chunkstore -import "context" +import ( + "context" + "errors" + "fmt" + "path" + "strconv" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) // SweepCopies settles expired copy attempts using permanent publication -// target claims; it never expires them from a deadline alone. -func (g *Collector) SweepCopies(ctx context.Context) (int, error) { return 0, nil } +// target claims; a deadline only admits a claim, never releases protection. +// It shares the collector pass mutex but acquires no storage locks. +func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) { + g.mu.Lock() + defer g.mu.Unlock() + now := g.cfg.Now() + vols, err := g.cat.ListVolumes(ctx) + if err != nil { + return 0, err + } + type copyAttempt struct { + vol string + remote *ChunkRemote + in storage.ChunkIntent + } + var pending []copyAttempt + for _, vol := range vols { + r, e := NewChunkRemote(g.cat.f, nilBlobs{}, path.Join(g.cat.base, vol)) + if e != nil { + return 0, e + } + intents, e := r.ListIntents(ctx) + if e != nil { + return 0, e + } + for _, in := range intents { + if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") { + continue + } + if in.CreatedNs <= 0 || in.CreatedNs > now.UnixNano() { + return 0, errors.New("chunkstore: invalid copy intent creation time") + } + if in.DeadlineNs <= 0 || now.UnixNano() <= in.DeadlineNs { + continue + } + pending = append(pending, copyAttempt{vol, r, in}) + } + } + for _, a := range pending { + if err = ctx.Err(); err != nil { + return settled, err + } + if strings.HasPrefix(a.in.Holder, "snapshot:") { + parts := strings.Split(strings.TrimPrefix(a.in.Holder, "snapshot:"), "/") + if len(parts) != 3 || parts[0] != a.vol || CheckSnapshotName(parts[1]) != nil || !storage.ValidChunkIntentID(parts[2]) { + return settled, fmt.Errorf("chunkstore: malformed snapshot intent %s", a.in.ID) + } + // Claim the final attempt, never the reusable name record. + if _, err = g.cat.AbortSnapshot(ctx, a.vol, parts[1], parts[2]); err != nil { + return settled, err + } + dir := path.Join(g.cat.base, a.vol, snapsDir, parts[1]) + e, readErr := g.cat.f.LookupEntry(ctx, dir, parts[2]) + if readErr != nil { + return settled, readErr + } + info, _, readErr := decodeSnap(path.Join(dir, parts[2]), e) + if readErr != nil { + return settled, readErr + } + if info.VolumeID != a.vol || info.Name != parts[1] || string(e.Extended[extAttempt]) != parts[2] { + return settled, errors.New("chunkstore: copy claim identity mismatch") + } + } else { + parts := strings.SplitN(strings.TrimPrefix(a.in.Holder, "fork:"), "/", 2) + if len(parts) != 2 || parts[0] != a.vol || parts[1] == "" { + return settled, fmt.Errorf("chunkstore: malformed fork intent %s", a.in.ID) + } + v, ok, readErr := g.cat.ReadVolume(ctx, a.vol) + if readErr != nil { + return settled, readErr + } + if !ok || v.Origin != OriginFork || v.Fork == nil || v.Fork.RequestID != parts[1] { + return settled, errors.New("chunkstore: fork intent has no matching target VOLUME") + } + if _, err = g.cat.AbortFork(ctx, a.vol); err != nil { + return settled, err + } + h, ok, readErr := g.cat.ReadHead(ctx, a.vol) + if readErr != nil { + return settled, readErr + } + if !ok || h.Gen == 0 { + return settled, errors.New("chunkstore: fork claim did not settle the publishing HEAD") + } + } + // Both a valid published immutable entry and a valid permanent aborted + // entry settle this attempt. Unknown claim/read never drops its intent. + if err = a.remote.DeleteIntent(ctx, a.in.ID); err != nil { + return settled, err + } + settled++ + } + return settled, nil +} + +func (g *Collector) gcEntries(ctx context.Context, dir string) ([]*filerpb.Entry, error) { + var out []*filerpb.Entry + after := "" + for { + page, err := g.cat.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return nil, err + } + for _, e := range page { + if e.GetName() <= after || path.Base(e.GetName()) != e.GetName() { + return nil, errors.New("chunkstore: invalid/non-advancing GC directory listing") + } + after = e.Name + out = append(out, e) + } + if len(page) < listPage { + return out, nil + } + } +} + +// snapshotAttemptHeads includes unnamed attempts left behind by DeleteSnapshot. +// Attempt entries are permanent. A deleting attempt stops rooting its keys +// only after its deleting timestamp ages past grace; ordinary two marks +// still apply afterward. An aborted attempt roots no keys. +func (g *Collector) snapshotAttemptHeads(ctx context.Context, vol string, now time.Time) ([]storage.ChunkHead, error) { + root := path.Join(g.cat.base, vol, snapsDir) + dirs, err := g.gcEntries(ctx, root) + if err != nil { + return nil, err + } + var heads []storage.ChunkHead + for _, dir := range dirs { + if !dir.GetIsDirectory() || CheckSnapshotName(dir.Name) != nil { + return nil, errors.New("chunkstore: invalid snapshot attempt directory") + } + entries, err := g.gcEntries(ctx, path.Join(root, dir.Name)) + if err != nil { + return nil, err + } + for _, e := range entries { + if !storage.ValidChunkIntentID(e.Name) || string(e.Extended[extAttempt]) != e.Name { + return nil, errors.New("chunkstore: invalid snapshot attempt identity") + } + info, _, err := decodeSnap(path.Join(root, dir.Name, e.Name), e) + if err != nil { + return nil, err + } + if info.VolumeID != vol || info.Name != dir.Name { + return nil, errors.New("chunkstore: snapshot attempt names another volume/name") + } + if info.State == SnapAborted { + continue + } + if info.State == SnapDeleting { + ns, err := strconv.ParseInt(string(e.Extended[extSnapDeletedNs]), 10, 64) + if err != nil || ns <= 0 || ns > now.UnixNano() { + return nil, errors.New("chunkstore: invalid deleted snapshot timestamp") + } + if now.Sub(time.Unix(0, ns)) > g.cfg.Grace { + continue + } + } + heads = append(heads, info.Head()) + } + } + return heads, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go index fcf55f4836..9aae1be90a 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go @@ -7,7 +7,6 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" ) func snapshotDir(t *testing.T, f *fakeFiler, vol, name string) { @@ -62,5 +61,4 @@ func TestGC_CopySweepClaimsSnapshotAttemptBeforeRelease(t *testing.T) { if err != nil || info.Head().Gen != h.Gen { t.Fatalf("new snapshot: %+v %v", info, err) } - _ = storage.ChunkHead{} } From 03e8253885d12a694b5d1b5fdc4911b9b64c1ee7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 09:51:47 -0800 Subject: [PATCH 11/14] test(gc): cover fork claims, unnamed snapshot grace and unknown settlement --- .../core/frontend/chunkstore/gc_copy_test.go | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go index 9aae1be90a..4f1264caa1 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go @@ -1,7 +1,10 @@ package chunkstore import ( + "bytes" "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/storage" "path" "testing" "time" @@ -62,3 +65,133 @@ func TestGC_CopySweepClaimsSnapshotAttemptBeforeRelease(t *testing.T) { t.Fatalf("new snapshot: %+v %v", info, err) } } + +func TestGC_CopySweepClaimsForkHEADNotExistingVolume(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + c.SetClock(func() time.Time { return *now }) + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)}) + snapshotDir(t, f, "v1", "s1") + if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h); e != nil { + t.Fatal(e) + } + if e := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); e != nil { + t.Fatal(e) + } + holdFirst(f, path.Join(catBase, "v2", headName)) + if _, e := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "dead"}); CodeOf(e) != CodeOutcomeUnknown { + t.Fatalf("held fork: %v", e) + } + if _, ok, e := c.ReadVolume(ctx, "v2"); e != nil || !ok { + t.Fatalf("fixture lacks existing VOLUME: %v", e) + } + if _, ok, e := c.ReadHead(ctx, "v2"); e != nil || ok { + t.Fatalf("held fork already published: %v %v", ok, e) + } + *now = now.Add(DefaultOpDeadline + time.Second) + count, e := g.SweepCopies(ctx) + if e != nil || count != 1 { + t.Fatalf("fork sweep: %d %v", count, e) + } + head, ok, e := c.ReadHead(ctx, "v2") + if e != nil || !ok || head.State != storage.ChunkHeadAborted { + t.Fatalf("final HEAD not claimed: %+v %v", head, e) + } + if n := f.releaseDeferredCreates(); n != 0 { + t.Fatalf("late fork HEAD published over claim: %d", n) + } + if _, e := c.EnsureVolume(ctx, "v2", catGeo); CodeOf(e) != CodeForkIncomplete { + t.Fatalf("aborted target attached: %v", e) + } + if _, e := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "new"}); CodeOf(e) != CodeTargetExists { + t.Fatalf("volume id reused: %v", e) + } +} + +type retainCopyIntent struct{ Filer } + +func (f retainCopyIntent) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { + if path.Base(dir) == intentsDir { + return errors.New("cleanup response unavailable") + } + return f.Filer.DeleteEntry(ctx, dir, name, expected) +} + +func TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + c.SetClock(func() time.Time { return *now }) + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x51)}) + snapshotDir(t, f, "v1", "s1") + c.f = retainCopyIntent{f} + if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "published"}, h); e != nil { + t.Fatal(e) + } + c.f = f + oldPath := snapPath(t, f, "v1", "s1") + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if _, e := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1"}); e != nil { + t.Fatal(e) + } + *now = now.Add(DefaultOpDeadline + time.Second) + if count, e := g.SweepCopies(ctx); e != nil || count != 1 { + t.Fatalf("published copy claim: %d %v", count, e) + } + e, err := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath)) + if err != nil || string(e.Extended[extSnapState]) != SnapActive { + t.Fatalf("published snapshot was overwritten: %v", err) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatal(err) + } + // The name is gone, but its immutable attempt remains a root throughout grace. + if list, _, e := c.ListSnapshots(ctx, "v1", ListOptions{IncludeDeleting: true}); e != nil || len(list) != 0 { + t.Fatalf("name still listed: %+v %v", list, e) + } + for i := 0; i < 2; i++ { + if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 { + t.Fatalf("unnamed deleting attempt lost grace: %+v %v", result, e) + } + *now = now.Add(time.Minute) + } + for _, ref := range h.Chunks { + if got, e := r.Get(ctx, ref.Key); e != nil || !bytes.Equal(got, chunkBytes(0x51)) { + t.Fatalf("snapshot bytes lost: %v", e) + } + } + *now = now.Add(2 * time.Hour) + if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 { + t.Fatalf("first unrooted mark: %+v %v", result, e) + } + *now = now.Add(time.Hour) + if result, e := g.Run(ctx); e != nil || result.Reclaimed != 1 { + t.Fatalf("deleted attempt retained chunks forever: %+v %v", result, e) + } + if _, e := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath)); e != nil { + t.Fatal("permanent attempt entry removed", e) + } +} + +func TestGC_CopyClaimUnknownRetainsIntent(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + c.SetClock(func() time.Time { return *now }) + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x61)}) + snapshotDir(t, f, "v1", "s1") + holdFirst(f, path.Join(catBase, "v1", snapsDir, "s1")+"/") + if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "dead"}, h); CodeOf(e) != CodeOutcomeUnknown { + t.Fatal(e) + } + *now = now.Add(DefaultOpDeadline + time.Second) + f.failCreate = func(string) error { return errors.New("claim outcome unknown") } + if n, e := g.SweepCopies(ctx); e == nil || n != 0 { + t.Fatalf("unknown claim accepted: %d %v", n, e) + } + if ins := intentsOf(t, f, "v1"); len(ins) != 1 { + t.Fatalf("unknown claim released root: %+v", ins) + } + f.failCreate = nil + if n, e := g.SweepCopies(ctx); e != nil || n != 1 { + t.Fatalf("claim recovery: %d %v", n, e) + } +} From 4e54d2cfe86195447844307bf658f34bbdf2502c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 09:52:35 -0800 Subject: [PATCH 12/14] test(gc): bind fencing controls to the initialized W2 HEAD version --- seaweed-block/core/frontend/chunkstore/gc_test.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/gc_test.go b/seaweed-block/core/frontend/chunkstore/gc_test.go index a0ade3fcde..31d3b1bda4 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_test.go @@ -201,7 +201,12 @@ func TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence(t *testing.T) { *now = time.Unix(0, ins[0].CreatedNs).Add(tc.age) // A real remote HEAD fence. The publisher's original expected version // can no longer install after epoch 2 was published. - if _, e = r.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: tc.head, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); e != nil { + cur, e := r.GetHead(ctx) + if e != nil { + t.Fatal(e) + } + old := storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch} + if _, e = r.CASHead(ctx, old, storage.ChunkHead{Epoch: tc.head, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); e != nil { t.Fatal(e) } g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { @@ -225,7 +230,7 @@ func TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence(t *testing.T) { t.Fatal("one mark reclaimed bytes") } if tc.expire { - _, e = r.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "h1"}) + _, e = r.CASHead(ctx, old, storage.ChunkHead{Epoch: 1, Holder: "h1"}) if !errors.Is(e, storage.ErrChunkHeadPrecondition) { t.Fatalf("expired publisher can still CAS: %v", e) } @@ -315,7 +320,11 @@ func TestGC_CopyIntentSurvivesTakeover(t *testing.T) { t.Fatal(e) } } - if _, e := r.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 2, Holder: "new"}); e != nil { + cur, e := r.GetHead(ctx) + if e != nil { + t.Fatal(e) + } + if _, e := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "new"}); e != nil { t.Fatal(e) } g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil } From 82a73daff141d8b032b2f118bcd13cab9f6ad35e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 09:53:53 -0800 Subject: [PATCH 13/14] docs(gc): document permanent copy claims and W2 capture integration --- seaweed-block/core/frontend/chunkstore/GC.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/GC.md b/seaweed-block/core/frontend/chunkstore/GC.md index 502402574e..3a02ab963f 100644 --- a/seaweed-block/core/frontend/chunkstore/GC.md +++ b/seaweed-block/core/frontend/chunkstore/GC.md @@ -1,8 +1,8 @@ # Chunk garbage collection (W5, library slice) -`NewCollector(catalog, blobDeleter, config).Run(ctx)` traces every volume returned by the catalog, every HEAD, every snapshot (including deleting snapshots), and every live upload/copy intent. Use a deadline-bound context. Supply `IssuedEpoch` from the authoritative blockmaster reader, not lease expiry or a host-local projection. There is no automatic scheduler or destructive CLI in this slice. +`NewCollector(catalog, blobDeleter, config).Run(ctx)` traces every volume returned by the catalog, every HEAD, every snapshot (including unnamed attempt entries), and every live upload/copy intent. Use a deadline-bound context. Supply `IssuedEpoch` from the authoritative blockmaster reader, not lease expiry or a host-local projection. There is no automatic scheduler or destructive CLI in this slice. -A capture intent can expire only when its age strictly exceeds IntentTTL, the blockmaster has issued a higher epoch, and the actual remote HEAD has advanced to a higher epoch no greater than the issued one. Unknown authority retains it. Snapshot/fork copy intents are retained until the operation settles: their exclusive creates are not fenced by the remote HEAD epoch. This is intentionally conservative pending a shared publication fence for those operations. +A capture intent can expire only when its age strictly exceeds IntentTTL, the blockmaster has issued a higher epoch, and the actual remote HEAD has advanced to a higher epoch no greater than the issued one. Unknown authority retains it. Snapshot/fork copy intents never expire by epoch. `SweepCopies(ctx)` may settle an attempt past its recorded deadline only by claiming its final immutable publication target through Catalog.AbortSnapshot/AbortFork. Snapshot targets are `snaps//`; fork targets are HEAD, never VOLUME. A confirmed permanent aborted target or a validated published target settles the intent. Unknown claim/read retains it. The deadline admits a claim but never by itself releases protection. Old copy intents without deadline metadata remain protected. An immutable binding becomes a candidate only when its creation time is strictly older than Grace and no root names it. Reclamation requires another successful mark at least Grace after its first observation with the same binding bytes. A rooted candidate is forgotten; failed marks and collector restart discard coverage. Grace must exceed the catalog operation deadline plus the measured mark duration. Backward clock movement refuses the pass. @@ -12,7 +12,7 @@ Unbound needles (upload succeeded but key binding never persisted) are RETAINED. ## Scope and follow-ups -This first Draft implements the GC core and the real Capture/intent/HEAD caller regression. Retention (newest N plus logarithmic age buckets), removal of deleting snapshots, workspace tombstoning, CLI scheduling and a concrete blockmaster client binding remain follow-up W5 slices. Deleting snapshots continue to root their data until the catalog actually removes them. This is safe retention, not complete workspace lifecycle acceptance. +This first Draft implements the GC core and the real Capture/intent/HEAD caller regression. Retention (newest N plus logarithmic age buckets), workspace tombstoning, CLI scheduling and a concrete blockmaster client binding remain follow-up W5 slices. Unnamed deleting snapshot attempts root their keys until their deleting timestamp is older than grace; normal two-mark/upload-age admission still applies afterward. The immutable attempt record is never removed, even after reclaim. Active unnamed attempts remain roots. This is not complete workspace lifecycle acceptance. ## Lock order @@ -21,3 +21,9 @@ The new Collector mutex serializes its own passes and candidate state; it never ## Evidence boundary The assertion RED is an initial GC candidate that already implemented HEAD/snapshot tracing and two marks but omitted intent roots; the base has no GC API to test. It is NOT claimed as a GC bug reproduced on unmodified main. The same test holds the shipping Capture before CAS after real immutable uploads, runs two GC marks, resumes CAS, and reads exact bytes through ChunkRemote. Filer/needle services are deterministic adapters; no SeaweedFS process, hardware, lab or cloud acceptance is claimed. + +## Copy-sweep integration + +The follow-up branch merges W2 #119 b51713e with #117 5f010ca (the #121 parent). The sole capture conflict keeps #117's pre-upload intent list and cleanup semantics, and retains #119's typed `ErrChunkRemoteUnavailable` wrapper on upload failure. No capture intent is swept through the copy protocol. Name reuse creates a new snapshot attempt; permanent old attempt tombstones continue refusing late old inserts. Volume IDs cannot be reused. + +The first copy-sweep RED uses the prior retain-forever behavior (a no-op SweepCopies seam), not a claimed bug on an unmodified main. The same real Catalog caller turns GREEN with permanent-target claims. Tests cover a pending snapshot across name reuse, a fork with VOLUME already present and HEAD held, published unnamed/deleting attempts, unknown claim recovery, and the retained stalled-Capture case. Deterministic remote services only; no lab/cloud actions. From 8fa8cd524386bd1bb4c35a1e9522786a4063b1ea Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 10:12:53 -0800 Subject: [PATCH 14/14] fix(gc): accept final W2 aborted tombstones without published-attempt metadata --- seaweed-block/core/frontend/chunkstore/gc_copy.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy.go b/seaweed-block/core/frontend/chunkstore/gc_copy.go index 1ef7bfa368..4b6fdc261f 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy.go @@ -74,7 +74,7 @@ func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) { if readErr != nil { return settled, readErr } - if info.VolumeID != a.vol || info.Name != parts[1] || string(e.Extended[extAttempt]) != parts[2] { + if info.VolumeID != a.vol || info.Name != parts[1] || (info.State != SnapAborted && string(e.Extended[extAttempt]) != parts[2]) { return settled, errors.New("chunkstore: copy claim identity mismatch") } } else { @@ -151,14 +151,14 @@ func (g *Collector) snapshotAttemptHeads(ctx context.Context, vol string, now ti return nil, err } for _, e := range entries { - if !storage.ValidChunkIntentID(e.Name) || string(e.Extended[extAttempt]) != e.Name { + if !storage.ValidChunkIntentID(e.Name) { return nil, errors.New("chunkstore: invalid snapshot attempt identity") } info, _, err := decodeSnap(path.Join(root, dir.Name, e.Name), e) if err != nil { return nil, err } - if info.VolumeID != vol || info.Name != dir.Name { + if info.VolumeID != vol || info.Name != dir.Name || (info.State != SnapAborted && string(e.Extended[extAttempt]) != e.Name) { return nil, errors.New("chunkstore: snapshot attempt names another volume/name") } if info.State == SnapAborted {