fix(master): a pending restore record is settled by a replay that finds its snapshot gone; a failed removal is a retry

Review follow-up. A restore can pass the master's snapshot check, write
its record, and then meet a snapshot deleted in between (refused for good
by target creation); a crash, or a removal that fails, leaves the record.
The replay then stops at the master's own snapshot check: it now removes
the matching not-ready record there, since a recorded dependent keeps
its snapshot, so an absent snapshot proves the target was never recorded
on the source. A removal that fails answers Unavailable (retry), not the
refusal.

Tests through the real catalog: a restore of a restore target's snapshot
is refused with no filer write and no record; a failure after the
dependent's write keeps the record and the replay completes it with the
same target id. Renewal on a not-ready name: admitted deletion untyped,
committed deletion typed DELETED.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-28 10:50:27 -08:00
1 parent 9f1c3d591f
commit 1ec0404d9d
4 files changed
+447 -4

No files matched your search

@@ -0,0 +1,367 @@
package master
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// catalogBlobs is an in-memory needle store for the real catalog.
type catalogBlobs struct {
mu sync.Mutex
m map[string][]byte
}
func (b *catalogBlobs) Put(_ context.Context, data []byte) (string, error) {
b.mu.Lock()
defer b.mu.Unlock()
id := fmt.Sprint(len(b.m) + 1)
b.m[id] = append([]byte(nil), data...)
return id, nil
}
func (b *catalogBlobs) Get(_ context.Context, fid string) ([]byte, error) {
b.mu.Lock()
defer b.mu.Unlock()
d, ok := b.m[fid]
if !ok {
return nil, fmt.Errorf("%w: %s", chunkstore.ErrBlobNotFound, fid)
}
return append([]byte(nil), d...), nil
}
// countingFiler counts the filer writes and can fail the first VOLUME
// create in a directory whose name starts with failVolumeIn.
type countingFiler struct {
chunkstore.Filer
mu sync.Mutex
writes int
failVolumeIn string
}
func (f *countingFiler) count() int {
f.mu.Lock()
defer f.mu.Unlock()
return f.writes
}
func (f *countingFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, excl bool) error {
f.mu.Lock()
f.writes++
fail := f.failVolumeIn != "" && e.Name == "VOLUME" && strings.Contains(dir, "/"+f.failVolumeIn)
if fail {
f.failVolumeIn = ""
}
f.mu.Unlock()
if fail {
return errors.New("fixture: lost the target's VOLUME create")
}
return f.Filer.CreateEntry(ctx, dir, e, excl)
}
func (f *countingFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
f.mu.Lock()
f.writes++
f.mu.Unlock()
return f.Filer.UpdateEntry(ctx, dir, e, expected)
}
func catalogRef(t *testing.T, spec lifecycle.VolumeSpec) chunkstore.VolumeRef {
t.Helper()
id, err := layout.ParseVolumeID(spec.LayoutID)
if err != nil {
t.Fatal(err)
}
return chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}
}
// catalogMaster is a master whose layout hooks are the real catalog's, as
// blockmaster wires them (cmd/blockmaster/layout_create.go).
func catalogMaster(t *testing.T) (*Host, *services, *chunkstore.BCatalog, *countingFiler) {
t.Helper()
filer := &countingFiler{Filer: chunkstore.NewMemFiler()}
cat, err := chunkstore.NewBCatalog(filer, &catalogBlobs{m: map[string][]byte{}}, "/blocks")
if err != nil {
t.Fatal(err)
}
h := newTestMaster(t, t.TempDir())
t.Cleanup(func() { closeTestMaster(t, h) })
ref := func(spec lifecycle.VolumeSpec) (chunkstore.VolumeRef, error) {
id, err := layout.ParseVolumeID(spec.LayoutID)
return chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}, err
}
h.cfg.LayoutCreateVolume = func(ctx context.Context, spec lifecycle.VolumeSpec) error {
r, err := ref(spec)
if err != nil {
return err
}
_, err = cat.CreateVolume(ctx, r, layout.Geometry{SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes})
return err
}
h.cfg.LayoutReadVolume = func(ctx context.Context, spec lifecycle.VolumeSpec) (layout.Volume, error) {
r, err := ref(spec)
if err != nil {
return layout.Volume{}, err
}
return cat.ReadVolume(ctx, r)
}
h.cfg.LayoutReadHead = func(ctx context.Context, spec lifecycle.VolumeSpec) (layout.Head, error) {
r, err := ref(spec)
if err != nil {
return layout.Head{}, err
}
hd, found, err := cat.ReadHead(ctx, r)
if err == nil && !found {
err = layout.ErrHeadAbsent
}
return hd, err
}
h.cfg.LayoutCreateTarget = func(ctx context.Context, source, target lifecycle.VolumeSpec, snapshot string) error {
s, err := ref(source)
if err != nil {
return err
}
tg, err := ref(target)
if err != nil {
return err
}
_, err = cat.Restore(ctx, s, snapshot, tg)
return err
}
return h, newServices(h), cat, filer
}
type catalogLease struct{}
func (catalogLease) OldLeaseEnded(context.Context, uint64) error { return nil }
// catalogSnapshot makes the volume hold a snapshot named name through the
// kernel's steps (Start, Begin, objects, Commit). With fromCurrent it
// snapshots the chunk its current root names at index 1 (a restore
// target's: the source's chunk); otherwise it writes one own chunk.
func catalogSnapshot(t *testing.T, cat *chunkstore.BCatalog, rec lifecycle.VolumeRecord, name string, fromCurrent bool) {
t.Helper()
ctx := context.Background()
v := catalogRef(t, rec.Spec)
st, err := cat.Store(v)
if err != nil {
t.Fatal(err)
}
g := layout.Geometry{SizeBytes: rec.Spec.SizeBytes, BlockSize: rec.Spec.BlockSize, ChunkBytes: rec.Spec.ChunkBytes}
me := layout.HolderID{Epoch: 1, Holder: "s/" + v.Name, ClaimID: "k-" + v.Name}
if _, err := layout.Start(ctx, st, catalogLease{}, layout.HolderID{Epoch: 1, Holder: me.Holder}, layout.LocalRoot{Geometry: g, ClaimID: me.ClaimID, Fresh: true, CanStartFrom: func(layout.Head) error { return nil }}); err != nil {
t.Fatal(err)
}
h, _, err := st.ReadHead(ctx)
if err != nil {
t.Fatal(err)
}
if _, err := layout.RunBegin(ctx, st, me, "s-"+name); err != nil {
t.Fatal(err)
}
var prev, next map[uint64]layout.Ref
if fromCurrent {
img, err := layout.NewReader("/blocks", v.Dir(), st.Fetch)
if err != nil {
t.Fatal(err)
}
im, err := img.Open(ctx, *h.Current)
if err != nil {
t.Fatal(err)
}
r, _, err := im.Resolve(ctx, 1)
if err != nil {
t.Fatal(err)
}
prev = map[uint64]layout.Ref{1: r}
next = prev
} else {
data := bytes.Repeat([]byte{0x5a}, int(g.BlockSize))
ch := layout.NameChunk(1, data)
if err := layout.EnsureObject(ctx, st, ch.Path(), data, "s-"+name); err != nil {
t.Fatal(err)
}
next = map[uint64]layout.Ref{1: {Owner: v.Name, OwnerID: v.ID, Chunk: ch}}
}
root, segs, err := layout.Build(next)
if err != nil {
t.Fatal(err)
}
for n, b := range segs {
if err := layout.EnsureObject(ctx, st, n.Path(), b, "s-"+name); err != nil {
t.Fatal(err)
}
}
rn, rb, err := layout.NameRoot(root)
if err != nil {
t.Fatal(err)
}
if err := layout.EnsureObject(ctx, st, rn.Path(), rb, "s-"+name); err != nil {
t.Fatal(err)
}
if _, err := layout.RunCommit(ctx, st, st, v.Name, me, layout.CommitRequest{Session: "s-" + name, Prev: prev, Next: next, Position: 1, Snapshot: name}); err != nil {
t.Fatalf("snapshot %s of %s: %v", name, v.Name, err)
}
}
func catalogGen(t *testing.T, cat *chunkstore.BCatalog, rec lifecycle.VolumeRecord) layout.Head {
t.Helper()
h, found, err := cat.ReadHead(context.Background(), catalogRef(t, rec.Spec))
if err != nil || !found {
t.Fatalf("HEAD of %s: found=%t %v", rec.Spec.VolumeID, found, err)
}
return h
}
// catalogSourceAndTarget: a source "src" with snapshot "daily", restored
// to "t", which takes a snapshot "copy" of the source's chunk.
func catalogSourceAndTarget(t *testing.T) (*Host, *services, *chunkstore.BCatalog, *countingFiler, lifecycle.VolumeRecord, lifecycle.VolumeRecord) {
t.Helper()
h, svc, cat, filer := catalogMaster(t)
ctx := context.Background()
if _, err := svc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "src", SizeBytes: 64 * 4096, ReplicationFactor: 1}); err != nil {
t.Fatal(err)
}
src, _ := h.Lifecycle().Volumes.GetVolume("src")
catalogSnapshot(t, cat, src, "daily", false)
if r, err := svc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "t", SourceVolume: "src", SourceSnapshot: "daily", CreateRequestId: "restore-t"}); err != nil || !r.GetStoreReady() {
t.Fatalf("setup restore: %+v %v", r, err)
}
tgt, _ := h.Lifecycle().Volumes.GetVolume("t")
catalogSnapshot(t, cat, tgt, "copy", true)
return h, svc, cat, filer, src, tgt
}
// Through the real catalog: a restore from a restore target's snapshot is
// refused before any filer write, and the master keeps no record of it.
func TestARealCatalogRestoreOfARestoreTargetLeavesNothing(t *testing.T) {
h, svc, cat, filer, src, tgt := catalogSourceAndTarget(t)
srcBefore, tgtBefore, writes := catalogGen(t, cat, src).Gen, catalogGen(t, cat, tgt).Gen, filer.count()
_, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "t2", SourceVolume: "t", SourceSnapshot: "copy", CreateRequestId: "restore-t2"})
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(err.Error(), "another volume's chunks") {
t.Fatalf("restore of a restore target's snapshot: %v; want FailedPrecondition naming the foreign chunks", err)
}
if rec, ok := h.Lifecycle().Volumes.GetVolume("t2"); ok {
t.Fatalf("the refused restore left the record %+v", rec)
}
if got := filer.count(); got != writes {
t.Fatalf("the refused restore made %d filer writes", got-writes)
}
if s, g := catalogGen(t, cat, src).Gen, catalogGen(t, cat, tgt).Gen; s != srcBefore || g != tgtBefore {
t.Fatalf("HEADs moved: source %d -> %d, target %d -> %d", srcBefore, s, tgtBefore, g)
}
}
// Control, through the real catalog: a target creation that fails after
// the dependent's write keeps its record, and the replay completes it with
// the same full target id.
func TestARealCatalogRestoreFailedAfterItsDependentKeepsItsIdentity(t *testing.T) {
h, svc, cat, filer, src, _ := catalogSourceAndTarget(t)
filer.failVolumeIn = "t3-"
req := &control.CreateVolumeRequest{VolumeId: "t3", SourceVolume: "src", SourceSnapshot: "daily", CreateRequestId: "restore-t3"}
if _, err := svc.CreateVolume(context.Background(), req); status.Code(err) != codes.Unavailable {
t.Fatalf("a restore that failed after its dependent: %v; want Unavailable (retry)", err)
}
rec, ok := h.Lifecycle().Volumes.GetVolume("t3")
if !ok || rec.StoreReady {
t.Fatalf("record %+v present=%t; want the not-ready record kept", rec, ok)
}
id := catalogRef(t, rec.Spec).ID
recorded := false
for _, d := range catalogGen(t, cat, src).Snapshots["daily"].Dependents {
recorded = recorded || d.TargetID == id
}
if !recorded {
t.Fatal("setup: the failure was not after the dependent's write")
}
resp, err := svc.CreateVolume(context.Background(), req)
if err != nil || !resp.GetStoreReady() || resp.GetLayoutId() != rec.Spec.LayoutID {
t.Fatalf("replay: %+v %v; want store-ready with the same layout id %s", resp, err, rec.Spec.LayoutID)
}
}
// A snapshot deleted between the master's check and the dependent's write
// (the refusal arrives from target creation) is NotFound, with no record.
func TestARestoreWhoseSnapshotWentAwayAfterTheCheckLeavesNoRecord(t *testing.T) {
h, svc, _ := restoreRefusalMaster(t, fmt.Errorf("%w: %q", layout.ErrNoSnapshot, "s1"))
_, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "target", SourceVolume: "source", SourceSnapshot: "s1", CreateRequestId: "restore-1"})
if status.Code(err) != codes.NotFound {
t.Fatalf("snapshot gone after the check: %v; want NotFound", err)
}
if rec, ok := h.Lifecycle().Volumes.GetVolume("target"); ok {
t.Fatalf("left the record %+v", rec)
}
}
// A record kept for the replay (an interrupted target creation, or a crash
// before a refused restore's removal) whose snapshot is gone by the replay:
// the replay stops at the master's own snapshot check and settles the record
// there (an absent snapshot proves no dependent of the target was written).
func TestAPendingRestoreRecordWhoseSnapshotIsGoneIsSettledByTheReplay(t *testing.T) {
h, svc, _ := restoreRefusalMaster(t, errors.New("filer unavailable"))
req := &control.CreateVolumeRequest{VolumeId: "target", SourceVolume: "source", SourceSnapshot: "s1", CreateRequestId: "restore-1"}
if _, err := svc.CreateVolume(context.Background(), req); status.Code(err) != codes.Unavailable {
t.Fatalf("setup: interrupted restore: %v", err)
}
if rec, ok := h.Lifecycle().Volumes.GetVolume("target"); !ok || rec.StoreReady {
t.Fatalf("setup: record %+v present=%t; want a kept not-ready record", rec, ok)
}
h.cfg.LayoutReadHead = func(_ context.Context, source lifecycle.VolumeSpec) (layout.Head, error) {
id, _ := layout.ParseVolumeID(source.LayoutID)
return layout.Head{VolumeID: id, State: layout.StateLive}, nil // "s1" deleted since
}
if _, err := svc.CreateVolume(context.Background(), req); status.Code(err) != codes.NotFound {
t.Fatalf("replay with the snapshot gone: %v; want NotFound", err)
}
if rec, ok := h.Lifecycle().Volumes.GetVolume("target"); ok {
t.Fatalf("the replay left the pending record %+v", rec)
}
h.cfg.LayoutCreateTarget = func(context.Context, lifecycle.VolumeSpec, lifecycle.VolumeSpec, string) error { return nil }
h.cfg.LayoutReadHead = func(_ context.Context, source lifecycle.VolumeSpec) (layout.Head, error) {
id, _ := layout.ParseVolumeID(source.LayoutID)
return layout.Head{VolumeID: id, State: layout.StateLive, Snapshots: map[string]layout.Snapshot{"s2": {}}}, nil
}
if r, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "target", SourceVolume: "source", SourceSnapshot: "s2", CreateRequestId: "restore-2"}); err != nil || !r.GetStoreReady() {
t.Fatalf("a new restore under the settled name: %+v %v", r, err)
}
}
// Lease renewal on a not-ready name: an admitted deletion is the untyped
// "being deleted", a committed one the typed DELETED; never the retry hint.
func TestRenewalOfADeletedNotReadyNameSaysDeleted(t *testing.T) {
h := newTestMaster(t, t.TempDir())
t.Cleanup(func() { closeTestMaster(t, h) })
h.cfg.WorkspaceRPC = true
svc := newServices(h)
h.cfg.LayoutCreateVolume = func(context.Context, lifecycle.VolumeSpec) error { return fmt.Errorf("filer unavailable") }
if _, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "x", SizeBytes: 1 << 20, ReplicationFactor: 1}); status.Code(err) != codes.Unavailable {
t.Fatalf("setup: not-ready create: %v", err)
}
if text, r := refusalOf(t, "not ready", svc.workspaceVolumeForRenewal("x")); text != "workspace: created, store not ready; retry CreateVolume" || r != nil {
t.Fatalf("control: not ready, not deleted: %q %v; want the retry hint", text, r)
}
if _, err := h.lifecycle.Deletions.Admit("x", "del-x"); err != nil {
t.Fatal(err)
}
if text, r := refusalOf(t, "admitted", svc.workspaceVolumeForRenewal("x")); text != "workspace: volume is being deleted" || r != nil {
t.Fatalf("admitted deletion: %q detail %v; want the untyped being-deleted refusal", text, r)
}
if _, err := h.lifecycle.Deletions.Commit("x", "del-x"); err != nil {
t.Fatal(err)
}
if text, r := refusalOf(t, "committed", svc.workspaceVolumeForRenewal("x")); text != "workspace: volume is being deleted" || r == nil || r.GetKind() != control.WorkspaceLeaseRefusal_DELETED {
t.Fatalf("committed deletion: %q detail %v; want typed DELETED", text, r)
}
}
@@ -100,7 +100,7 @@ func TestWorkspaceShowOfADeletedNotReadyNameSaysDeleted(t *testing.T) {
if _, err := h.lifecycle.Deletions.Admit("x", "del-x"); err != nil {
t.Fatal(err)
}
if _, err := svc.QueryWorkspace(context.Background(), q); status.Convert(err).Message() != "workspace: volume is being deleted" {
t.Fatalf("a deleted not-ready name: %v; want 'workspace: volume is being deleted'", err)
if _, err := svc.QueryWorkspace(context.Background(), q); status.Code(err) != codes.FailedPrecondition || status.Convert(err).Message() != "workspace: volume is being deleted" {
t.Fatalf("a deleted not-ready name: %v; want FailedPrecondition 'workspace: volume is being deleted'", err)
}
}
@@ -0,0 +1,58 @@
package master
import (
"context"
"errors"
"fmt"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// A removal that fails answers a retry, not the refusal, and keeps the
// record; the replay removes it. For a foreign snapshot the replay is
// refused again by target creation; for a snapshot gone since, the replay
// stops at the master's own check and settles the record there.
func TestAFailedRecordRemovalIsARetryAndTheReplaySettlesIt(t *testing.T) {
for _, tc := range []struct {
name string
refuse error
replay codes.Code
gone bool // the snapshot is absent at the replay's check
}{
{"foreign snapshot", fmt.Errorf("%w: %q", layout.ErrForeignSource, "s1"), codes.FailedPrecondition, false},
{"snapshot gone, then absent at the check", fmt.Errorf("%w: %q", layout.ErrNoSnapshot, "s1"), codes.NotFound, true},
} {
t.Run(tc.name, func(t *testing.T) {
h, svc, _ := restoreRefusalMaster(t, tc.refuse)
prior := undoRestoreRecord
t.Cleanup(func() { undoRestoreRecord = prior })
undoRestoreRecord = func(*Host, string) error { return errors.New("fixture: lifecycle store write failed") }
req := &control.CreateVolumeRequest{VolumeId: "target", SourceVolume: "source", SourceSnapshot: "s1", CreateRequestId: "restore-1"}
if _, err := svc.CreateVolume(context.Background(), req); status.Code(err) != codes.Unavailable {
t.Fatalf("failed removal: %v; want Unavailable (retry)", err)
}
if rec, ok := h.Lifecycle().Volumes.GetVolume("target"); !ok || rec.StoreReady {
t.Fatalf("failed removal: record %+v present=%t; want it kept, not ready", rec, ok)
}
undoRestoreRecord = prior
if tc.gone {
h.cfg.LayoutReadHead = func(_ context.Context, source lifecycle.VolumeSpec) (layout.Head, error) {
id, _ := layout.ParseVolumeID(source.LayoutID)
return layout.Head{VolumeID: id, State: layout.StateLive}, nil
}
}
if _, err := svc.CreateVolume(context.Background(), req); status.Code(err) != tc.replay {
t.Fatalf("replay: %v; want %v", err, tc.replay)
}
if rec, ok := h.Lifecycle().Volumes.GetVolume("target"); ok {
t.Fatalf("replay left the record %+v", rec)
}
})
}
}
+20 -2
View File
@@ -123,6 +123,16 @@ func (s *services) CreateVolume(ctx context.Context, req *control.CreateVolumeRe
return nil, status.Error(codes.FailedPrecondition, "restore source HEAD is absent, foreign or not live/detached")
}
if _, ok := head.Snapshots[spec.SourceSnapshot]; !ok {
// A replay whose earlier attempt wrote the target's record and then
// stopped (a crash, or a removal that failed) settles it here: a
// recorded dependent keeps its snapshot, so an absent snapshot
// proves the target was never recorded on the source, and nothing
// in the filer names it. The request tuple was matched above.
if existing, ok := stores.Volumes.GetVolume(spec.VolumeID); ok && !existing.StoreReady && existing.Spec.SourceLayoutID == source.Spec.LayoutID {
if err := undoRestoreRecord(s.host, spec.VolumeID); err != nil {
return nil, status.Errorf(codes.Unavailable, "restore source snapshot %q is absent; the target's pending record was not removed: %v; retry", spec.SourceSnapshot, err)
}
}
return nil, status.Errorf(codes.NotFound, "restore source snapshot %q is absent", spec.SourceSnapshot)
}
spec.SourceLayoutID = source.Spec.LayoutID
@@ -162,6 +172,12 @@ func (s *services) CreateVolume(ctx context.Context, req *control.CreateVolumeRe
var errLayoutStoreNotReady = errors.New("layout store not ready")
// undoRestoreRecord removes a refused restore's not-ready record; a variable
// so a test can make the removal fail.
var undoRestoreRecord = func(h *Host, volumeID string) error {
return h.lifecycle.Volumes.DeleteVolume(volumeID)
}
// restoreRefusedForGood: target creation refused the restore before any
// write (RunAddDependent's checks, ahead of its update), for a reason no
// replay changes: the snapshot names another volume's chunks, or it is
@@ -203,8 +219,10 @@ func (h *Host) createLifecycleVolume(ctx context.Context, spec lifecycle.VolumeS
// Refused before it wrote anything, and a replay is refused the
// same way (a snapshot's root never changes): a refused restore
// changes nothing, so its not-ready record goes too.
if err := h.lifecycle.Volumes.DeleteVolume(rec.Spec.VolumeID); err != nil {
return lifecycle.VolumeRecord{}, fmt.Errorf("%w: %w (undo of its record: %v)", errLayoutStoreNotReady, createErr, err)
if err := undoRestoreRecord(h, rec.Spec.VolumeID); err != nil {
// Not the refusal's answer: the record stays, so this is a
// retry (Unavailable), and the replay removes it.
return lifecycle.VolumeRecord{}, fmt.Errorf("%w: %v; its pending record was not removed: %v", errLayoutStoreNotReady, createErr, err)
}
return lifecycle.VolumeRecord{}, createErr
}