From 79055a1e74311f6b48e9d729509827f60f11b29a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 16:08:18 -0800 Subject: [PATCH 1/2] fix(snapshot): refuse a snapshot past the limit before its cut A snapshot request on a volume already holding the maximum number of snapshots ran its cut first and met the limit only at the commit. With new data, the cut committed unnamed; with none, the cut's session stayed open on HEAD. Either way HEAD moved, and the answer was 500 internal because the HTTP mapping had no case for the limit or for a taken name. SnapshotVolume now checks the count under the volume's snapshot lock, before it names the cut or opens a session, so the refusal writes nothing. The holder answers 409 snapshot_limit (new code) and 409 snapshot_exists, neither retryable. The in-commit check stays as the backstop. Tests: the snapshot past the limit through the real provider, chunk control and HTTP route answers 409 snapshot_limit with HEAD unchanged (generation, activity, root, position), with nothing new and with new data waiting; the provider test changes from "the cut commits unnamed" to the same; a volume-delete under a live lease against the real master answers not_admitted with "deletion refused before persistence". Co-Authored-By: Claude Opus 5.5 --- .../chunk_volume_delete_refusal_test.go | 62 ++++++++++++++ .../core/frontend/chunkstore/control_types.go | 1 + .../durable/provider_layout_snapshot.go | 11 ++- .../durable/provider_layout_snapshot_test.go | 29 +++++-- .../core/host/volume/chunk_control.go | 4 + .../host/volume/chunk_snapshot_limit_test.go | 85 +++++++++++++++++++ .../volume/chunk_snapshot_refusal_test.go | 27 ++++++ seaweed-block/docs/operator-guide.md | 5 ++ 8 files changed, 215 insertions(+), 9 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/chunk_volume_delete_refusal_test.go create mode 100644 seaweed-block/core/host/volume/chunk_snapshot_limit_test.go create mode 100644 seaweed-block/core/host/volume/chunk_snapshot_refusal_test.go diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete_refusal_test.go b/seaweed-block/cmd/sw-block/chunk_volume_delete_refusal_test.go new file mode 100644 index 0000000000..51875a6fd6 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete_refusal_test.go @@ -0,0 +1,62 @@ +package main + +import ( + "bytes" + "context" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// A delete of an established volume (its primary attested its write-ACK +// stores, so creation is over) whose line holds a live lease is refused by +// the real master's reservation before anything is persisted, and the +// command's JSON answer says so: code not_admitted and the "refused before +// persistence" sentence. HEAD stays live and no reservation is recorded. +func TestOpsChunkVolumeDeleteRefusalSaysNothingWasPersisted(t *testing.T) { + cfg := master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }} + h, stop := startDeleteMaster(t, cfg) + defer stop() + seedForcedVolumeLease(t, h, true) + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + // The primary's attestation of its stores ends creation, as its heartbeat + // carries it in production. + if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-f", ReplicaId: "r1", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}}, + StoreAttestation: &control.StoreAttestation{VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1, Stores: []*control.AttestedStore{{ReplicaId: "r1", StoreId: bytes.Repeat([]byte{7}, 16)}}}}); err != nil { + t.Fatal(err) + } + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "vol-f", "daily") + code, out, stderr := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", h.Addr(), "--request-id", "live-lease"})...) + body := chunkErrorOut(t, out) + t.Logf("exit %d answer %+v", code, body) + if code != chunkExitFailed || body.Code != "not_admitted" || + !strings.Contains(body.Message, "deletion refused before persistence") { + t.Fatalf("volume-delete with a live lease: exit %d answer %+v stderr %s; want not_admitted saying it was refused before persistence", code, body, stderr) + } + if h.Lifecycle().Deletions.Reserved("vol-f") { + t.Fatal("the refused delete recorded a reservation") + } + cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + if hd, found, err := cat.ReadHead(context.Background(), v); err != nil || !found || hd.State != layout.StateLive { + t.Fatalf("HEAD after the refused delete: %+v %v %v; want live", hd, found, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/control_types.go b/seaweed-block/core/frontend/chunkstore/control_types.go index f76f0e8e22..3efd29a1bf 100644 --- a/seaweed-block/core/frontend/chunkstore/control_types.go +++ b/seaweed-block/core/frontend/chunkstore/control_types.go @@ -42,6 +42,7 @@ const ( CodeNotChunkVolume = "not_chunk_volume" CodeInvalidName = "invalid_name" CodeSnapshotExists = "snapshot_exists" + CodeSnapshotLimit = "snapshot_limit" CodeSnapshotNotFound = "snapshot_not_found" CodeSnapshotDeleting = "snapshot_deleting" CodeTargetExists = "target_exists" diff --git a/seaweed-block/core/frontend/durable/provider_layout_snapshot.go b/seaweed-block/core/frontend/durable/provider_layout_snapshot.go index de76dc7132..efd9afbe05 100644 --- a/seaweed-block/core/frontend/durable/provider_layout_snapshot.go +++ b/seaweed-block/core/frontend/durable/provider_layout_snapshot.go @@ -27,8 +27,10 @@ var snapshotLocks sync.Map // volume -> *sync.Mutex // commit (the engine's barrier gives the image at H); when the cut had // nothing to publish, the current image is named by a commit of its own. // A replay of a name already in HEAD returns the facts recorded there. A -// name or facts the kernel refuses is the typed refusal; the cut itself -// still commits unnamed. It returns HEAD with the name recorded +// HEAD already at layout.MaxSnapshots refuses a new name before the cut +// opens a session, so the refusal writes nothing. A name the commit itself +// refuses (the backstop) is the typed refusal and the cut still commits +// unnamed. It returns HEAD with the name recorded // (chunkstore.SnapshotInfoFromHead makes the request's answer). func (p *DurableProvider) SnapshotVolume(ctx context.Context, volumeID, name string, meta layout.SnapshotMeta) (layout.Head, error) { if err := layout.CheckSnapshot(name, meta); err != nil { @@ -53,6 +55,11 @@ func (p *DurableProvider) SnapshotVolume(ctx context.Context, volumeID, name str if _, ok := h.Snapshots[name]; ok { return h, nil } + // Only this path adds a name, under the volume's lock, so the count read + // here is the one the commit would check. + if len(h.Snapshots) >= layout.MaxSnapshots { + return layout.Head{}, fmt.Errorf("%w: at most %d per volume; delete a snapshot, or let retention prune", layout.ErrTooManySnapshots, layout.MaxSnapshots) + } sr.SetSnapshot(name, meta) // A request that fails withdraws its name: the cut may keep its session // for a retry, and the name must not ride onto that later image. diff --git a/seaweed-block/core/frontend/durable/provider_layout_snapshot_test.go b/seaweed-block/core/frontend/durable/provider_layout_snapshot_test.go index f5a288ea34..e51193ce08 100644 --- a/seaweed-block/core/frontend/durable/provider_layout_snapshot_test.go +++ b/seaweed-block/core/frontend/durable/provider_layout_snapshot_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "reflect" "strings" "testing" "time" @@ -90,13 +91,26 @@ func TestLayoutProviderSnapshotVolume(t *testing.T) { if _, err := p.SnapshotVolume(ctx, "v1", strings.Repeat("n", layout.MaxSnapshotNameBytes+1), layout.SnapshotMeta{}); !errors.Is(err, layout.ErrMalformed) { t.Fatalf("too-long name: %v; want ErrMalformed", err) } - // The cap: snapshots up to it are named; past it, the cut still commits - // (new data reaches HEAD, unnamed) and the request gets the typed error. + // The cap: snapshots up to it are named; past it the request gets the + // typed error before its cut opens a session, so HEAD is unchanged (same + // generation, activity idle, same root and position), with nothing new + // to publish and with new data waiting. for i := len(head().Snapshots); i < layout.MaxSnapshots; i++ { if _, err := p.SnapshotVolume(ctx, "v1", "s"+string(rune('a'+i)), layout.SnapshotMeta{CreatedNs: int64(20 + i)}); err != nil { t.Fatalf("snapshot %d: %v", i+1, err) } } + refusedPastCap := func(what string) { + t.Helper() + before := head() + if _, err := p.SnapshotVolume(ctx, "v1", "over", layout.SnapshotMeta{CreatedNs: 50}); !errors.Is(err, layout.ErrTooManySnapshots) { + t.Fatalf("%s: snapshot past the cap: %v; want ErrTooManySnapshots", what, err) + } + if after := head(); !reflect.DeepEqual(after, before) || after.Activity.Kind != layout.ActIdle { + t.Fatalf("%s: a refused snapshot changed HEAD: before %+v, after %+v", what, before, after) + } + } + refusedPastCap("nothing new") before := head() if _, err = ws.Write(1, bytes.Repeat([]byte{'B'}, 4096)); err != nil { t.Fatal(err) @@ -104,12 +118,13 @@ func TestLayoutProviderSnapshotVolume(t *testing.T) { if _, err = ws.Sync(); err != nil { t.Fatal(err) } - if _, err := p.SnapshotVolume(ctx, "v1", "over", layout.SnapshotMeta{CreatedNs: 50}); !errors.Is(err, layout.ErrTooManySnapshots) { - t.Fatalf("snapshot past the cap: %v; want ErrTooManySnapshots", err) + refusedPastCap("new data waiting") + // The waiting data reaches HEAD by the next ordinary cut. + if _, err := p.CutVolume(ctx, "v1", 0); err != nil { + t.Fatalf("cut after the refusal: %v", err) } - after := head() - if _, named := after.Snapshots["over"]; named || after.Position <= before.Position || *after.Current == *before.Current { - t.Fatalf("past the cap: named %t, position %d -> %d; want the cut committed unnamed", named, before.Position, after.Position) + if after := head(); after.Position <= before.Position || *after.Current == *before.Current || len(after.Snapshots) != layout.MaxSnapshots { + t.Fatalf("cut after the refusal: position %d -> %d, %d snapshots", before.Position, after.Position, len(after.Snapshots)) } // A replay after later cuts answers with the facts recorded when the // name was taken, not HEAD's current position or root. diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 31eb6eb2b6..ce965837b0 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -302,6 +302,10 @@ func chunkErrorCode(err error) (int, string, bool) { return http.StatusServiceUnavailable, chunkstore.CodeOutcomeUnknown, true case errors.Is(err, layout.ErrGeometryMismatch): return http.StatusConflict, chunkstore.CodeGeometryMismatch, false + case errors.Is(err, layout.ErrTooManySnapshots): + return http.StatusConflict, chunkstore.CodeSnapshotLimit, false + case errors.Is(err, layout.ErrSnapshotExists): + return http.StatusConflict, chunkstore.CodeSnapshotExists, false case errors.Is(err, layout.ErrHeadAbsent), errors.Is(err, layout.ErrNoSnapshot): return http.StatusNotFound, "not_found", false case errors.Is(err, layout.ErrHasDependents), errors.Is(err, layout.ErrVolumeDeleting), errors.Is(err, layout.ErrDetached), errors.Is(err, layout.ErrIdentity): diff --git a/seaweed-block/core/host/volume/chunk_snapshot_limit_test.go b/seaweed-block/core/host/volume/chunk_snapshot_limit_test.go new file mode 100644 index 0000000000..33c4e09875 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_snapshot_limit_test.go @@ -0,0 +1,85 @@ +package volume + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "reflect" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" +) + +// Through the real provider, chunk control and HTTP route: the snapshot past +// the per-volume limit answers 409 snapshot_limit and writes nothing (HEAD +// keeps its generation, idle activity, root and position), with nothing new +// to publish and with new data waiting. The next ordinary cut publishes the +// waiting data. +func TestChunkSnapshotPastTheLimitIsRefusedWithHEADUnchanged(t *testing.T) { + ctx := context.Background() + fixture := testutil.NewLayoutFixture(t, "v1", 256, 16) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16} + fixture.Configure(&cfg) + dp, err := durable.NewDurableProvider(cfg, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dp.Close() }) + s, err := dp.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err := dp.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + head := func() layout.Head { + h, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found { + t.Fatalf("HEAD: found=%v err=%v", found, err) + } + return h + } + server := chunkServer(t, NewChunkControl(dp, fixture.Catalog, fixture.Ref), true) + snapshot := func(name string) (int, string) { + w := serve(t, server, http.MethodPost, "/chunk/snapshot", fmt.Sprintf(`{"volumeID":"v1","name":%q,"requestID":%q}`, name, "req-"+name), "") + var body struct { + Code string `json:"code"` + } + _ = json.Unmarshal(w.Body.Bytes(), &body) + return w.Code, body.Code + } + if _, err := s.Write(0, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + for i := 0; i < layout.MaxSnapshots; i++ { + if status, code := snapshot(fmt.Sprintf("s%d", i)); status != http.StatusOK { + t.Fatalf("snapshot %d: %d %s", i+1, status, code) + } + } + refused := func(what string) { + t.Helper() + before := head() + if status, code := snapshot("over"); status != http.StatusConflict || code != chunkstore.CodeSnapshotLimit { + t.Fatalf("%s: snapshot %d answered %d %s; want 409 %s", what, layout.MaxSnapshots+1, status, code, chunkstore.CodeSnapshotLimit) + } + if after := head(); !reflect.DeepEqual(after, before) || after.Activity.Kind != layout.ActIdle { + t.Fatalf("%s: the refused snapshot changed HEAD: before %+v, after %+v", what, before, after) + } + } + refused("nothing new") + if _, err := s.Write(1, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + refused("new data waiting") + before := head() + if _, err := dp.CutVolume(ctx, "v1", 0); err != nil { + t.Fatalf("cut after the refusals: %v", err) + } + if after := head(); after.Position <= before.Position || len(after.Snapshots) != layout.MaxSnapshots { + t.Fatalf("cut after the refusals: position %d -> %d, %d snapshots", before.Position, after.Position, len(after.Snapshots)) + } +} diff --git a/seaweed-block/core/host/volume/chunk_snapshot_refusal_test.go b/seaweed-block/core/host/volume/chunk_snapshot_refusal_test.go new file mode 100644 index 0000000000..6a4d5ac16f --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_snapshot_refusal_test.go @@ -0,0 +1,27 @@ +package volume + +import ( + "fmt" + "net/http" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// A snapshot the volume cannot name is a typed, final refusal: past the +// per-volume limit, or a name another snapshot already holds. +func TestChunkSnapshotRefusalsAreTyped(t *testing.T) { + for _, c := range []struct { + err error + code string + }{ + {layout.ErrTooManySnapshots, chunkstore.CodeSnapshotLimit}, + {layout.ErrSnapshotExists, chunkstore.CodeSnapshotExists}, + } { + status, code, retry := chunkErrorCode(fmt.Errorf("%w: at most 10 per volume", c.err)) + if status != http.StatusConflict || code != c.code || retry { + t.Errorf("%v: %d %s retryable=%v; want 409 %s, not retryable", c.err, status, code, retry, c.code) + } + } +} diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index b55c515ff3..c4d3263b24 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -206,6 +206,11 @@ A late upload by a dead holder into a deleted volume can remain; rerun volume-de - `ops chunk verify`; - restoring a snapshot into a new volume, which reads the chunks it has not made local from that snapshot (fork is not supported in this release). +A volume holds at most 10 snapshots. The next one is refused with `snapshot_limit` (HTTP 409, not retryable; +`at most 10 per volume; delete a snapshot, or let retention prune`) and nothing changes: no snapshot, no cut, HEAD +as it was (`TestChunkSnapshotPastTheLimitIsRefusedWithHEADUnchanged`). Delete a snapshot, or let retention prune, +then take it again. + A snapshot can be refused with `host_slot_busy` / `no background slot` (retryable) while every host slot is held by other volumes' cuts; retry with the same request id. With many volumes on a host, a snapshot may wait for a slot: measured up to 15 s at 32 volumes with the default 3 slots. From 2d374aaee53e0637748c51ede0b0ed9535142536 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 16:19:01 -0800 Subject: [PATCH 2/2] fix(snapshot): a scheduled snapshot at the limit still publishes A volume at the snapshot limit refuses every scheduled snapshot before its cut, so the schedule would no longer publish the image. The scheduled pass now runs its ordinary cut after a snapshot_limit refusal and still records the refusal (status lastFailure snapshot_limit, then snapshot_overdue). Tests read the committed image back: after the refusals and the next cut, and after the scheduled pass at the limit, the distinctive block written while refused is in the image HEAD names. INV-SNAPK-HEAD-BOUND-001 names the pre-check, the mapping, the scheduled cut and their tests. Co-Authored-By: Claude Opus 5.5 --- .../host/volume/chunk_scheduled_snapshot.go | 14 ++- .../host/volume/chunk_snapshot_limit_test.go | 99 ++++++++++++++++++- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/operator-guide.md | 4 +- 4 files changed, 112 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go b/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go index b552790991..dfd149c26a 100644 --- a/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go +++ b/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go @@ -2,6 +2,7 @@ package volume import ( "context" + "errors" "strconv" "time" @@ -18,12 +19,21 @@ func ScheduledSnapshotName(at time.Time) string { } // ScheduledSnapshot uses the same snapshot commit as an explicit snapshot; -// it never follows an ordinary cut with a second catalog write. +// it never follows an ordinary cut with a second catalog write. A volume +// already at the snapshot limit refuses the name before any cut; the +// scheduled pass then still publishes the image by an ordinary cut, so +// the schedule keeps HEAD current, and records the refusal (status +// lastFailure snapshot_limit, then snapshot_overdue). func ScheduledSnapshot(snapshot func(context.Context, string, string, layout.SnapshotMeta) (chunkstore.SnapshotInfo, error), keep int) func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error { - return func(ctx context.Context, volumeID string, at time.Time, _ func(context.Context) (storage.ChunkHead, error)) error { + return func(ctx context.Context, volumeID string, at time.Time, cut func(context.Context) (storage.ChunkHead, error)) error { meta := layout.SnapshotMeta{CreatedNs: at.UnixNano(), Class: layout.ClassScheduled, Labels: map[string]string{retain.LabelScheduleKeep: strconv.Itoa(keep)}} if _, err := snapshot(ctx, volumeID, ScheduledSnapshotName(at), meta); err != nil { _, code, _ := chunkErrorCode(err) + if errors.Is(err, layout.ErrTooManySnapshots) && cut != nil { + if _, cutErr := cut(ctx); cutErr != nil { + err = errors.Join(err, cutErr) + } + } return &durable.SnapshotFailure{Code: code, Err: err} } return nil diff --git a/seaweed-block/core/host/volume/chunk_snapshot_limit_test.go b/seaweed-block/core/host/volume/chunk_snapshot_limit_test.go index 33c4e09875..56189398b3 100644 --- a/seaweed-block/core/host/volume/chunk_snapshot_limit_test.go +++ b/seaweed-block/core/host/volume/chunk_snapshot_limit_test.go @@ -1,17 +1,21 @@ package volume import ( + "bytes" "context" "encoding/json" + "errors" "fmt" "net/http" "reflect" "testing" + "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" + "github.com/seaweedfs/seaweed-block/core/storage" ) // Through the real provider, chunk control and HTTP route: the snapshot past @@ -19,7 +23,10 @@ import ( // keeps its generation, idle activity, root and position), with nothing new // to publish and with new data waiting. The next ordinary cut publishes the // waiting data. -func TestChunkSnapshotPastTheLimitIsRefusedWithHEADUnchanged(t *testing.T) { +// limitVolume is a chunk volume through the real provider (as blockvolume +// builds it), with its write path and a HEAD reader. +func limitVolume(t *testing.T) (*durable.DurableProvider, *testutil.LayoutFixture, storage.LogicalStorage, func() layout.Head) { + t.Helper() ctx := context.Background() fixture := testutil.NewLayoutFixture(t, "v1", 256, 16) cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16} @@ -43,6 +50,44 @@ func TestChunkSnapshotPastTheLimitIsRefusedWithHEADUnchanged(t *testing.T) { } return h } + return dp, fixture, s, head +} + +// committedBlock reads block lba of HEAD's current image from the store +// (the root, its segment, the chunk), not from the holder's cache. +func committedBlock(t *testing.T, fixture *testutil.LayoutFixture, h layout.Head, lba uint64) []byte { + t.Helper() + ctx := context.Background() + if h.Current == nil { + t.Fatal("HEAD names no image") + } + st, err := fixture.Catalog.Store(fixture.Ref) + if err != nil { + t.Fatal(err) + } + r, err := layout.NewReader("/provider-test", fixture.Ref.Dir(), st.Fetch) // testutil.NewLayoutFixture's base + if err != nil { + t.Fatal(err) + } + img, err := r.Open(ctx, *h.Current) + if err != nil { + t.Fatal(err) + } + const chunkBlocks = 16 // limitVolume's geometry + c, err := img.Chunk(ctx, lba/chunkBlocks) + if err != nil { + t.Fatal(err) + } + if c.Zero { + return make([]byte, 4096) + } + off := (lba % chunkBlocks) * 4096 + return c.Data[off : off+4096] +} + +func TestChunkSnapshotPastTheLimitIsRefusedWithHEADUnchanged(t *testing.T) { + ctx := context.Background() + dp, fixture, s, head := limitVolume(t) server := chunkServer(t, NewChunkControl(dp, fixture.Catalog, fixture.Ref), true) snapshot := func(name string) (int, string) { w := serve(t, server, http.MethodPost, "/chunk/snapshot", fmt.Sprintf(`{"volumeID":"v1","name":%q,"requestID":%q}`, name, "req-"+name), "") @@ -71,7 +116,8 @@ func TestChunkSnapshotPastTheLimitIsRefusedWithHEADUnchanged(t *testing.T) { } } refused("nothing new") - if _, err := s.Write(1, make([]byte, 4096)); err != nil { + waiting := bytes.Repeat([]byte("past-the-limit:1"), 4096/16) + if _, err := s.Write(1, waiting); err != nil { t.Fatal(err) } refused("new data waiting") @@ -79,7 +125,54 @@ func TestChunkSnapshotPastTheLimitIsRefusedWithHEADUnchanged(t *testing.T) { if _, err := dp.CutVolume(ctx, "v1", 0); err != nil { t.Fatalf("cut after the refusals: %v", err) } - if after := head(); after.Position <= before.Position || len(after.Snapshots) != layout.MaxSnapshots { + after := head() + if after.Position <= before.Position || len(after.Snapshots) != layout.MaxSnapshots { t.Fatalf("cut after the refusals: position %d -> %d, %d snapshots", before.Position, after.Position, len(after.Snapshots)) } + if got := committedBlock(t, fixture, after, 1); !bytes.Equal(got, waiting) { + t.Fatalf("block 1 of the image committed after the refusals: %q...; want the data written while refused", got[:16]) + } +} + +// The scheduled snapshot on a volume at the limit (snapshots the schedule's +// retention does not prune) is refused and recorded as snapshot_limit, and +// its pass still publishes the waiting data by an ordinary cut: the +// schedule keeps HEAD current while the volume is full. +func TestScheduledSnapshotAtTheLimitStillPublishes(t *testing.T) { + ctx := context.Background() + dp, fixture, s, head := limitVolume(t) + for i := 0; i < layout.MaxSnapshots; i++ { + if _, err := dp.SnapshotVolume(ctx, "v1", fmt.Sprintf("op%d", i), layout.SnapshotMeta{CreatedNs: int64(i + 1), Class: layout.ClassSemantic}); err != nil { + t.Fatalf("snapshot %d: %v", i+1, err) + } + } + waiting := bytes.Repeat([]byte("scheduled-full:2"), 4096/16) + if _, err := s.Write(2, waiting); err != nil { + t.Fatal(err) + } + snapshot := func(ctx context.Context, vol, name string, meta layout.SnapshotMeta) (chunkstore.SnapshotInfo, error) { + h, err := dp.SnapshotVolume(ctx, vol, name, meta) + if err != nil { + return chunkstore.SnapshotInfo{}, err + } + return chunkstore.SnapshotInfoFromHead(vol, name, h), nil + } + cut := func(ctx context.Context) (storage.ChunkHead, error) { // as the schedule loop cuts + r, err := dp.CutVolume(ctx, "v1", 0) + return r.Head, err + } + before := head() + err := ScheduledSnapshot(snapshot, 7)(ctx, "v1", time.Now(), cut) + var failure *durable.SnapshotFailure + if !errors.As(err, &failure) || failure.Code != chunkstore.CodeSnapshotLimit { + t.Fatalf("scheduled snapshot at the limit: %v; want a SnapshotFailure with code %s", err, chunkstore.CodeSnapshotLimit) + } + after := head() + if after.Position <= before.Position || *after.Current == *before.Current || len(after.Snapshots) != layout.MaxSnapshots || after.Activity.Kind != layout.ActIdle { + t.Fatalf("scheduled pass at the limit: position %d -> %d, %d snapshots, activity %s; want the data published unnamed", + before.Position, after.Position, len(after.Snapshots), after.Activity.Kind) + } + if got := committedBlock(t, fixture, after, 2); !bytes.Equal(got, waiting) { + t.Fatalf("block 2 of the image the scheduled pass published: %q...; want the data written before it", got[:16]) + } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 72e81d7517..c65c5ba46a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1089,7 +1089,7 @@ Notes: | `INV-SNAPK-RESTORE-ORDER-001` | Master checks the source HEAD and named snapshot and refuses RF>1 before persisting. The target binds source layout id, snapshot, request id and VOLUME geometry as not-ready; then AddDependent, copy root/segments, create VOLUME and unclaimed HEAD, and mark ready. A retry keeps the binding. | M9 source HEAD, dependents | `core/lifecycle/store.go` `CreateVolume`; `core/host/master/services.go` `CreateVolume`; `core/frontend/chunkstore/layout/create.go` `CreateTarget`; `cmd/sw-block/chunk_b.go` `chunkRestore` | `TestRestoreRequestBindsTargetName`, `TestRestoreCreateVolumePersistsRequestBeforeTargetAndHealsRetry`, `TestOpsChunkRestoreUsesOnlyMasterCreate`, `TestCreateTarget`, `TestRunAddDependent_RefusesAForeignSource` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-SNAP-DELETE-001` | A named snapshot leaves HEAD by one conditional update, refused while it has dependents; the automatic delete (retention) also refuses a snapshot pinned at its time. | M9 idle → idle | `core/frontend/chunkstore/layout` `snapshots.go` `Head.DeleteSnapshot`, `Head.RetireSnapshot` | `TestDeleteSnapshot_Closure`, `TestRetireSnapshot_Closure`, `TestRunRetireSnapshot_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `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. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `check`, `Encode`; `snapshots.go` `AddDependent` | `TestHead_SizeAtTheSnapshotCap`, `TestHead_BoundsRefused` | — (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 | | `INV-SNAPK-RELEASE-001` | A target is released from a source's dependents by its volume id, from every snapshot, in one conditional update; a volume created again under its name releases nothing; an absent target writes nothing. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `Head.ReleaseDependent`, `RunReleaseDependent` | `TestReleaseDependent_Closure`, `TestRunReleaseDependent_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-CALLERS-001` | Only the target's own delete (its HEAD already deleting) and the operator's command release a dependent; a source scan restricts the callers and requires the operator's read of the target. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-OPERATOR-001` | The operator's command releases a target that is deleted (HEAD deleting or deleted, or its directory's VOLUME of another id), one whose live roots name no chunk of the source, or one without HEAD, after its tombstone. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index c4d3263b24..1eb863e8ab 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -209,7 +209,9 @@ A late upload by a dead holder into a deleted volume can remain; rerun volume-de A volume holds at most 10 snapshots. The next one is refused with `snapshot_limit` (HTTP 409, not retryable; `at most 10 per volume; delete a snapshot, or let retention prune`) and nothing changes: no snapshot, no cut, HEAD as it was (`TestChunkSnapshotPastTheLimitIsRefusedWithHEADUnchanged`). Delete a snapshot, or let retention prune, -then take it again. +then take it again. A scheduled snapshot refused this way still publishes the volume's image by an ordinary cut, +and `GET STATUS/status/durable?volume=` shows `Chunk.ScheduledSnapshot.lastFailure.code: snapshot_limit`, then +`snapshot_overdue` (`TestScheduledSnapshotAtTheLimitStillPublishes`). A snapshot can be refused with `host_slot_busy` / `no background slot` (retryable) while every host slot is held by other volumes' cuts; retry with the same request id. With many volumes on a host, a snapshot may wait for a slot: