diff --git a/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go b/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go index 6238d1c83d..36bc322ce0 100644 --- a/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go +++ b/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go @@ -8,7 +8,6 @@ import ( "io" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" ) // chunkRunCatalogSnapshotDelete is the CLI-owned execution/observation seam. @@ -66,29 +65,7 @@ func chunkAdmitCatalogSnapshotDelete(ctx context.Context, cat *chunkstore.BCatal if err != nil { return nil, err } - op, err := st.AdmitSnapshotDeleteOperation(ctx, id, name, func(ctx context.Context) (uint64, error) { - h, found, err := st.ReadHead(ctx) - if err != nil { - return 0, err - } - if !found { - return 0, layout.ErrHeadAbsent - } - if h.Version != layout.HeadVersion1 { - return 0, &chunkstore.CatalogError{Code: "snapshot_generation_unavailable", Message: "make the first v1.1 HEAD write with a v1.1 holder to stamp snapshot generations before operation-based deletion", Retryable: true} - } - target, found := h.Snapshots[name] - if !found { - return 0, nil - } - if target.Gen == 0 { - return 0, &chunkstore.CatalogError{Code: "snapshot_generation_unavailable", Message: "snapshot has no publishing generation; make the first v1.1 HEAD write with a v1.1 holder first", Retryable: true} - } - if pin != 0 && target.Gen != pin { - return 0, &chunkstore.CatalogError{Code: "snapshot_generation_mismatch", Message: fmt.Sprintf("the snapshot is %s@%d, not %s@%d (--gen)", name, target.Gen, name, pin)} - } - return target.Gen, nil - }) + op, err := st.AdmitSnapshotDeleteOperation(ctx, id, name, chunkstore.SnapshotDeleteTarget(st, name, pin)) if err != nil { if errors.Is(err, chunkstore.ErrSnapshotOperationIntent) { return nil, &chunkstore.CatalogError{Code: "operation_intent_conflict", Message: err.Error(), Err: err} diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_delete_target.go b/seaweed-block/core/frontend/chunkstore/snapshot_delete_target.go new file mode 100644 index 0000000000..92142cdf5d --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/snapshot_delete_target.go @@ -0,0 +1,41 @@ +package chunkstore + +import ( + "context" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// SnapshotDeleteTarget is the admission resolver of a delete by name, shared +// by the CLI and the holder's control route: the publishing generation of +// the incarnation name holds now on a version-1 HEAD, 0 when the name is +// absent (admission then retains its refusal), and, when pin is nonzero, +// only that incarnation. A version-0 HEAD, or an unstamped incarnation, has +// no generation yet: refused retryably until a v1.1 holder's first write +// stamps it. +func SnapshotDeleteTarget(st *LayoutStore, name string, pin uint64) func(context.Context) (uint64, error) { + return func(ctx context.Context) (uint64, error) { + h, found, err := st.ReadHead(ctx) + if err != nil { + return 0, err + } + if !found { + return 0, layout.ErrHeadAbsent + } + if h.Version != layout.HeadVersion1 { + return 0, &CatalogError{Code: "snapshot_generation_unavailable", Message: "make the first v1.1 HEAD write with a v1.1 holder to stamp snapshot generations before operation-based deletion", Retryable: true} + } + target, found := h.Snapshots[name] + if !found { + return 0, nil + } + if target.Gen == 0 { + return 0, &CatalogError{Code: "snapshot_generation_unavailable", Message: "snapshot has no publishing generation; make the first v1.1 HEAD write with a v1.1 holder first", Retryable: true} + } + if pin != 0 && target.Gen != pin { + return 0, &CatalogError{Code: "snapshot_generation_mismatch", Message: fmt.Sprintf("the snapshot is %s@%d, not %s@%d (--gen)", name, target.Gen, name, pin)} + } + return target.Gen, nil + } +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index fc71681032..094eb68e42 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -9,6 +9,7 @@ package volume import ( "context" + "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" @@ -1011,12 +1012,29 @@ func (c *chunkControl) ListSnapshots(ctx context.Context, volumeID string, opts return out, next, nil } +// DeleteSnapshot deletes volumeID's snapshot name. On a version-0 HEAD it is +// v1.0's name-only delete. On a version-1 HEAD it is an operation delete of +// the incarnation the name holds now, under an id made for this request: a +// new request is a new intent, and the operation keeps its incarnation +// across its own resumes. func (c *chunkControl) DeleteSnapshot(ctx context.Context, volumeID, name string) (string, error) { v, err := c.catalogVolume(volumeID) if err != nil { return "", err } - _, err = c.cat.DeleteSnapshot(ctx, v, name) + st, err := c.cat.Store(v) + if err != nil { + return "", err + } + h, found, err := st.ReadHead(ctx) + if err != nil { + return "", err + } + if found && h.Version >= layout.HeadVersion1 { + err = c.deleteSnapshotOperation(ctx, volumeID, v, st, name) + } else { + _, err = c.cat.DeleteSnapshot(ctx, v, name) + } if err != nil { return "", err } @@ -1026,6 +1044,55 @@ func (c *chunkControl) DeleteSnapshot(ctx context.Context, volumeID, name string return "deleted", nil } +// deleteSnapshotOperation admits one delete operation for name and runs it. +// A run that finds the previous delete's intent not yet consumed (busy) or +// HEAD moved leaves the operation resumable: the holder kicks its cleaning +// and resumes the same operation, within holderDeleteResume, so its own +// request never leaves it stalled. +func (c *chunkControl) deleteSnapshotOperation(ctx context.Context, volumeID string, v chunkstore.VolumeRef, st *chunkstore.LayoutStore, name string) error { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return err + } + op, err := st.AdmitSnapshotDeleteOperation(ctx, "holder-"+hex.EncodeToString(b[:]), name, chunkstore.SnapshotDeleteTarget(st, name, 0)) + if err != nil { + return err + } + end := time.Now().Add(holderDeleteResume) + for { + if op.State == "refused" { + return &chunkstore.CatalogError{Code: op.ErrorCode, Message: op.ErrorMessage} + } + answer, runErr := c.cat.RunSnapshotDeleteOperation(ctx, v, op, nil) + switch { + case runErr == nil && answer.State == "succeeded": + return nil + case runErr == nil && answer.State == "refused": + return &chunkstore.CatalogError{Code: answer.ErrorCode, Message: answer.ErrorMessage} + case runErr != nil && !errors.Is(runErr, layout.ErrBusy) && !errors.Is(runErr, layout.ErrPrecondition): + return runErr + case time.Now().After(end): + if runErr == nil { + runErr = &chunkstore.CatalogError{Code: "no_progress", Message: "snapshot delete operation has not settled", Retryable: true} + } + return runErr + } + c.p.KickMaintenance(volumeID) + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(100 * time.Millisecond): + } + if op, err = st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence); err != nil { + return err + } + } +} + +// holderDeleteResume bounds how long the holder resumes one delete +// operation that found the previous intent unconsumed or HEAD moved. +const holderDeleteResume = 30 * time.Second + func (c *chunkControl) ScheduleSnapshotNow(volumeID string) bool { if _, err := c.catalogVolume(volumeID); err != nil { return false diff --git a/seaweed-block/core/host/volume/chunk_control_order_test.go b/seaweed-block/core/host/volume/chunk_control_order_test.go index 81931c42cd..6adf46a2a7 100644 --- a/seaweed-block/core/host/volume/chunk_control_order_test.go +++ b/seaweed-block/core/host/volume/chunk_control_order_test.go @@ -16,7 +16,7 @@ import ( type healthyView struct{} func (healthyView) Projection() frontend.Projection { - return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true} + return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true, FormatLevel: 1} } // Through the real provider: a minLSN never written is refused with no diff --git a/seaweed-block/core/host/volume/snapshot_delete_legacy_refusal_test.go b/seaweed-block/core/host/volume/snapshot_delete_legacy_refusal_test.go index a5ab0c5915..bc6240f134 100644 --- a/seaweed-block/core/host/volume/snapshot_delete_legacy_refusal_test.go +++ b/seaweed-block/core/host/volume/snapshot_delete_legacy_refusal_test.go @@ -2,14 +2,20 @@ package volume import ( "context" + "errors" "fmt" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" - "net/http" "testing" ) -func TestSnapshotDeleteLegacyHostRetryCannotDeleteV11Replacement(t *testing.T) { +// The holder's v1.0 delete by name succeeded but its reply was lost, and the +// name was recreated in a v1.1 HEAD. A new request is a new intent: on the +// version-1 HEAD the holder runs an operation delete of the incarnation the +// name holds now, which removes the replacement, and kicks its cleaning. The +// name-only primitive (an old client's call) refuses that HEAD with nothing +// written. +func TestSnapshotDeleteHolderAfterALostLegacyReplyIsANewIntent(t *testing.T) { ctx := context.Background() filer := &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}} cat, err := chunkstore.NewBCatalog(filer, filer, "/chunks") @@ -22,11 +28,28 @@ func TestSnapshotDeleteLegacyHostRetryCannotDeleteV11Replacement(t *testing.T) { t.Fatal(err) } st, _ := cat.Store(volume) + root, segments, err := layout.Build(map[uint64]layout.Ref{}) + if err != nil { + t.Fatal(err) + } + rn, rb, err := layout.NameRoot(root) + if err != nil { + t.Fatal(err) + } + objects := map[string][]byte{rn.Path(): rb} + for name, data := range segments { + objects[name.Path()] = data + } + for name, data := range objects { + if err := layout.EnsureObject(ctx, st, name, data, "fixture"); err != nil { + t.Fatal(err) + } + } h, _, err := st.ReadHead(ctx) if err != nil { t.Fatal(err) } - original := layout.Snapshot{Root: layout.RootName{Hash: layout.Sum([]byte("original"))}} + original := layout.Snapshot{Root: rn} h.Snapshots = map[string]layout.Snapshot{"daily": original} if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil { t.Fatal(err) @@ -41,12 +64,13 @@ func TestSnapshotDeleteLegacyHostRetryCannotDeleteV11Replacement(t *testing.T) { if err != nil { t.Fatal(err) } - original.Gen = h.Gen + 1 + replacement := original + replacement.Gen = h.Gen + 1 h.Version = layout.HeadVersion1 if h.Snapshots == nil { h.Snapshots = map[string]layout.Snapshot{} } - h.Snapshots["daily"] = original + h.Snapshots["daily"] = replacement if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil { t.Fatal(err) } @@ -54,17 +78,21 @@ func TestSnapshotDeleteLegacyHostRetryCannotDeleteV11Replacement(t *testing.T) { if err != nil { t.Fatal(err) } - _, err = control.DeleteSnapshot(ctx, "v1", "daily") - status, code, retry := chunkErrorCode(err) - if err == nil || status != http.StatusConflict || code != "snapshot_delete_requires_operation" || retry { - t.Errorf("legacy retry must refuse v1.1: err=%v status=%d code=%s retry=%v", err, status, code, retry) + if _, err := cat.DeleteSnapshot(ctx, volume, "daily"); !errors.Is(err, layout.ErrSnapshotDeleteNeedsOperation) { + t.Fatalf("the name-only primitive on a version-1 HEAD: %v; want snapshot_delete_requires_operation", err) } - after, _, readErr := st.ReadHead(ctx) - if readErr != nil || after.Gen != before.Gen || after.Snapshots["daily"].Gen != original.Gen { - t.Fatalf("lost-reply retry deleted replacement: before=%+v after=%+v err=%v", before, after, readErr) + if after, _, err := st.ReadHead(ctx); err != nil || after.Gen != before.Gen { + t.Fatalf("the refused primitive wrote the HEAD: before gen %d after %+v %v", before.Gen, after, err) } - if len(provider.kicks) != 1 { - t.Fatalf("refused v1.1 delete kicked maintenance: %v", provider.kicks) + if _, err := control.DeleteSnapshot(ctx, "v1", "daily"); err != nil { + t.Fatalf("a new holder delete on the version-1 HEAD: %v; want the replacement deleted", err) + } + after, _, err := st.ReadHead(ctx) + if err != nil || len(after.Snapshots) != 0 || after.Version != layout.HeadVersion1 { + t.Fatalf("after the new holder delete: %+v %v; want a version-1 HEAD without daily", after, err) + } + if len(provider.kicks) != 2 { + t.Fatalf("maintenance kicks %v; want one per completed delete", provider.kicks) } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index df00dba933..3d33c5d733 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1367,7 +1367,7 @@ Notes: | `INV-SNAP-OP-FINGERPRINT-001` | A retained operation ID reused with changed snapshot intent refuses before any cut or HEAD write. | M9 operation admission (planned) | `CreateSnapshotOperation` canonical fingerprint; create executor wired; delete executor pending | `TestSnapshotOperationSameIDChangedIntentRefusesBeforeWrite` (`core/host/volume/snapshot_operation_red_test.go`) | SnapOps.Send; rows 211–219 | STUB | | `INV-SNAP-OP-READMIT-001` | A create whose HEAD publication applied before its answer was lost reconciles that original outcome on re-admission; later removal cannot cause another execution under its retained operation ID. | M9 operation re-admission (planned) | `SnapshotOperationBinding`, `LayoutStore.GuardSnapshotOperations`; create executor and compact index wired; native qualification pending | `TestSnapshotOperationLostPublishAnswerReadmitDeleteCannotRepublish`, `TestSnapshotOperationRemovalBeforeReadmitKeepsPublishedOutcome` (`core/host/volume/snapshot_operation_red_test.go`) | SnapOps.Send/Publish/Settle/Delete; rows 211–219 (persisted-stall removal controls included; concurrent-owner controls pending) | STUB | | `INV-SNAP-OP-CLI-001` | Snapshot observation preserves the printed operation ID across retries, polling, interruption and no-wait submission; observing an operation never admits another identity. | M9 operation observation (planned) | `chunkObserveSnapshot`, holder asynchronous create executor | `TestSnapshotOperationCLIUsesPrintedIDForAsyncObservation`, `TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID` (`cmd/sw-block/snapshot_operation_red_test.go`, `cmd/sw-block/snapshot_operation_interrupt_unix_test.go`) | SnapOps.Send/Start; rows 211–219 (server crash controls owed) | STUB | -| `INV-SNAP-DELETE-NAME-001` | The name-only delete primitive (an old client's) refuses a v1.1 HEAD without a HEAD write. Retries in one CLI invocation keep its request id and resolved incarnation, so a lost reply never deletes a replacement; a new invocation resolves the name again (--gen pins it). | M9 legacy delete admission | `layout.RunDeleteSnapshot`; catalog, CLI and host delete routes | `TestSnapshotDeleteOldClientNameOnlyRefusesAV1Head`, `TestSnapshotDeleteAfterALostLegacyReplyIsANewIntent`, `TestSnapshotDeleteLegacyHostRetryCannotDeleteV11Replacement`, `TestSnapshotDeletePublicOperationKeepsTargetAcrossRecreation`, `TestSnapshotDeletePublicNoWaitResumesSameAdmission`, `TestSnapshotDeletePublicAbsentHeadRefuses` | SnapDelete row 242; rows 241-245 | STUB | +| `INV-SNAP-DELETE-NAME-001` | The name-only delete primitive (an old client's) refuses a v1.1 HEAD without a HEAD write. Retries in one CLI invocation keep its request id and resolved incarnation, so a lost reply never deletes a replacement; a new invocation resolves the name again (--gen pins it). | M9 legacy delete admission | `layout.RunDeleteSnapshot`; catalog, CLI and host delete routes | `TestSnapshotDeleteOldClientNameOnlyRefusesAV1Head`, `TestSnapshotDeleteAfterALostLegacyReplyIsANewIntent`, `TestSnapshotDeleteHolderAfterALostLegacyReplyIsANewIntent`, `TestSnapshotDeletePublicOperationKeepsTargetAcrossRecreation`, `TestSnapshotDeletePublicNoWaitResumesSameAdmission`, `TestSnapshotDeletePublicAbsentHeadRefuses` | SnapDelete row 242; rows 241-245 | STUB | | `INV-SNAP-DELETE-LOGICAL-001` | A delete receipt succeeds only after its retained target is proven absent. Actual unlink and its durable reclamation intent publish in one HEAD CAS; physical continuation depends on HEAD/pages, not the receipt. | M9 delete running to succeeded | `snapshotDeleteLogicalStep`, `RunDeleteSnapshotWithIntent` | `TestSnapshotDeleteLogicalCommitKeepsIndependentIntent`, `TestSnapshotDeleteLogicalCommitResumesAcrossLostAnswers`, `TestSnapshotDeleteLogicalCommitSparesReplacement` | SnapDelete rows 241-245; PageChain rows 246-253 | STUB | | `INV-SNAP-DELETE-EXECUTOR-001` | A catalog delete attempt reads its issued handle before work, takes ownership by receipt CAS, and persists uncertain work as stalled. It never infers terminal success from a callback return; terminal replay reads the same incarnation. | M9 delete attempt transport | `BCatalog.RunSnapshotDeleteOperation`; CLI execution seam | `TestSnapshotDeleteCatalogResumesDurableIntentOnAnotherExecutor`, `TestSnapshotDeleteCatalogRefusesWrongIntentBeforeWork`, `TestSnapshotDeleteCatalogCannotInferSuccessFromWorkReturn`, `TestSnapshotDeleteOfflineCLILeavesProgressInFiler` | SnapDelete retained target; SnapOps owner/state refinement; V8 completion adapter and public command activation owed | STUB | | `INV-SNAP-OP-ADMISSION-CLOSE-001` | Admission checks HEAD after receipt publication and refuses a deleting/deleted or absent volume. Closed incarnations cannot answer retained operation queries; their terminal receipt bytes are not rewritten by closing. | M9 admission and observation | `checkSnapshotOperationAdmission`, `readOperationIndex`, create/delete admission | `TestSnapshotOperationAdmissionRechecksHeadAfterPublication`, `TestSnapshotOperationClosedVolumeRefusesReceipts`, `TestSnapshotOperationTerminalReadmissionRechecksHeadAfterFlag` | SnapVolDel rows 257-260 (per-incarnation) | STUB |