fix: end snapshot operation namespace with volume deletion

This commit is contained in:
pingqiu committed 2026-12-01 18:49:11 -08:00
1 parent 55731e6cdf
commit e08a6fb1db
8 files changed
+237 -10

No files matched your search

@@ -226,7 +226,10 @@ func (c *BCatalog) DeleteVolume(ctx context.Context, v VolumeRef, auth layout.De
sources = append(sources, ss)
}
list := func(ctx context.Context) ([]string, error) { return c.listObjects(ctx, v) }
return skipped, layout.DeleteVolume(ctx, s, auth, v.ID, sources, s, list, progress...)
if err := layout.DeleteVolume(ctx, s, auth, v.ID, sources, s, list, progress...); err != nil {
return skipped, err
}
return skipped, s.deleteSnapshotOperations(ctx)
}
// foreignOwners returns the volumes, other than h's own, whose chunks a
@@ -19,15 +19,16 @@ import (
// master's volume record, never from a name given plus an id read from
// that same directory. A new site fails until it is classified here.
var deleteSites = map[string]string{
"core/frontend/chunkstore/snapshot_operation_index.go LayoutStore.deleteOperationReceipt -> DeleteEntry": "only op-<16 hex sequence> files under the configured volume's operations directory, conditional on volume and sequence; no HEAD, VOLUME or directory removal (TestSnapshotOperationOrphanIsNeverAnsweredOrAdopted, TestSnapshotOperationBoundReceiptCanBeRebuiltAndRetiredBeforeRemoval)",
"core/frontend/chunkstore/layout_create.go LayoutStore.CreateVolumeRecord -> VolumeDir": "validation only after a rejected exclusive create: a valid full foreign VOLUME must name the already selected name/id8 directory; TestCreateVolumeExclusiveCollisionRedraws; no directory selection or removal",
"core/frontend/chunkstore/startup_head_probe.go BCatalog.cleanStartupProbes -> DeleteEntry": "only exact reserved 32-hex probe directories observed before the full active-probe grace; nonrecursive HEAD and empty directory deletes, no volume directory (TestConditionalHeadNextStartCleansCrashLeftovers)",
"core/frontend/chunkstore/startup_head_probe.go BCatalog.checkConditionalHead -> DeleteEntry": "only the disposable HEAD and empty random probe directory after successful exclusive create; no volume directory is used (TestCatalogStartupRequiresWrongGenerationHeadRefusal)",
"cmd/sw-block/chunk_verify.go chunkVerify -> VolumeDir": "master-resolved full id and requested name; offline form accepts an explicit directory without discovering an identity",
"core/frontend/chunkstore/layout/verify.go verifier.chunks -> VolumeDir": "chunk reference's owner name and full id",
"core/frontend/chunkstore/layout/verify.go verifier.depHead -> VolumeDir": "HEAD dependent target name and full id",
"core/frontend/chunkstore/layout/verify.go verifier.orphans -> VolumeDir": "HEAD dependent target name and full id",
"core/frontend/chunkstore/layout/verify.go verifier.volumeID -> VolumeDir": "validation only: compare inspected VOLUME name/id with the already selected directory, never choose a different directory",
"core/frontend/chunkstore/snapshot_operation_cleanup.go LayoutStore.deleteSnapshotOperations -> DeleteEntry": "only operations/INDEX, conditional on full volume ID and index kind after HEAD is deleted; receipts removed first, no directory or HEAD/VOLUME removal (TestSnapshotOperationVolumeDeleteEndsNamespace, TestSnapshotOperationVolumeDeleteCleanupReruns)",
"core/frontend/chunkstore/snapshot_operation_index.go LayoutStore.deleteOperationReceipt -> DeleteEntry": "only op-<16 hex sequence> files under the configured volume's operations directory, conditional on volume and sequence; no HEAD, VOLUME or directory removal (TestSnapshotOperationOrphanIsNeverAnsweredOrAdopted, TestSnapshotOperationBoundReceiptCanBeRebuiltAndRetiredBeforeRemoval)",
"core/frontend/chunkstore/layout_create.go LayoutStore.CreateVolumeRecord -> VolumeDir": "validation only after a rejected exclusive create: a valid full foreign VOLUME must name the already selected name/id8 directory; TestCreateVolumeExclusiveCollisionRedraws; no directory selection or removal",
"core/frontend/chunkstore/startup_head_probe.go BCatalog.cleanStartupProbes -> DeleteEntry": "only exact reserved 32-hex probe directories observed before the full active-probe grace; nonrecursive HEAD and empty directory deletes, no volume directory (TestConditionalHeadNextStartCleansCrashLeftovers)",
"core/frontend/chunkstore/startup_head_probe.go BCatalog.checkConditionalHead -> DeleteEntry": "only the disposable HEAD and empty random probe directory after successful exclusive create; no volume directory is used (TestCatalogStartupRequiresWrongGenerationHeadRefusal)",
"cmd/sw-block/chunk_verify.go chunkVerify -> VolumeDir": "master-resolved full id and requested name; offline form accepts an explicit directory without discovering an identity",
"core/frontend/chunkstore/layout/verify.go verifier.chunks -> VolumeDir": "chunk reference's owner name and full id",
"core/frontend/chunkstore/layout/verify.go verifier.depHead -> VolumeDir": "HEAD dependent target name and full id",
"core/frontend/chunkstore/layout/verify.go verifier.orphans -> VolumeDir": "HEAD dependent target name and full id",
"core/frontend/chunkstore/layout/verify.go verifier.volumeID -> VolumeDir": "validation only: compare inspected VOLUME name/id with the already selected directory, never choose a different directory",
"cmd/blockvolume/main.go parseFlagsWithCgroup -> VolumeDir": "validated master layout id and volume name; unchanged parser body behind parseFlags; TestBlockvolumeLayoutIdentitySelectsTheLocalRoot",
"core/launcher/k8s_renderer.go durableRoot -> VolumeDir": "persisted workload plan layout id and name; launcher layout identity controls",
@@ -70,6 +70,8 @@ var headReaders = map[string]string{
"core/frontend/chunkstore/layout_remote.go rollBackLocked -> ReadHead": "refuses ErrHeadAbsent before any Begin or upload (probe LayoutRemote)",
"core/frontend/chunkstore/layout/create.go createVolume -> ReadHead": "reads HEAD only after its exclusive create found one; absent then refuses ErrIdentity, writes nothing more (probe LayoutCreate)",
"core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)",
"core/frontend/chunkstore/snapshot_operation_cleanup.go deleteSnapshotOperations -> ReadHead": "absent or not-deleted HEAD refuses cleanup without deleting operation authority (TestSnapshotOperationCleanupRequiresDeletedHead)",
"core/frontend/chunkstore/snapshot_operation_index.go readOperationIndex -> ReadHead": "absent HEAD refuses empty-index admission; deleting/deleted refuses sequence reset after namespace cleanup (TestSnapshotOperationCleanupRequiresDeletedHead, TestSnapshotOperationVolumeDeleteEndsNamespace)",
// above the chunk store: they read through the layout remote's GetHead, so an
// absent HEAD reaches them as ErrHeadAbsent, never as a zero HEAD (probe LayoutRemote)
"cmd/sw-block/chunk_b.go chunkShowContext -> ReadHead": "found=false: prints a null head, including via the chunkShow wrapper (probe TestOpsChunk_AbsentVolume)",
@@ -0,0 +1,61 @@
package chunkstore
import (
"context"
"errors"
"path"
"strconv"
"strings"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// deleteSnapshotOperations ends the namespace only after the volume's ordered
// deletion. Receipts go first; retaining INDEX across an interruption prevents
// an incomplete cleanup from resetting the issued sequence authority.
func (s *LayoutStore) deleteSnapshotOperations(ctx context.Context) error {
h, found, err := s.ReadHead(ctx)
if err != nil {
return err
}
if !found || h.State != layout.StateDeleted {
return layout.ErrPrecondition
}
dir := path.Join(s.root, "operations")
cursor := ""
for {
entries, err := s.f.ListEntries(ctx, dir, "op-", cursor, 128)
if err != nil {
return remoteErr(err, "snapshot operation deletion listing")
}
for _, e := range entries {
if e == nil || e.IsDirectory || e.Name <= cursor {
return layout.ErrCorrupt
}
sequence, err := strconv.ParseUint(strings.TrimPrefix(e.Name, "op-"), 16, 64)
if err != nil || sequence == 0 || operationReceiptName(sequence) != e.Name {
return layout.ErrCorrupt
}
cursor = e.Name
if err := s.deleteOperationReceipt(ctx, sequence); err != nil {
return err
}
}
if len(entries) < 128 {
break
}
}
err = s.f.DeleteEntry(ctx, dir, operationIndexName, map[string][]byte{layoutVolume: []byte(s.id.String()), layoutKind: []byte("snapshot-operation-index")})
if errors.Is(err, ErrNotFound) {
return nil
}
if errors.Is(err, ErrPrecondition) {
if _, lookupErr := s.f.LookupEntry(ctx, dir, operationIndexName); errors.Is(lookupErr, ErrNotFound) {
return nil
}
}
if err != nil {
return remoteErr(err, "snapshot operation index deletion")
}
return nil
}
@@ -87,6 +87,16 @@ func (s *LayoutStore) readOperationIndex(ctx context.Context) (operationIndex, e
return operationIndex{}, remoteErr(listErr, "snapshot operation index evidence")
}
if len(files) == 0 {
h, found, headErr := s.ReadHead(ctx)
if headErr != nil {
return operationIndex{}, headErr
}
if !found {
return operationIndex{}, layout.ErrHeadAbsent
}
if h.State == layout.StateDeleting || h.State == layout.StateDeleted {
return operationIndex{}, layout.ErrVolumeDeleting
}
return operationIndex{next: 1}, nil
}
// Another executor may have created the index and its receipt after
@@ -0,0 +1,130 @@
package chunkstore
import (
"context"
"errors"
"path"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
func TestSnapshotOperationVolumeDeleteEndsNamespace(t *testing.T) {
ctx := context.Background()
c, f, _, _, target := rerunFixture(t)
s, err := c.Store(target)
if err != nil {
t.Fatal(err)
}
op, _, err := s.CreateSnapshotOperation(ctx, "pending", "create", "daily", strings.Repeat("a", 64))
if err != nil {
t.Fatal(err)
}
dir := path.Join(s.root, "operations")
if _, err := c.DeleteVolume(ctx, target, okDeleteAuthority{}); err != nil {
t.Fatal(err)
}
entries, err := f.ListEntries(ctx, dir, "", "", 100)
if err != nil || len(entries) != 0 {
t.Fatalf("operation namespace survived volume deletion: entries=%v err=%v", entries, err)
}
if _, err := s.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence); !errors.Is(err, layout.ErrVolumeDeleting) && !errors.Is(err, ErrSnapshotOperationRetired) {
t.Fatalf("deleted volume answered old operation: %v", err)
}
if _, _, err := s.CreateSnapshotOperation(ctx, "new", "create", "new", strings.Repeat("b", 64)); !errors.Is(err, layout.ErrVolumeDeleting) {
t.Fatalf("deleted namespace readmitted: %v", err)
}
for _, name := range []string{"HEAD", "VOLUME"} {
if _, err := f.LookupEntry(ctx, s.root, name); err != nil {
t.Fatalf("control %s removed: %v", name, err)
}
}
}
func TestSnapshotOperationVolumeDeleteCleanupReruns(t *testing.T) {
ctx := context.Background()
c, f, _, _, target := rerunFixture(t)
s, err := c.Store(target)
if err != nil {
t.Fatal(err)
}
for _, id := range []string{"first", "second"} {
if _, _, err := s.CreateSnapshotOperation(ctx, id, "create", id, strings.Repeat("a", 64)); err != nil {
t.Fatal(err)
}
}
injected := errors.New("receipt delete interrupted")
attempts := 0
f.failDelete = func(p string) error {
if strings.Contains(p, "/operations/op-") {
attempts++
if attempts == 2 {
return injected
}
}
return nil
}
if _, err := c.DeleteVolume(ctx, target, okDeleteAuthority{}); !errors.Is(err, injected) {
t.Fatalf("cleanup did not surface interrupted receipt delete: %v", err)
}
f.failDelete = nil
if _, err := f.LookupEntry(ctx, path.Join(s.root, "operations"), operationIndexName); err != nil {
t.Fatalf("authority removed ahead of receipts: %v", err)
}
if _, err := c.DeleteVolume(ctx, target, okDeleteAuthority{}); err != nil {
t.Fatal(err)
}
entries, err := f.ListEntries(ctx, path.Join(s.root, "operations"), "", "", 100)
if err != nil || len(entries) != 0 {
t.Fatalf("rerun left operations: %v %v", entries, err)
}
}
func TestSnapshotOperationCleanupRequiresDeletedHead(t *testing.T) {
ctx := context.Background()
_, _, s, _ := cleanFixture(t)
if err := s.deleteSnapshotOperations(ctx); !errors.Is(err, layout.ErrPrecondition) {
t.Fatalf("live HEAD allowed cleanup: %v", err)
}
if err := s.f.DeleteEntry(ctx, s.root, "HEAD", nil); err != nil {
t.Fatal(err)
}
if err := s.deleteSnapshotOperations(ctx); !errors.Is(err, layout.ErrPrecondition) {
t.Fatalf("absent HEAD allowed cleanup: %v", err)
}
if _, _, err := s.CreateSnapshotOperation(ctx, "missing-head", "create", "daily", strings.Repeat("a", 64)); !errors.Is(err, layout.ErrHeadAbsent) {
t.Fatalf("absent HEAD restarted index: %v", err)
}
}
func TestSnapshotOperationVolumeDeleteSparesForeignReceipt(t *testing.T) {
ctx := context.Background()
c, f, _, _, target := rerunFixture(t)
s, err := c.Store(target)
if err != nil {
t.Fatal(err)
}
op, _, err := s.CreateSnapshotOperation(ctx, "foreign", "create", "daily", strings.Repeat("a", 64))
if err != nil {
t.Fatal(err)
}
dir := path.Join(s.root, "operations")
entry, err := f.LookupEntry(ctx, dir, operationReceiptName(op.Sequence))
if err != nil {
t.Fatal(err)
}
entry.Extended[layoutVolume] = []byte(newRef(t, "replacement").ID.String())
if err := f.UpdateEntry(ctx, dir, entry, nil); err != nil {
t.Fatal(err)
}
if _, err := c.DeleteVolume(ctx, target, okDeleteAuthority{}); err == nil {
t.Fatal("foreign operation receipt counted as removed")
}
if _, err := f.LookupEntry(ctx, dir, entry.Name); err != nil {
t.Fatalf("foreign receipt deleted: %v", err)
}
if _, err := f.LookupEntry(ctx, dir, operationIndexName); err != nil {
t.Fatalf("authority removed after refused receipt: %v", err)
}
}
+7
View File
@@ -651,6 +651,12 @@ most 512 bytes. Process-owned asynchronous create is wired, but asynchronous
catalog delete and the full native crash/concurrent-worker qualification remain
owed before these STUB rows become ACTIVE. No complete-unit acceptance is claimed.
When the enclosing volume reaches deleted through its ordered catalog deletion,
its operation receipts are removed conditionally before INDEX. An interrupted
namespace cleanup reruns; the deleted HEAD remains the fence against creating
a fresh sequence authority. This is volume lifetime termination, not retirement
of a live snapshot operation or an early declaration of snapshot cleanup success.
## Part B. Invariant ledger
@@ -1325,6 +1331,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-OP-END-001` | After ordered volume deletion, remove its receipts by full volume/sequence and then INDEX by full volume/kind; an interrupted cleanup reruns. Missing or deleted HEAD never restarts index admission. HEAD, VOLUME and directories stay. | M9 deleted → operation namespace ended | `snapshot_operation_cleanup.go`; `BCatalog.DeleteVolume`; `readOperationIndex` | `TestSnapshotOperationVolumeDeleteEndsNamespace`, `TestSnapshotOperationVolumeDeleteCleanupReruns`, `TestSnapshotOperationVolumeDeleteSparesForeignReceipt`, `TestSnapshotOperationCleanupRequiresDeletedHead` | SnapOps namespace lifetime ends with volume; native qualification owed | STUB |
| `INV-SNAP-OP-CRASH-001` | A durable snapshot intent survives holder SIGKILL before publication and completes once after restart; after publication, restart settles its original receipt without another cut. | M9 operation recovery (planned) | Process-owned create executor; native crash qualification pending | `TestSnapshotOperationIntentAndPublicationCrashBoundaries`, `TestSnapshotOperationKillReceiptRejectsOrdinaryExit` (`cmd/blockvolume/snapshot_operation_crash_integration_test.go`) | SnapOps.Start/Publish/Settle; rows 211–219 (native red receipt owed) | STUB |
| `INV-SNAPK-RETAIN-META-001` | Reachability, removal and the volume delete never read a snapshot's retention facts (source guard); the policy entry beside VOLUME changes by one conditional update and is read only by retain. | M9 snap → idle | `core/frontend/chunkstore/layout` `head.go` `SnapshotMeta`; `core/frontend/chunkstore` `retain_b.go` | `TestSnapshotMeta_WrittenOnceByTheCommit`, `TestGuard_SafetyIgnoresSnapshotMeta`, `TestBCatalog_RetainKeepsTheOldBehaviour`, `TestBCatalog_RetentionPolicyIsConditional` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-HEAD-BOUND-001` | HEAD stays inline: at most 10 snapshots, names at most 64 bytes, 4 labels, 4 dependents per snapshot and 16 per HEAD, refused where they enter with the cure; Encode refuses a HEAD above 64 KiB. A snapshot past 10 is refused before its cut: nothing is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `check`, `Encode`; `snapshots.go` `AddDependent`; `commit.go` `Commit`; `core/frontend/durable/provider_layout_snapshot.go` `SnapshotVolume`; `core/host/volume/chunk_control.go` `chunkErrorCode`; `core/host/volume/chunk_scheduled_snapshot.go` `ScheduledSnapshot` | `TestHead_SizeAtTheSnapshotCap`, `TestHead_BoundsRefused`, `TestChunkSnapshotPastTheLimitIsRefusedWithHEADUnchanged`, `TestScheduledSnapshotAtTheLimitStillPublishes`, `TestChunkSnapshotRefusalsAreTyped`, `TestLayoutProviderSnapshotVolume` | — (the snapshot kernel model is not in this repository) | ACTIVE |
@@ -107,3 +107,16 @@ This low-level admission API does not execute a delete, start a daemon, stamp
HEAD, or claim crash/legacy integration qualification. Catalog and CLI callers,
V8's universal publishing-generation field, the target-qualified HEAD CAS and
its legacy stamp controls remain owed. The corresponding ledger rows are STUB.
## End of the operation namespace
After the existing ordered volume delete reaches HEAD deleted, catalog deletion
removes receipt files conditional on full volume ID and sequence, then removes
INDEX conditional on full volume ID and kind. A partial failure leaves INDEX
until the remaining receipts are removed; rerunning volume delete repeats this
cleanup. Missing INDEX on a deleting/deleted volume cannot start a new sequence
authority. The immutable HEAD tombstone, VOLUME and directories remain. This is
not receipt retirement during a live snapshot delete: it ends all operations
only when their enclosing volume itself has been deleted. A late write is swept
by a later rerun, as with late data objects; no concurrent-transport drain is
claimed by the cleanup alone.