From a4de2484f9c0d82b2fe725e28bbbdb4e4a082191 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 19:47:42 -0800 Subject: [PATCH 1/8] chunkstore: independent restore, catalog part (Restore, OriginRestore, independence marker) Restore is Fork recorded with Origin restore (same claim semantics: live until the target has a HEAD). Every reader of the fork record accepts OriginRestore; a replay onto a volume of the other origin is refused. MarkIndependent writes the write-once RESTORE-INDEPENDENT entry only when the resolved HEAD holds no ref to another volume (ForeignRefs: owner-qualified keys whose owner is not the volume). Tests: restore records origin/fork record and attaches; replay and origin mismatch; marker refused while foreign refs remain, write-once replay; source snapshot and source volume deleted mid-restore (attach, replay and finish stay normal); GC keeps every chunk the restored HEAD names with the snapshot and the source gone; a restore without a live HEAD never attaches. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 46 ++- .../core/frontend/chunkstore/gc_copy.go | 2 +- .../core/frontend/chunkstore/restore.go | 154 ++++++++++ .../core/frontend/chunkstore/restore_test.go | 265 ++++++++++++++++++ 4 files changed, 456 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/restore.go create mode 100644 seaweed-block/core/frontend/chunkstore/restore_test.go diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index eb6fd6f4eb..a3b93e5e09 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -70,9 +70,12 @@ const ( // SnapAbsent is DeleteSnapshot's answer for a snapshot that is not there. SnapAbsent = "absent" - // OriginCreate and OriginFork are a volume's origins. - OriginCreate = "create" - OriginFork = "fork" + // OriginCreate, OriginFork and OriginRestore are a volume's origins. A + // restore is a fork whose volume later becomes independent of its source + // (own chunks, restoreIndependentName written); until then it is a fork. + OriginCreate = "create" + OriginFork = "fork" + OriginRestore = "restore" // DefaultOpDeadline bounds a snapshot or fork from reading its source to // its final write (spec §2.3). @@ -395,10 +398,10 @@ func decodeVolume(p string, e *filerpb.Entry) (VolumeInfo, error) { if v.Format != volumeFormat { return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: format %d not supported", p, v.Format) } - if v.Origin != OriginCreate && v.Origin != OriginFork { + if v.Origin != OriginCreate && v.Origin != OriginFork && v.Origin != OriginRestore { return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: origin %q", p, v.Origin) } - if v.Origin == OriginFork && (v.Fork == nil || v.Fork.RequestID == "") { + if isForked(v.Origin) && (v.Fork == nil || v.Fork.RequestID == "") { return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: a fork without its fork record", p) } v.State = string(e.Extended[extVolState]) @@ -527,8 +530,10 @@ func (c *Catalog) EnsureVolume(ctx context.Context, vol string, g Geometry) (Vol return VolumeInfo{}, err } } - if v.Origin == OriginFork { + if isForked(v.Origin) { // One read of HEAD decides both: absent and aborted never attach. + // A restore reads only its own HEAD here, never its source: a source + // deleted meanwhile is a normal state, not a mismatch. h, has, err := c.ReadHead(ctx, vol) switch { case err != nil: @@ -1169,6 +1174,24 @@ func (c *Catalog) ListVolumes(ctx context.Context) ([]string, error) { // unsettled keeps its own intent (that create may still land); no attempt // or replay deletes another attempt's intent. func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) { + return c.fork(ctx, req, OriginFork) +} + +// Restore starts an independent restore of req.Source's snapshot into +// req.Target: the same steps as Fork (claim, qualified refs, HEAD), recorded +// with Origin restore. The target serves at once (lazy fill); the restore +// driver then hydrates every chunk, re-uploads the qualified ones under the +// target's own keys in bounded batch cuts, and MarkIndependent records the +// end of the lineage once HEAD holds no qualified ref (DESIGN-r2, O-REC-2). +func (c *Catalog) Restore(ctx context.Context, req ForkRequest) (ForkResult, error) { + return c.fork(ctx, req, OriginRestore) +} + +// isForked reports whether origin made the volume from another volume's +// snapshot (a fork record exists and HEAD may hold qualified refs). +func isForked(origin string) bool { return origin == OriginFork || origin == OriginRestore } + +func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (ForkResult, error) { if _, err := c.volRoot(req.Source); err != nil { return ForkResult{}, err } @@ -1199,7 +1222,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, refuseDeleted(req.Target, "fork to a new volume id") } if ok { - if err := c.checkForkRecord(existing, req); err != nil { + if err := c.checkForkRecord(existing, req, origin); err != nil { return ForkResult{}, err } h, has, err := c.ReadHead(ctx, req.Target) @@ -1271,7 +1294,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) req.Target, req.Source, req.Snapshot, existing.Fork.SourceGen, snap.HeadGen) } } else { - vol := VolumeInfo{Format: volumeFormat, VolumeID: req.Target, Geometry: snap.geo, Origin: OriginFork, CreatedNs: c.now().UnixNano(), + vol := VolumeInfo{Format: volumeFormat, VolumeID: req.Target, Geometry: snap.geo, Origin: origin, CreatedNs: c.now().UnixNano(), Parent: &Parent{VolumeID: req.Source, Snapshot: req.Snapshot, Gen: snap.HeadGen}, Fork: record} ve, err := volumeEntry(vol, req.RequestID) if err != nil { @@ -1285,7 +1308,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: VOLUME create outcome unknown; retry with the same request id", req.Target) } v, err := decodeVolume(path.Join(dstRoot, volumeName), got) - if err != nil || c.checkForkRecord(v, req) != nil || v.Fork.HeadSHA256 != digest { + if err != nil || c.checkForkRecord(v, req, origin) != nil || v.Fork.HeadSHA256 != digest { return ForkResult{}, catErr(CodeTargetExists, false, nil, "volume %s exists (another request, or another image)", req.Target) } } @@ -1477,7 +1500,10 @@ func (c *Catalog) AbortFork(ctx context.Context, target string) (claimed bool, e } // checkForkRecord refuses a target VOLUME that is not this fork request's. -func (c *Catalog) checkForkRecord(v VolumeInfo, req ForkRequest) error { +func (c *Catalog) checkForkRecord(v VolumeInfo, req ForkRequest, origin string) error { + if v.Origin != origin { + return catErr(CodeTargetExists, false, nil, "volume %s exists (origin %s, not %s)", req.Target, v.Origin, origin) + } if v.Fork == nil || v.Fork.RequestID != req.RequestID { return catErr(CodeTargetExists, false, nil, "volume %s exists (another request)", req.Target) } diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy.go b/seaweed-block/core/frontend/chunkstore/gc_copy.go index 2da07b132e..78453dd337 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy.go @@ -86,7 +86,7 @@ func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) { if readErr != nil { return settled, readErr } - if !ok || v.Origin != OriginFork || v.Fork == nil || v.Fork.RequestID != parts[1] { + if !ok || !isForked(v.Origin) || v.Fork == nil || v.Fork.RequestID != parts[1] { return settled, errors.New("chunkstore: fork intent has no matching target VOLUME") } if _, err = g.cat.AbortFork(ctx, a.vol); err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/restore.go b/seaweed-block/core/frontend/chunkstore/restore.go new file mode 100644 index 0000000000..4ba43e7b6a --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/restore.go @@ -0,0 +1,154 @@ +package chunkstore + +import ( + "context" + "encoding/json" + "errors" + "path" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// restoreIndependentName is the write-once entry that ends a restore's +// lineage: written only when the restored volume's HEAD holds no qualified +// ref, so from then on nothing of the volume reaches its source's chunks. +const ( + restoreIndependentName = "RESTORE-INDEPENDENT" + kindRestoreIndependent = "chunkrestoreindependent" +) + +// Restore error codes. +const ( + // CodeNotRestore: the volume was not made by Restore. + CodeNotRestore = "not_restore" + // CodeRestoreIncomplete: HEAD still holds qualified refs (or no HEAD). + CodeRestoreIncomplete = "restore_incomplete" +) + +// RestoreIndependence is the content of restoreIndependentName. +type RestoreIndependence struct { + Format int `json:"format"` + VolumeID string `json:"volume_id"` + HeadGen uint64 `json:"head_gen"` + MarkedNs int64 `json:"marked_ns"` +} + +// ForeignRefs counts the refs of vol's HEAD h that name ANOTHER volume's +// chunks or segments: a "@/" key whose owner is not vol. A resolved +// HEAD writes every chunk key in owner-qualified form, vol's own included, +// so a bare "@" prefix does not make a ref foreign; an unqualified key is +// always vol's own. +func ForeignRefs(h storage.ChunkHead, vol string) int { + foreign := func(key string) bool { + if !strings.HasPrefix(key, "@") { + return false + } + owner, _, ok := strings.Cut(key[1:], "/") + return !ok || owner != vol + } + n := 0 + for _, ref := range h.Chunks { + if foreign(ref.Key) { + n++ + } + } + for _, seg := range h.Segments { + if foreign(seg.Key) { + n++ + } + } + return n +} + +// MarkIndependent records that restored volume vol no longer depends on its +// source: refused unless vol was made by Restore and its current HEAD holds +// no qualified ref. Write-once: an existing marker is a replay (ok). +func (c *Catalog) MarkIndependent(ctx context.Context, vol string) (RestoreIndependence, error) { + root, err := c.volRoot(vol) + if err != nil { + return RestoreIndependence{}, err + } + if m, ok, err := c.ReadIndependence(ctx, vol); err != nil || ok { + return m, err + } + v, ok, err := c.ReadVolume(ctx, vol) + if err != nil { + return RestoreIndependence{}, err + } + if !ok || v.Origin != OriginRestore { + return RestoreIndependence{}, catErr(CodeNotRestore, false, nil, "volume %s was not made by restore", vol) + } + h, has, err := c.ReadHead(ctx, vol) + if err != nil { + return RestoreIndependence{}, err + } + if !has || h.State == storage.ChunkHeadAborted || headDeletingOrDeleted(h) { + return RestoreIndependence{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s has no live HEAD", vol) + } + // The manifest segments name chunk refs too: check the resolved HEAD (every + // segment key and every chunk ref inside), as GC and usage resolve it. + if c.blobs == nil { + return RestoreIndependence{}, errors.New("chunkstore: restore marker needs the segment reader") + } + r, err := NewChunkRemote(c.f, c.blobs, path.Join(c.base, vol)) + if err != nil { + return RestoreIndependence{}, err + } + resolved, err := r.resolveManifest(ctx, h) + if err != nil { + return RestoreIndependence{}, remoteErr(err, "resolve HEAD of %s", vol) + } + if q := ForeignRefs(resolved, vol); q > 0 { + return RestoreIndependence{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s: HEAD gen %d still holds %d refs to another volume", vol, h.Gen, q) + } + m := RestoreIndependence{Format: volumeFormat, VolumeID: vol, HeadGen: h.Gen, MarkedNs: c.now().UnixNano()} + body, err := json.Marshal(m) + if err != nil { + return RestoreIndependence{}, err + } + now := time.Now().Unix() + e := &filerpb.Entry{ + Name: restoreIndependentName, + Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now, Crtime: now, FileMode: 0o644, Mime: "application/json"}, + Extended: map[string][]byte{extKind: []byte(kindRestoreIndependent)}, + Content: body, + } + if err := c.f.CreateEntry(ctx, root, e, true); err != nil { + if !errors.Is(err, ErrExists) { + return RestoreIndependence{}, remoteErr(err, "create %s of %s", restoreIndependentName, vol) + } + m, ok, err := c.ReadIndependence(ctx, vol) + if err == nil && !ok { + err = remoteErr(nil, "re-read %s of %s", restoreIndependentName, vol) + } + return m, err + } + return m, nil +} + +// ReadIndependence returns vol's independence marker; ok is false when the +// restore has not ended (or vol is not a restore). +func (c *Catalog) ReadIndependence(ctx context.Context, vol string) (RestoreIndependence, bool, error) { + root, err := c.volRoot(vol) + if err != nil { + return RestoreIndependence{}, false, err + } + e, err := c.f.LookupEntry(ctx, root, restoreIndependentName) + if errors.Is(err, ErrNotFound) { + return RestoreIndependence{}, false, nil + } + if err != nil { + return RestoreIndependence{}, false, remoteErr(err, "read %s of %s", restoreIndependentName, vol) + } + if k := string(e.Extended[extKind]); k != kindRestoreIndependent { + return RestoreIndependence{}, false, remoteErr(nil, "%s of %s: kind %q", restoreIndependentName, vol, k) + } + var m RestoreIndependence + if err := json.Unmarshal(e.GetContent(), &m); err != nil || m.VolumeID != vol { + return RestoreIndependence{}, false, remoteErr(err, "decode %s of %s", restoreIndependentName, vol) + } + return m, true, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/restore_test.go b/seaweed-block/core/frontend/chunkstore/restore_test.go new file mode 100644 index 0000000000..f844827032 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/restore_test.go @@ -0,0 +1,265 @@ +package chunkstore + +import ( + "bytes" + "context" + "crypto/sha256" + "fmt" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// restoreFixture: v1 with snapshot s1, restored into v2. +func restoreFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) { + t.Helper() + f, b, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); err != nil { + t.Fatal(err) + } + return f, b, c, h +} + +// ownAll re-uploads every qualified chunk of vol under vol's own keys and +// publishes a HEAD with no qualified ref (what the restore's batch cuts do). +func ownAll(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string) storage.ChunkHead { + t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(f, b, catBase+"/"+vol) + if err != nil { + t.Fatal(err) + } + h, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + // The batch cut's result in one step: every chunk under a fresh own key + // (chunks/e2/...), a new manifest, one HEAD CAS, intents dropped. + next := storage.ChunkHead{Epoch: 1, Holder: "h2", RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}} + for idx, ref := range h.Chunks { + data, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + key := fmt.Sprintf("chunks/e2/c%d/k", idx) + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + next, intents, err := r.PrepareManifest(ctx, h, next, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next); err != nil { + t.Fatal(err) + } + for _, id := range intents { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + got, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + return got +} + +// allQualified reports whether every chunk ref and segment key of h names another volume. +func allQualified(h storage.ChunkHead) bool { + for _, ref := range h.Chunks { + if !strings.HasPrefix(ref.Key, "@") { + return false + } + } + for _, seg := range h.Segments { + if !strings.HasPrefix(seg.Key, "@") { + return false + } + } + return len(h.Chunks) > 0 +} + +func TestRestore_RecordsOriginForkRecordAndQualifiedHead(t *testing.T) { + f, b, c, h := restoreFixture(t) + ctx := context.Background() + v, ok, err := c.ReadVolume(ctx, "v2") + if err != nil || !ok || v.Origin != OriginRestore || v.Fork == nil || v.Fork.Source != "v1" || v.Parent == nil { + t.Fatalf("restored VOLUME %+v ok=%v err=%v: want Origin restore with a fork record and Parent", v, ok, err) + } + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + h2, _ := r2.GetHead(ctx) + if !allQualified(h2) || len(h2.Chunks) != len(h.Chunks) { + t.Fatalf("restored HEAD %v: want all %d chunk refs (and segments) qualified", h2.Chunks, len(h.Chunks)) + } + if _, err := c.EnsureVolume(ctx, "v2", v.Geometry); err != nil { + t.Fatalf("a restored volume attaches like a fork: %v", err) + } +} + +func TestRestore_ReplayAndOriginMismatchRefused(t *testing.T) { + _, _, c, _ := restoreFixture(t) + ctx := context.Background() + if r, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); err != nil || !r.Replayed { + t.Fatalf("restore replay: %+v %v", r, err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("a fork onto a restored volume with the same request id must be refused: %v", err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "f1"}); err != nil { + t.Fatal(err) + } + if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "f1"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("a restore onto a fork volume with the same request id must be refused: %v", err) + } +} + +func TestRestore_MarkIndependentOnlyWithoutQualifiedRefs(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + if _, err := c.MarkIndependent(ctx, "v2"); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("marker while HEAD holds qualified refs: %v, want %s", err, CodeRestoreIncomplete) + } + if _, ok, err := c.ReadIndependence(ctx, "v2"); err != nil || ok { + t.Fatalf("no marker may exist after a refused mark: ok=%v err=%v", ok, err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "f1"}); err != nil { + t.Fatal(err) + } + if _, err := c.MarkIndependent(ctx, "v3"); CodeOf(err) != CodeNotRestore { + t.Fatalf("marker on a fork: %v, want %s", err, CodeNotRestore) + } + h := ownAll(t, f, b, "v2") + if ForeignRefs(h, "v2") != 0 { + t.Fatalf("fixture: %d foreign refs left", ForeignRefs(h, "v2")) + } + m, err := c.MarkIndependent(ctx, "v2") + if err != nil || m.HeadGen != h.Gen || m.VolumeID != "v2" { + t.Fatalf("marker: %+v %v (HEAD gen %d)", m, err, h.Gen) + } + if again, err := c.MarkIndependent(ctx, "v2"); err != nil || again != m { + t.Fatalf("marker is write-once (a replay returns it): %+v %v", again, err) + } + if got, ok, err := c.ReadIndependence(ctx, "v2"); err != nil || !ok || got != m { + t.Fatalf("read marker: %+v %v %v", got, ok, err) + } +} + +// claude06 (verify side): deleting the source mid-restore is a normal state for every reader of T's fork record. +func TestRestore_SourceGoneIsNormal(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + h2, _ := r2.GetHead(ctx) + before := map[uint64][]byte{} + for idx, ref := range h2.Chunks { + data, err := r2.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + before[idx] = data + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatalf("after T has its HEAD the source snapshot may go: %v", err) + } + detachHead(t, f, b, "v1") + if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { + t.Fatalf("delete the source volume: %v", err) + } + v, _, _ := c.ReadVolume(ctx, "v2") + if _, err := c.EnsureVolume(ctx, "v2", v.Geometry); err != nil { + t.Fatalf("attach of a restore whose source is gone must be normal: %v", err) + } + if r, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); err != nil || !r.Replayed { + t.Fatalf("replay of a restore whose source is gone: %+v %v", r, err) + } + for idx, ref := range h2.Chunks { + data, err := r2.Get(ctx, ref.Key) + if err != nil || sha256.Sum256(data) != sha256.Sum256(before[idx]) || sha256.Sum256(data) != ref.SHA256 { + t.Fatalf("chunk %d unreadable or changed after the source was deleted: %v", idx, err) + } + } + h := ownAll(t, f, b, "v2") + if _, err := c.MarkIndependent(ctx, "v2"); err != nil { + t.Fatalf("the restore finishes with its source gone: %v (HEAD gen %d)", err, h.Gen) + } +} + +// claude05/claude06 load-bearing invariant for O-REC-2 option 1: after the restore's HEAD exists, the +// source snapshot and the source volume may both go; GC must keep every chunk T's HEAD names (qualified +// refs resolve to the owner's bindings) until T's own batch cuts replace them. +func TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x31), 3: chunkBytes(0x33)}) + if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); e != nil { + t.Fatal(e) + } + if e := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); e != nil { + t.Fatal(e) + } + if _, e := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs"}); e != nil { + t.Fatal(e) + } + if _, e := c.DeleteSnapshot(ctx, "v1", "s1"); e != nil { + t.Fatalf("retention/delete may retire S once T has a HEAD: %v", e) + } + detachHead(t, f, b.fakeBlobs, "v1") + if _, e := c.DeleteVolume(ctx, "v1", nil); e != nil { + t.Fatalf("delete the source volume: %v", e) + } + r2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) + h2, e := r2.GetHead(ctx) + if e != nil { + t.Fatal(e) + } + for i := 0; i < 3; i++ { + if _, e := g.Run(ctx); e != nil { + t.Fatalf("gc: %v", e) + } + *now = now.Add(2 * time.Hour) + } + want := map[uint64][]byte{0: chunkBytes(0x31), 3: chunkBytes(0x33)} + for idx, ref := range h2.Chunks { + got, e := r2.Get(ctx, ref.Key) + if e != nil || !bytes.Equal(got, want[idx]) { + t.Fatalf("restored chunk %d lost after S and V were deleted and GC ran: %v", idx, e) + } + } +} + +// claude06 condition (3): a restore whose HEAD is absent or an aborted tombstone never attaches, like a fork. +func TestRestore_WithoutLiveHeadNeverAttaches(t *testing.T) { + f, _, c, _ := catalogFixture(t) + ctx := context.Background() + v := VolumeInfo{Format: volumeFormat, VolumeID: "v9", Geometry: catGeo, Origin: OriginRestore, CreatedNs: 1, + Parent: &Parent{VolumeID: "v1", Snapshot: "s1", Gen: 1}, Fork: &ForkRecord{RequestID: "rq", Source: "v1", Snapshot: "s1"}} + e, err := volumeEntry(v, "rq") + if err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase+"/v9", e, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(ctx, "v9", catGeo); CodeOf(err) != CodeForkIncomplete { + t.Fatalf("restore without a HEAD attached: %v, want %s", err, CodeForkIncomplete) + } + if _, err := c.AbortFork(ctx, "v9"); err != nil { + t.Fatalf("abort the unpublished restore (sweep): %v", err) + } + if _, err := c.EnsureVolume(ctx, "v9", catGeo); CodeOf(err) != CodeForkIncomplete { + t.Fatalf("restore with an aborted HEAD attached: %v, want %s", err, CodeForkIncomplete) + } + if _, err := c.MarkIndependent(ctx, "v9"); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("marker on an aborted restore: %v, want %s", err, CodeRestoreIncomplete) + } +} From 566471971ad12f23b1170eebf34406dfb7c6db41 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 19:52:47 -0800 Subject: [PATCH 2/8] storage: background hydrate walker (HydrateAll) for independent restore HydrateAll makes every HEAD-named chunk local, lowest index first, through the same shared fill flights as guest read misses (one fetch per chunk; queue bound and read-miss timeout apply). It yields while any flight has guest waiters and admits each fill through the host limiter (cfg.Budget) with the caller's ctx, so the restore driver sets hostlimit.BackgroundFill on it. A refused admission or a pending fill backs off and retries; ctx cancel returns the remaining count. ChunkLayerStats.AbsentChunks reports what is still to fetch (0 = fully local). Tests: every chunk fetched exactly once and the HEAD image reads back, a second walk does nothing; local writes (full and partial chunk) are never overwritten; the walker issues no fetch while a guest waits and never fetches twice; each fill is admitted once and released, refusals are deferred, the caller's class reaches Admit; cancel reports the remaining count; AbsentChunks before/after. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_hydrate_all.go | 172 ++++++++++++++ .../core/storage/chunk_hydrate_all_test.go | 215 ++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 1 + seaweed-block/core/storage/chunk_seam.go | 3 + 4 files changed, 391 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_hydrate_all.go create mode 100644 seaweed-block/core/storage/chunk_hydrate_all_test.go diff --git a/seaweed-block/core/storage/chunk_hydrate_all.go b/seaweed-block/core/storage/chunk_hydrate_all.go new file mode 100644 index 0000000000..094ec50b24 --- /dev/null +++ b/seaweed-block/core/storage/chunk_hydrate_all.go @@ -0,0 +1,172 @@ +package storage + +import ( + "context" + "errors" + "time" +) + +// HydrateProgress reports one HydrateAll call. +// - Filled: chunks this call made local. +// - Remaining: chunks still absent (HEAD-named, with a block not written +// locally) when the call returned; 0 means the volume is fully local. +// - Paused: times the walker yielded to guest read misses. +// - Deferred: times the host limiter refused a fill (retried later). +type HydrateProgress struct { + Filled int + Remaining int + Paused uint64 + Deferred uint64 +} + +// Walker pacing: a guest wait or a refused fill is retried after a short +// backoff that doubles up to the cap. +var ( + hydrateAllMinBackoff = 20 * time.Millisecond + hydrateAllMaxBackoff = 2 * time.Second +) + +// HydrateAll makes every chunk local that HEAD names and the volume does not +// hold yet (an independent restore's background hydrate, O-REC-2). It walks +// the absent chunks lowest index first through the same shared fill flights +// as guest read misses (one fetch per chunk, the hydration queue bound and +// the read-miss timeout apply), so it never fetches a chunk twice or races a +// guest fill. It yields while any flight has guest waiters, and admits each +// fill through the host limiter (cfg.Budget) with ctx: the caller sets the +// limiter class on ctx (hostlimit.WithClass(ctx, hostlimit.BackgroundFill)). +// It returns when nothing is absent, when ctx ends, or on a fill error that +// is not a retryable pending state; the caller may call it again. +func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error) { + var p HydrateProgress + backoff := hydrateAllMinBackoff + wait := func() error { + t := time.NewTimer(backoff) + defer t.Stop() + if backoff *= 2; backoff > hydrateAllMaxBackoff { + backoff = hydrateAllMaxBackoff + } + select { + case <-t.C: + return nil + case <-ctx.Done(): + return ctx.Err() + case <-l.ctx.Done(): + return errChunkLayerClosed + } + } + for { + if err := ctx.Err(); err != nil { + p.Remaining = l.absentHydratable() + return p, err + } + lba, ok, guests := l.nextHydrateTarget() + if !ok { + p.Remaining = 0 + return p, nil + } + if guests > 0 { + p.Paused++ + if err := wait(); err != nil { + p.Remaining = l.absentHydratable() + return p, err + } + continue + } + release, err := l.admitFill(ctx) + if err != nil { + p.Deferred++ + if err := wait(); err != nil { + p.Remaining = l.absentHydratable() + return p, err + } + continue + } + _, err = l.OnReadMissContext(ctx, lba) + release() + switch { + case err == nil: + p.Filled++ + backoff = hydrateAllMinBackoff + case errors.Is(err, ErrChunkHydrationPending): + // queue full or the read-miss timeout: retry the same chunk later + if err := wait(); err != nil { + p.Remaining = l.absentHydratable() + return p, err + } + default: + p.Remaining = l.absentHydratable() + return p, err + } + } +} + +// nextHydrateTarget returns a block of the lowest-index chunk that HEAD names, +// is absent and has a block without a local extent version (localBlocks: a +// chunk whose every block reached the extent needs no fetch; a write still only +// in the WAL does not count, and the fill never overwrites it), and the number +// of flights that have guest waiters. +func (l *chunkLayerImpl) nextHydrateTarget() (lba uint64, ok bool, guests int) { + l.stMu.Lock() + defer l.stMu.Unlock() + for _, f := range l.hydration { + if f.waiters > 0 { + guests++ + } + } + best := uint64(0) + for idx := range l.absent { + if !l.absent[idx] || (ok && idx >= best) { + continue + } + if b, has := l.hydratableBlockLocked(idx); has { + best, lba, ok = idx, b, true + } + } + return lba, ok, guests +} + +// absentHydratable counts the chunks nextHydrateTarget would still visit. +func (l *chunkLayerImpl) absentHydratable() int { + l.stMu.Lock() + defer l.stMu.Unlock() + n := 0 + for idx, absent := range l.absent { + if _, has := l.hydratableBlockLocked(idx); absent && has { + n++ + } + } + return n +} + +// hydratableBlockLocked returns a block of chunk idx that is not written +// locally, if HEAD names the chunk. Caller holds stMu. +func (l *chunkLayerImpl) hydratableBlockLocked(idx uint64) (uint64, bool) { + if _, named := l.head.Chunks[idx]; !named { + return 0, false + } + first := idx * l.chunkBlocks + for i := uint64(0); i < l.chunkBlocks; i++ { + b := first + i + if b >= uint64(l.s.NumBlocks()) { + break + } + if !l.localBlocks[b] { + return b, true + } + } + return 0, false +} + +// admitFill reserves one chunk of fill payload from the host limiter, if +// there is one; the returned release gives it back. +func (l *chunkLayerImpl) admitFill(ctx context.Context) (func(), error) { + host := l.cfg.Budget + if host == nil { + return func() {}, nil + } + ticket, err := host.Admit(ctx, int64(l.chunkBlocks)*int64(l.blockSize), func(error) {}) + if err != nil { + return nil, err + } + return func() { host.Release(ticket) }, nil +} diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go new file mode 100644 index 0000000000..9ff3d672e6 --- /dev/null +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -0,0 +1,215 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "strings" + "sync" + "testing" + "time" +) + +func countGets(r *fakeChunkRemote) map[string]int { + r.mu.Lock() + defer r.mu.Unlock() + out := map[string]int{} + for _, op := range r.ops { + if key, ok := strings.CutPrefix(op, "get:"); ok { + out[key]++ + } + } + return out +} + +func fastWalker(t *testing.T) { + t.Helper() + minB, maxB := hydrateAllMinBackoff, hydrateAllMaxBackoff + hydrateAllMinBackoff, hydrateAllMaxBackoff = time.Millisecond, 5*time.Millisecond + t.Cleanup(func() { hydrateAllMinBackoff, hydrateAllMaxBackoff = minB, maxB }) +} + +func TestHydrateAll_FillsEveryChunkOnceAndReadsTheHeadImage(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + ctx := context.Background() + p, err := layer.HydrateAll(ctx) + if err != nil || p.Remaining != 0 || p.Filled != ctNumBlocks/ctChunkBlocks { + t.Fatalf("hydrate all: %+v %v, want %d filled, 0 remaining", p, err, ctNumBlocks/ctChunkBlocks) + } + for key, n := range countGets(remote) { + if n != 1 { + t.Fatalf("chunk %s fetched %d times, want exactly once", key, n) + } + } + for b := uint32(0); b < ctNumBlocks; b++ { + got, err := s.Read(b) + if err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, byte(0x40+b))) { + t.Fatalf("block %d after hydrate: %v", b, err) + } + } + before := len(countGets(remote)) + if p, err := layer.HydrateAll(ctx); err != nil || p.Filled != 0 || p.Remaining != 0 || len(countGets(remote)) != before { + t.Fatalf("a second walk of a full volume must do nothing: %+v %v", p, err) + } +} + +// A guest write that is still only in the WAL is not visible to the walker as +// local (localBlocks is set when the extent gets a local version), so the chunk +// may be fetched; the fill must never overwrite the local write (reads resolve +// the WAL first and the fill installs only blocks without a newer local version). +func TestHydrateAll_NeverOverwritesALocalWrite(t *testing.T) { + fastWalker(t) + s, layer, _, _ := hydrationFixture(t, 2, 64) + for i := uint32(0); i < ctChunkBlocks; i++ { // chunk 0 fully overwritten + if _, err := s.Write(i, makeBlock(ctBlockSize, 0xEE)); err != nil { + t.Fatal(err) + } + } + if _, err := s.Write(ctChunkBlocks+1, makeBlock(ctBlockSize, 0xEF)); err != nil { // one block of chunk 1 + t.Fatal(err) + } + p, err := layer.HydrateAll(context.Background()) + if err != nil || p.Remaining != 0 { + t.Fatalf("hydrate all: %+v %v", p, err) + } + for i := uint32(0); i < ctChunkBlocks; i++ { + if got, _ := s.Read(i); !bytes.Equal(got, makeBlock(ctBlockSize, 0xEE)) { + t.Fatalf("block %d: the local write was overwritten by the walker", i) + } + } + if got, _ := s.Read(ctChunkBlocks + 1); !bytes.Equal(got, makeBlock(ctBlockSize, 0xEF)) { + t.Fatal("partial local write in chunk 1 overwritten") + } + if got, _ := s.Read(ctChunkBlocks); !bytes.Equal(got, makeBlock(ctBlockSize, byte(0x40+ctChunkBlocks))) { + t.Fatal("the unwritten blocks of chunk 1 must read HEAD's bytes after the walk") + } +} + +func TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice(t *testing.T) { + fastWalker(t) + s, layer, remote, registered := hydrationFixture(t, 2, 64) + entered, release := holdNextGet(t, remote) + guest := startHydrationRead(t, s, context.Background(), 5*ctChunkBlocks) + waitHydrationRegistration(t, registered, 1) + <-entered // the guest's fetch of chunk 5 is held + type res struct { + p HydrateProgress + err error + } + walked := make(chan res, 1) + go func() { + p, err := layer.HydrateAll(context.Background()) + walked <- res{p, err} + }() + time.Sleep(30 * time.Millisecond) + if n := len(countGets(remote)); n != 1 { + t.Fatalf("the walker fetched while a guest was waiting: %d distinct gets", n) + } + release() + if r := hydrationOutcome(t, guest); r.err != nil { + t.Fatalf("guest read: %v", r.err) + } + var r res + select { + case r = <-walked: + case <-time.After(ctLocalBound): + t.Fatal("walker did not finish") + } + if r.err != nil || r.p.Remaining != 0 || r.p.Paused == 0 || r.p.Filled != ctNumBlocks/ctChunkBlocks-1 { + t.Fatalf("walker: %+v %v, want paused for the guest and the 7 other chunks filled", r.p, r.err) + } + for key, n := range countGets(remote) { + if n != 1 { + t.Fatalf("chunk %s fetched %d times", key, n) + } + } +} + +type walkerClassKey struct{} + +type walkerBudget struct { + mu sync.Mutex + refuse int + admitted int + released int + classes []any +} + +func (b *walkerBudget) Admit(ctx context.Context, _ int64, _ func(error)) (uint64, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.classes = append(b.classes, ctx.Value(walkerClassKey{})) + if b.refuse > 0 { + b.refuse-- + return 0, errors.New("fill class over budget") + } + b.admitted++ + return uint64(b.admitted), nil +} +func (b *walkerBudget) ReserveCOW(uint64, int64) error { return nil } +func (b *walkerBudget) Release(uint64) { + b.mu.Lock() + b.released++ + b.mu.Unlock() +} + +func TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass(t *testing.T) { + fastWalker(t) + _, layer, _, _ := hydrationFixture(t, 2, 64) + budget := &walkerBudget{refuse: 2} + layer.cfg.Budget = budget + ctx := context.WithValue(context.Background(), walkerClassKey{}, "fill") + p, err := layer.HydrateAll(ctx) + if err != nil || p.Remaining != 0 || p.Deferred != 2 { + t.Fatalf("hydrate all: %+v %v, want 2 deferred then everything filled", p, err) + } + budget.mu.Lock() + defer budget.mu.Unlock() + if budget.admitted != p.Filled || budget.released != budget.admitted { + t.Fatalf("budget admitted %d released %d, filled %d: every fill admitted once and released", budget.admitted, budget.released, p.Filled) + } + for _, c := range budget.classes { + if c != "fill" { + t.Fatalf("the caller's limiter class did not reach Admit: %v", c) + } + } +} + +func TestHydrateAll_CancelReturnsTheRemainingCount(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + entered, release := holdNextGet(t, remote) + defer release() + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan HydrateProgress, 1) + go func() { + p, _ := layer.HydrateAll(ctx) + done <- p + }() + <-entered + cancel() + release() + select { + case p := <-done: + if p.Remaining == 0 { + t.Fatalf("cancelled walk reports nothing remaining: %+v", p) + } + case <-time.After(ctLocalBound): + t.Fatal("cancelled walker did not return") + } +} + +func TestHydrateAll_StatsReportAbsentChunks(t *testing.T) { + fastWalker(t) + _, layer, _, _ := hydrationFixture(t, 2, 64) + if n := layer.Stats().AbsentChunks; n != ctNumBlocks/ctChunkBlocks { + t.Fatalf("absent before the walk: %d, want %d", n, ctNumBlocks/ctChunkBlocks) + } + if _, err := layer.HydrateAll(context.Background()); err != nil { + t.Fatal(err) + } + if n := layer.Stats().AbsentChunks; n != 0 { + t.Fatalf("absent after the walk: %d, want 0", n) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 5c32d22aeb..29579b0f97 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1430,6 +1430,7 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats { l.stMu.Unlock() out.DirtyChunks = len(l.captureCandidates()) + out.AbsentChunks = l.absentHydratable() return out } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 2fda490f07..7e2c7c3c95 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -476,6 +476,9 @@ type chunkLayerStats struct { // BarrierOverBound counts cuts whose barrier copied more than the // bound after the staging rounds. BarrierOverBound uint64 + // AbsentChunks is the number of HEAD-named chunks still absent with a + // block not local (what HydrateAll would still fetch); 0 = fully local. + AbsentChunks int } // chunkCutResult is the outcome of one successful cut. From 796ef439e74dcc383da808a42a7f8ca449eadea6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 19:58:03 -0800 Subject: [PATCH 3/8] chunkstore: refuse snapshots of a restore until it is independent A snapshot taken while a restore still names its source's chunks would keep that lineage for its whole retention. CreateSnapshot on an Origin restore volume is refused (restore_incomplete) until RESTORE-INDEPENDENT exists; a refused request leaves no name or attempt. Test covers before, after own chunks without the marker, and after the marker (the snapshot then names no foreign ref). Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 10 +++++++ .../core/frontend/chunkstore/restore_test.go | 28 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index a3b93e5e09..c4ca9e9b8b 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -864,6 +864,16 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe if !ok { return SnapshotInfo{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol) } + if v.Origin == OriginRestore { + // A restore is independent only once its marker exists: a snapshot + // taken before would keep naming the source's chunks for its whole + // retention, so it is refused until then (DESIGN-r2 open question a). + if _, independent, err := c.ReadIndependence(ctx, vol); err != nil { + return SnapshotInfo{}, err + } else if !independent { + return SnapshotInfo{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s is still being restored: snapshots are refused until it is independent", vol) + } + } // Take the name: this request's record, or an earlier attempt's of it. attempt, err := c.claimName(ctx, vol, root, req, head.Gen) diff --git a/seaweed-block/core/frontend/chunkstore/restore_test.go b/seaweed-block/core/frontend/chunkstore/restore_test.go index f844827032..b30af27438 100644 --- a/seaweed-block/core/frontend/chunkstore/restore_test.go +++ b/seaweed-block/core/frontend/chunkstore/restore_test.go @@ -263,3 +263,31 @@ func TestRestore_WithoutLiveHeadNeverAttaches(t *testing.T) { t.Fatalf("marker on an aborted restore: %v, want %s", err, CodeRestoreIncomplete) } } + +// DESIGN-r2 open question (a), ruled: snapshots of a restore are refused until it is independent. +func TestRestore_SnapshotsRefusedUntilIndependent(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + h2, _ := r2.GetHead(ctx) + if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "early", RequestID: "e"}, h2); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("snapshot of a restore in progress: %v, want %s", err, CodeRestoreIncomplete) + } + if _, ok, err := c.SnapshotReplay(ctx, "v2", SnapshotRequest{Name: "early", RequestID: "e"}); err != nil || ok { + t.Fatalf("a refused snapshot must leave nothing: ok=%v err=%v", ok, err) + } + h := ownAll(t, f, b, "v2") + if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "late", RequestID: "l"}, h); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("own chunks but no marker yet: %v, want %s", err, CodeRestoreIncomplete) + } + if _, err := c.MarkIndependent(ctx, "v2"); err != nil { + t.Fatal(err) + } + s, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "late", RequestID: "l"}, h) + if err != nil { + t.Fatalf("snapshot after the marker: %v", err) + } + if ForeignRefs(s.Head(), "v2") != 0 { + t.Fatalf("a snapshot of an independent restore names %d foreign refs", ForeignRefs(s.Head(), "v2")) + } +} From 3b58335be59f044883520a1c53d6b1d686319a2e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:11:14 -0800 Subject: [PATCH 4/8] spec: RestoreIndependence model for independent restore (O-REC-2) TLA+ model of the restore: claim, two-step fork, hydrate, bounded batch cuts (upload own fids under an intent, one HEAD CAS per batch), marker after the last foreign ref, claim drop; GC, source delete, snapshot retention and crashes with a resume from remote facts at any point. Invariants NoGap, Independent, NoForeignList, ClaimUntilHead_Inv (option 1: today's fork claim semantics), LifecycleFree, StateRemote. cfgs: option-1 safe at three sizes, the stricter claim-until-independent variant, two witnesses, and one red cfg per mutant (each red at its expected invariant in simulation). Simulation only so far: no violation in about 0.81M states per safe cfg (3 seeds x 60000 traces, depth 40); not exhausted. Co-Authored-By: Claude Opus 5.5 --- .../docs/spec/RestoreIndependence.tla | 173 ++++++++++++++++++ ...toreIndependence_red_cas_before_upload.cfg | 24 +++ ...oreIndependence_red_drop_claim_at_fork.cfg | 24 +++ .../RestoreIndependence_red_list_foreign.cfg | 24 +++ ...toreIndependence_red_marker_before_cas.cfg | 24 +++ .../RestoreIndependence_red_marker_early.cfg | 24 +++ .../cfg/RestoreIndependence_red_no_intent.cfg | 24 +++ .../RestoreIndependence_red_resume_local.cfg | 24 +++ ...ependence_red_retention_ignores_marker.cfg | 24 +++ ...reIndependence_red_snap_during_restore.cfg | 24 +++ .../spec/cfg/RestoreIndependence_safe.cfg | 24 +++ .../spec/cfg/RestoreIndependence_safe_b2.cfg | 24 +++ .../spec/cfg/RestoreIndependence_safe_n4.cfg | 24 +++ ...endence_strict_claim_until_independent.cfg | 24 +++ .../RestoreIndependence_wit_crash_resume.cfg | 25 +++ .../spec/cfg/RestoreIndependence_wit_done.cfg | 25 +++ 16 files changed, 535 insertions(+) create mode 100644 seaweed-block/docs/spec/RestoreIndependence.tla create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg diff --git a/seaweed-block/docs/spec/RestoreIndependence.tla b/seaweed-block/docs/spec/RestoreIndependence.tla new file mode 100644 index 0000000000..0997891784 --- /dev/null +++ b/seaweed-block/docs/spec/RestoreIndependence.tla @@ -0,0 +1,173 @@ +------------------------------ MODULE RestoreIndependence ------------------------------ +(***************************************************************************) +(* Independent restore (O-REC-2): restore a snapshot into a volume that *) +(* ends up owning all its chunks, with no lineage to the source. *) +(* Source volume V with HEAD and one sealed snapshot S; target T restored *) +(* from S. T's HEAD maps indexes to fids; a fid is owned by V (a "@V/" *) +(* ref) or by T. Steps: 0 claim S; 1 fork (T HEAD = S's fids, all V-owned) *) +(* ; 2 hydrate (local, not modelled beyond "local" flags); 3 OWNING = *) +(* batch cuts, each re-uploads up to Batch V-owned indexes as T-owned fids *) +(* (intent -> upload -> HEAD CAS); 4 marker after the last V ref is gone, *) +(* then drop the claim. A GC (machine E, reduced: deletes only fids that *) +(* no root reaches) may run at any point; V may be deleted at any point; *) +(* the restore process may crash and a new owner resumes from REMOTE facts *) +(* only (forced move). Mutants are constants (FALSE = the design). *) +(* Reuse: the fid/owner/root vocabulary of the chunk GC model; this *) +(* spec models only what the restore adds, not the superseded list/grace. *) +(***************************************************************************) +EXTENDS Integers, FiniteSets, TLC + +CONSTANTS + NIdx, \* indexes of the volume (1..NIdx) + Batch, \* indexes per independence batch cut + MaxCrash, \* restore-process crashes (each followed by a resume) + MaxGc, \* GC rounds + \* ---- mutants (FALSE = the design) ---- + DropClaimAtFork, \* r0 mutant: the claim on S is dropped right after the fork + CasBeforeUpload, \* batch CAS swaps a ref before its own upload is durable + ListForeign, \* the batch lists the replaced V fid for GC (rule 8 broken) + MarkerEarly, \* marker written before the last V ref is gone + MarkerBeforeCas, \* marker written before the final batch's HEAD CAS + ResumeLocal, \* a new owner trusts a local "done" flag instead of remote facts + SnapDuringRestore, \* a snapshot of T is allowed before the marker + RetentionIgnoresMarker, \* after the marker, V's retention still treats T as holding S + \* ---- added in review (r0.1) ---- + ClaimUntilHead, \* r0.2 OPTION 1: the claim is dropped when T's HEAD is published (today's fork semantics) + NoIntent \* uploaded batch fids are not rooted by an intent before the HEAD CAS + +Idx == 1..NIdx +VF == [i \in Idx |-> <<"V", i>>] \* the source fid of index i +TF == [i \in Idx |-> <<"T", i>>] \* T's own fid for index i +Fids == {VF[i] : i \in Idx} \cup {TF[i] : i \in Idx} +\* r0.1: "no HEAD yet" is a function too (TLC cannot compare a function with a string) +NoHead == [i \in Idx |-> <<"N", i>>] + +VARIABLES + store, \* Fids -> "none" | "pres" | "del" + vlive, \* V still exists (its HEAD roots V fids) + slive, \* S exists + claim, \* the restore's claim on S + thead, \* T's HEAD: Idx -> fid, or "none" before the fork + step, \* restore step: "c" claimed | "f" forked | "own" | "done" + up, \* T fids uploaded durably but not yet in HEAD (current batch) + marker, \* restore/INDEPENDENT exists (remote) + tsnap, \* a snapshot of T (its fid set), {} if none + gclist, \* fids put on a GC list (rule 8 check) + localdone,\* local "restore done" flag of the current owner (ResumeLocal mutant) + crashes, gcs + +vars == <> + +THeadFids == IF thead = NoHead THEN {} ELSE {thead[i] : i \in Idx} +VRefs == {i \in Idx : thead # NoHead /\ thead[i][1] = "V"} +\* roots: V's HEAD (while V lives), S (while it lives), T's HEAD, T's snapshot, +\* uploaded-but-unpublished batch fids (intent roots them), S's fids while claimed +SFids == {VF[i] : i \in Idx} +Roots == (IF vlive THEN SFids ELSE {}) + \cup (IF slive THEN SFids ELSE {}) + \cup THeadFids \cup tsnap \cup (IF NoIntent THEN {} ELSE up) +\* S may be deleted by retention when nothing holds it +SHeld == claim \/ (RetentionIgnoresMarker /\ thead # NoHead) + +Init == + /\ store = [f \in Fids |-> IF f[1] = "V" THEN "pres" ELSE "none"] + /\ vlive = TRUE /\ slive = TRUE /\ claim = FALSE /\ thead = NoHead + /\ step = "start" /\ up = {} /\ marker = FALSE /\ tsnap = {} /\ gclist = {} + /\ localdone = FALSE /\ crashes = 0 /\ gcs = 0 + +\* step 0: S is sealed (given) and claimed +Claim == step = "start" /\ slive /\ claim' = TRUE /\ step' = "c" + /\ UNCHANGED <> + +\* step 1: fork (T HEAD names S's fids, all V-owned) +\* r0.1: two steps. Between them T exists without a HEAD, so only the claim keeps S (and +\* through S its fids) alive; that window is what the claim is for. +ForkBegin == step = "c" /\ step' = "fk" + /\ claim' = (IF DropClaimAtFork THEN FALSE ELSE claim) + /\ UNCHANGED <> +ForkEnd == step = "fk" /\ thead' = VF /\ step' = "own" + /\ claim' = (IF ClaimUntilHead THEN FALSE ELSE claim) + /\ UNCHANGED <> + +\* step 3: one batch: upload own fids for up to Batch V-owned indexes (intent roots them) +BatchSet == {B \in SUBSET VRefs : B # {} /\ Cardinality(B) <= Batch} +Upload(B) == step = "own" /\ up = {} /\ ~ CasBeforeUpload + /\ (\A i \in B : store[VF[i]] = "pres") \* reads its local copy (filled from V) + /\ store' = [f \in Fids |-> IF f \in {TF[j] : j \in B} THEN "pres" ELSE store[f]] + /\ up' = {TF[j] : j \in B} + /\ UNCHANGED <> +\* the batch HEAD CAS: swap exactly the uploaded indexes +Cas == step = "own" /\ up # {} + /\ thead' = [i \in Idx |-> IF TF[i] \in up THEN TF[i] ELSE thead[i]] + /\ gclist' = (IF ListForeign THEN gclist \cup {VF[i] : i \in {j \in Idx : TF[j] \in up}} ELSE gclist) + /\ up' = {} + /\ localdone' = (localdone \/ \A i \in Idx : (thead[i][1] = "V") => (TF[i] \in up)) + /\ UNCHANGED <> +\* mutant: CAS a batch whose upload is not durable (the T fid is still "none") +CasEarly(B) == CasBeforeUpload /\ step = "own" /\ up = {} + /\ thead' = [i \in Idx |-> IF i \in B THEN TF[i] ELSE thead[i]] + /\ UNCHANGED <> +UploadLate == CasBeforeUpload /\ step = "own" + /\ \E i \in Idx : thead[i] = TF[i] /\ store[TF[i]] = "none" + /\ store' = [store EXCEPT ![TF[i]] = "pres"] + /\ UNCHANGED <> + +\* step 4: marker after the last V ref is gone (and the final CAS is done), then drop the claim +Marker == step = "own" /\ ~ marker /\ up = {} + /\ (VRefs = {} \/ MarkerEarly \/ (MarkerBeforeCas /\ Cardinality(VRefs) <= Batch)) + /\ marker' = TRUE /\ step' = "done" /\ localdone' = TRUE + /\ UNCHANGED <> +DropClaim == marker /\ claim /\ claim' = FALSE + /\ UNCHANGED <> + +\* a snapshot of T: refused before the marker (unless the mutant allows it) +SnapT == tsnap = {} /\ thead # NoHead /\ (marker \/ SnapDuringRestore) + /\ tsnap' = THeadFids + /\ UNCHANGED <> + +\* crash of the restore process; the new owner resumes from remote facts (thead, marker) +Crash == crashes < MaxCrash /\ step \in {"fk", "own", "done"} + /\ up' = {} \* an unpublished batch is abandoned; its fids are collectable + /\ step' = (IF ResumeLocal /\ localdone THEN "done" + ELSE IF marker THEN "done" ELSE IF thead = NoHead THEN "fk" ELSE "own") + /\ crashes' = crashes + 1 + /\ UNCHANGED <> + +\* user deletes V; retention deletes S when nothing holds it +DeleteV == vlive /\ vlive' = FALSE + /\ UNCHANGED <> +DeleteS == slive /\ ~ SHeld /\ slive' = FALSE + /\ UNCHANGED <> + +\* GC (reduced machine E): deletes present fids no root reaches, and fids put on the list +Gc == gcs < MaxGc + /\ store' = [f \in Fids |-> IF store[f] = "pres" /\ (f \notin Roots \/ f \in gclist) THEN "del" ELSE store[f]] + /\ gcs' = gcs + 1 + /\ UNCHANGED <> + +Next == Claim \/ ForkBegin \/ ForkEnd \/ Cas \/ Marker \/ DropClaim \/ SnapT \/ Crash \/ DeleteV \/ DeleteS \/ Gc \/ UploadLate + \/ (\E B \in BatchSet : Upload(B) \/ CasEarly(B)) + +Spec == Init /\ [][Next]_vars + +---------------------------------------------------------------------------- +\* INV-RESTORE-NO-GAP: every index of T's HEAD resolves to a present fid +NoGap == thead = NoHead \/ \A i \in Idx : store[thead[i]] = "pres" +\* INV-RESTORE-INDEPENDENT: after the marker, T roots no V fid (HEAD or snapshot) +Independent == marker => (VRefs = {} /\ \A f \in tsnap : f[1] = "T") +\* INV-RESTORE-NO-FOREIGN-LIST: a restore never lists a V fid +NoForeignList == \A f \in gclist : f[1] = "T" +\* INV-RESTORE-CLAIM-UNTIL-INDEPENDENT +ClaimUntilIndependent == (thead # NoHead /\ ~ marker) => claim +\* r0.2 option 1: the claim covers exactly the window in which T exists without a HEAD +ClaimUntilHead_Inv == (step = "fk") => claim +\* lifecycle independence: after the marker and the claim drop, nothing of T holds S +LifecycleFree == (marker /\ ~ claim) => ~ SHeld +\* INV-RESTORE-STATE-REMOTE: "done" only when the remote marker exists +StateRemote == step = "done" => marker + +TypeOK == /\ step \in {"start", "c", "fk", "own", "done"} /\ up \subseteq Fids /\ tsnap \subseteq Fids +\* witnesses (r0.1): each is an invariant expected to be VIOLATED, proving the state is reachable +W_Done == ~ (marker /\ ~ claim /\ ~ slive /\ ~ vlive /\ \A i \in Idx : store[VF[i]] = "del") +W_CrashResume == ~ (marker /\ crashes = MaxCrash) +============================================================================= diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg new file mode 100644 index 0000000000..70a61b6cee --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = TRUE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg new file mode 100644 index 0000000000..5dae146b29 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = TRUE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = TRUE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilHead_Inv + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg new file mode 100644 index 0000000000..82592e7bc4 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = TRUE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg new file mode 100644 index 0000000000..560a8c4cc7 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = TRUE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg new file mode 100644 index 0000000000..38b2ecc46a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = TRUE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg new file mode 100644 index 0000000000..b2ed698e1f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg new file mode 100644 index 0000000000..383cbda367 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = TRUE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg new file mode 100644 index 0000000000..6c115a1f13 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = TRUE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg new file mode 100644 index 0000000000..dce285726d --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = TRUE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg new file mode 100644 index 0000000000..682ed72f1f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = TRUE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilHead_Inv + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg new file mode 100644 index 0000000000..bf269afeae --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 2 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = TRUE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilHead_Inv + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg new file mode 100644 index 0000000000..34c9db075b --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 4 + Batch = 2 + MaxCrash = 2 + MaxGc = 4 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = TRUE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilHead_Inv + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg new file mode 100644 index 0000000000..9590e854ad --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg @@ -0,0 +1,24 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg new file mode 100644 index 0000000000..1ab2298c47 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg @@ -0,0 +1,25 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilIndependent + LifecycleFree + StateRemote + W_CrashResume diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg new file mode 100644 index 0000000000..3d9c60ac18 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg @@ -0,0 +1,25 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = TRUE + NoIntent = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + ClaimUntilHead_Inv + LifecycleFree + StateRemote + W_Done From 88aea4c7ed8a03526d596822c393ef28fafb7368 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:23:53 -0800 Subject: [PATCH 5/8] restore: fold review of part A (fill permit, permit ownership, stale snapshot image, docs) - HydrateAll admits each fill as a background fill permit with no cut payload (the real limiter refuses a payload for BackgroundFill, so no fill ever ran), and the permit now belongs to the flight: the walker queues the shared flight without becoming a waiter and a layer-owned goroutine releases the permit when the flight's I/O is over (new settled signal, closed by the worker after fillOnce or when an unrun flight is removed), also after an early return on cancel, revocation or close. The limiter's abort callback stops the walker. The flight lookup is factored into hydrationFlightLocked (shared with OnReadMissContext, no behaviour change there). - CreateSnapshot on a restore volume also checks the supplied image: a cut saved before the marker that still names another volume's chunks is refused. - dropIntent keeps outliving the caller's cancellation but is bounded by dropIntentTimeout (it had no deadline at all). - Tests: the real hostlimit limiter (fill permits, payload 0, all released), permit held while a cancelled walker's Get is held, revocation, a witnessed pause for guests, cancel returning while the Get is held, bounded joins; stale pre-independence image refused; aborted first HEAD keeps the parent as fork_parent until the target is deleted; dropIntent bounded. - Docs: invariants.md M4/M6 rows and INV-RESTORE-* rows, GC owner rooting recorded as load-bearing in INV-GC-REACHABLE-001; restore diagram in the workspace design; RestoreIndependence in docs/spec/README.md (simulation). Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 18 +- .../core/frontend/chunkstore/restore.go | 31 +- .../core/frontend/chunkstore/restore_test.go | 111 ++++++++ .../core/storage/chunk_hydrate_all.go | 135 +++++++-- .../core/storage/chunk_hydrate_all_test.go | 264 +++++++++++++++--- seaweed-block/core/storage/chunk_hydration.go | 81 ++++-- seaweed-block/core/storage/chunk_layer.go | 1 + .../docs/design/agent-workspace-design.md | 18 +- seaweed-block/docs/design/invariants.md | 12 +- seaweed-block/docs/spec/README.md | 2 + 10 files changed, 555 insertions(+), 118 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index c4ca9e9b8b..a9d0553b6e 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -753,11 +753,18 @@ func (c *Catalog) AbortSnapshot(ctx context.Context, vol, name, attempt string) // is confirmed or can never apply. It never touches another attempt's // intent, even under the same operation: an earlier attempt's create may // still be held by the server and land later (W5 rule). A failed delete -// leaves the intent, which only over-protects. +// leaves the intent, which only over-protects. The delete outlives the +// caller's cancellation (cleanup after a refused or cancelled request) but is +// bounded by dropIntentTimeout, so it can never hang on an unresponsive filer. func (c *Catalog) dropIntent(ctx context.Context, root, id string) { - _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(root, intentsDir), id, nil) + dctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dropIntentTimeout) + defer cancel() + _ = c.f.DeleteEntry(dctx, path.Join(root, intentsDir), id, nil) } +// dropIntentTimeout bounds one intent delete (a var so tests can shorten it). +var dropIntentTimeout = 30 * time.Second + type createOutcome int const ( @@ -873,6 +880,13 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe } else if !independent { return SnapshotInfo{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s is still being restored: snapshots are refused until it is independent", vol) } + // The supplied image need not be the current HEAD: a cut taken before + // the marker may still name the source's chunks. Check the image itself. + if q, err := c.foreignRefsOf(ctx, vol, head); err != nil { + return SnapshotInfo{}, err + } else if q > 0 { + return SnapshotInfo{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s: snapshot image gen %d holds %d refs to another volume", vol, head.Gen, q) + } } // Take the name: this request's record, or an earlier attempt's of it. diff --git a/seaweed-block/core/frontend/chunkstore/restore.go b/seaweed-block/core/frontend/chunkstore/restore.go index 4ba43e7b6a..22a12d1f83 100644 --- a/seaweed-block/core/frontend/chunkstore/restore.go +++ b/seaweed-block/core/frontend/chunkstore/restore.go @@ -88,20 +88,11 @@ func (c *Catalog) MarkIndependent(ctx context.Context, vol string) (RestoreIndep if !has || h.State == storage.ChunkHeadAborted || headDeletingOrDeleted(h) { return RestoreIndependence{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s has no live HEAD", vol) } - // The manifest segments name chunk refs too: check the resolved HEAD (every - // segment key and every chunk ref inside), as GC and usage resolve it. - if c.blobs == nil { - return RestoreIndependence{}, errors.New("chunkstore: restore marker needs the segment reader") - } - r, err := NewChunkRemote(c.f, c.blobs, path.Join(c.base, vol)) + q, err := c.foreignRefsOf(ctx, vol, h) if err != nil { return RestoreIndependence{}, err } - resolved, err := r.resolveManifest(ctx, h) - if err != nil { - return RestoreIndependence{}, remoteErr(err, "resolve HEAD of %s", vol) - } - if q := ForeignRefs(resolved, vol); q > 0 { + if q > 0 { return RestoreIndependence{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s: HEAD gen %d still holds %d refs to another volume", vol, h.Gen, q) } m := RestoreIndependence{Format: volumeFormat, VolumeID: vol, HeadGen: h.Gen, MarkedNs: c.now().UnixNano()} @@ -152,3 +143,21 @@ func (c *Catalog) ReadIndependence(ctx context.Context, vol string) (RestoreInde } return m, true, nil } + +// foreignRefsOf counts the refs to other volumes in image h of vol, resolved: +// the manifest segments name chunk refs too, so every segment key and every +// chunk ref inside is checked, as GC and usage resolve it. +func (c *Catalog) foreignRefsOf(ctx context.Context, vol string, h storage.ChunkHead) (int, error) { + if c.blobs == nil { + return 0, errors.New("chunkstore: restore independence needs the segment reader") + } + r, err := NewChunkRemote(c.f, c.blobs, path.Join(c.base, vol)) + if err != nil { + return 0, err + } + resolved, err := r.resolveManifest(ctx, h) + if err != nil { + return 0, remoteErr(err, "resolve gen %d of %s", h.Gen, vol) + } + return ForeignRefs(resolved, vol), nil +} diff --git a/seaweed-block/core/frontend/chunkstore/restore_test.go b/seaweed-block/core/frontend/chunkstore/restore_test.go index b30af27438..6959ac850b 100644 --- a/seaweed-block/core/frontend/chunkstore/restore_test.go +++ b/seaweed-block/core/frontend/chunkstore/restore_test.go @@ -291,3 +291,114 @@ func TestRestore_SnapshotsRefusedUntilIndependent(t *testing.T) { t.Fatalf("a snapshot of an independent restore names %d foreign refs", ForeignRefs(s.Head(), "v2")) } } + +// hangingDeleteFiler blocks DeleteEntry until its ctx ends and records whether +// that ctx carried a deadline. +type hangingDeleteFiler struct { + Filer + hadDeadline chan bool +} + +func (h hangingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { + _, ok := ctx.Deadline() + h.hadDeadline <- ok + <-ctx.Done() + return ctx.Err() +} + +// dropIntent outlives a cancelled caller, but one unresponsive delete must still be bounded. +func TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled(t *testing.T) { + old := dropIntentTimeout + dropIntentTimeout = 50 * time.Millisecond + t.Cleanup(func() { dropIntentTimeout = old }) + h := hangingDeleteFiler{Filer: newFakeFiler(), hadDeadline: make(chan bool, 1)} + c := &Catalog{f: h} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + done := make(chan struct{}) + go func() { c.dropIntent(ctx, "/vols/v1", "op-1"); close(done) }() + select { + case ok := <-h.hadDeadline: + if !ok { + t.Fatal("the intent delete ran without any deadline") + } + case <-time.After(5 * time.Second): + t.Fatal("dropIntent never reached the filer") + } + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("dropIntent did not return: the delete is unbounded") + } +} + +// A cut image saved before the marker still names the source's chunks: the +// marker must not let it become a snapshot. +func TestRestore_SnapshotOfAStalePreIndependenceImageRefused(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + stale, _ := r2.GetHead(ctx) + h := ownAll(t, f, b, "v2") + if _, err := c.MarkIndependent(ctx, "v2"); err != nil { + t.Fatal(err) + } + req := SnapshotRequest{Name: "stale", RequestID: "s"} + if _, err := c.CreateSnapshot(ctx, "v2", req, stale); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("stale foreign image after the marker: %v, want %s", err, CodeRestoreIncomplete) + } + if _, ok, err := c.SnapshotReplay(ctx, "v2", req); err != nil || ok { + t.Fatalf("a refused snapshot must leave nothing: ok=%v err=%v", ok, err) + } + if list, _, err := c.ListSnapshots(ctx, "v2", ListOptions{}); err != nil || len(list) != 0 { + t.Fatalf("snapshots after the refusal: %v %v", list, err) + } + if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "own", RequestID: "o"}, h); err != nil { + t.Fatalf("the own image must still be accepted: %v", err) + } +} + +// Retention disposition with an aborted first HEAD on a restore target: the +// fork claim alone no longer holds the parent (liveClaims counts any HEAD, +// aborted included), but the fork-record scan does (forkParentsNeeded treats +// an aborted HEAD as no HEAD), so the parent snapshot is kept as fork_parent +// until the aborted target is deleted. That conservative hold is the rule. +func TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted(t *testing.T) { + f, c, _, _ := retentionFixture(t, 1) + ctx := context.Background() + if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy + t.Fatal(err) + } + for _, vol := range []string{"v1", "v2"} { + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + } + holdFirst(f, catBase+"/v2/HEAD") + if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s00", Target: "v2", RequestID: "rs"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("restore with a held HEAD create: %v", err) + } + if claimed, err := c.AbortFork(ctx, "v2"); err != nil || !claimed { + t.Fatalf("abort the unpublished restore: claimed=%v %v", claimed, err) + } + if live, err := c.liveClaims(ctx, "v1", "s00", []string{forkClaim("v2", "rs")}); err != nil || len(live) != 0 { + t.Fatalf("claim on an aborted target: live=%v %v, want not live (any HEAD ends the claim)", live, err) + } + res, err := c.Retain(ctx, "v1", false) + if err != nil { + t.Fatal(err) + } + if k := kept(res.Decisions); len(k) != 1 || k["s00"] == nil || k["s00"][0] != keepForkParent || len(res.Deleted) != 0 { + t.Fatalf("aborted restore: kept %v deleted %v; want s00 kept as fork_parent", k, res.Deleted) + } + if s, err := c.allSnapshots(ctx, "v1"); err != nil || len(s) != 1 { + t.Fatalf("parent after retention: %v %v", s, err) + } + if _, err := c.DeleteVolume(ctx, "v2", nil); err != nil { + t.Fatalf("delete the aborted restore: %v", err) + } + res, err = c.Retain(ctx, "v1", false) + if err != nil || len(res.Deleted) != 1 || res.Deleted[0] != "s00" { + t.Fatalf("after the target is gone: deleted %v (%v), want s00", res.Deleted, err) + } +} diff --git a/seaweed-block/core/storage/chunk_hydrate_all.go b/seaweed-block/core/storage/chunk_hydrate_all.go index 094ec50b24..01f9ad5ea2 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all.go +++ b/seaweed-block/core/storage/chunk_hydrate_all.go @@ -3,6 +3,7 @@ package storage import ( "context" "errors" + "sync" "time" ) @@ -31,14 +32,29 @@ var ( // the absent chunks lowest index first through the same shared fill flights // as guest read misses (one fetch per chunk, the hydration queue bound and // the read-miss timeout apply), so it never fetches a chunk twice or races a -// guest fill. It yields while any flight has guest waiters, and admits each -// fill through the host limiter (cfg.Budget) with ctx: the caller sets the -// limiter class on ctx (hostlimit.WithClass(ctx, hostlimit.BackgroundFill)). -// It returns when nothing is absent, when ctx ends, or on a fill error that -// is not a retryable pending state; the caller may call it again. +// guest fill. It yields while any flight has guest waiters; its own flights +// have no waiters, so workers serve guest flights first. +// +// Each fill holds one host-limiter permit (cfg.Budget), admitted with ctx and +// no cut payload, the background fill/idle contract (hostlimit Acquire): the +// caller sets the class on ctx (hostlimit.WithClass(ctx, +// hostlimit.BackgroundFill)). The permit belongs to the flight, not the wait: +// it is released only when the flight's I/O is over, also when the walker +// returns early on cancellation, revocation or close. The limiter's abort +// callback (revocation) stops the walker, which then returns the cause. +// +// It returns when nothing is absent, when ctx ends or the permit is revoked, +// or on a fill error that is not a retryable pending state; the caller may +// call it again. func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error) { var p HydrateProgress + walk, stop := context.WithCancelCause(ctx) + defer stop(nil) backoff := hydrateAllMinBackoff + quit := func(err error) (HydrateProgress, error) { + p.Remaining = l.absentHydratable() + return p, err + } wait := func() error { t := time.NewTimer(backoff) defer t.Stop() @@ -48,16 +64,15 @@ func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error select { case <-t.C: return nil - case <-ctx.Done(): - return ctx.Err() + case <-walk.Done(): + return context.Cause(walk) case <-l.ctx.Done(): return errChunkLayerClosed } } for { - if err := ctx.Err(); err != nil { - p.Remaining = l.absentHydratable() - return p, err + if walk.Err() != nil { + return quit(context.Cause(walk)) } lba, ok, guests := l.nextHydrateTarget() if !ok { @@ -66,40 +81,97 @@ func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error } if guests > 0 { p.Paused++ + if hook := l.testHydrateAllPause; hook != nil { + hook() + } if err := wait(); err != nil { - p.Remaining = l.absentHydratable() - return p, err + return quit(err) } continue } - release, err := l.admitFill(ctx) + release, err := l.admitFill(walk, stop) if err != nil { p.Deferred++ if err := wait(); err != nil { - p.Remaining = l.absentHydratable() - return p, err + return quit(err) } continue } - _, err = l.OnReadMissContext(ctx, lba) - release() + f, err := l.startWalkerFill(lba, release) + if err != nil { + if errors.Is(err, ErrChunkHydrationPending) { + if err := wait(); err != nil { // queue full: retry later + return quit(err) + } + continue + } + return quit(err) + } + if f == nil { + continue // resolved meanwhile + } + select { + case <-f.done: + case <-walk.Done(): + return quit(context.Cause(walk)) + case <-l.ctx.Done(): + return quit(errChunkLayerClosed) + } + l.stMu.Lock() + changed := l.absentGen[f.idx] != f.gen || l.head.Chunks[f.idx] != f.ref + ferr := f.err + l.stMu.Unlock() switch { - case err == nil: + case changed: + // a newer absence or HEAD: the next pass looks again + case ferr == nil: p.Filled++ backoff = hydrateAllMinBackoff - case errors.Is(err, ErrChunkHydrationPending): - // queue full or the read-miss timeout: retry the same chunk later - if err := wait(); err != nil { - p.Remaining = l.absentHydratable() - return p, err + case errors.Is(ferr, ErrChunkHydrationPending): + if err := wait(); err != nil { // the read-miss timeout: retry later + return quit(err) } default: - p.Remaining = l.absentHydratable() - return p, err + return quit(ferr) } } } +// startWalkerFill queues (or joins) the fill flight of lba's chunk without +// becoming a waiter, and hands the permit's release to the flight's +// settlement: a layer-owned goroutine releases it once the flight's I/O is +// over, whatever the walker does meanwhile. A nil flight means nothing is to +// fetch any more (release already called). +func (l *chunkLayerImpl) startWalkerFill(lba uint64, release func()) (*chunkHydrationFlight, error) { + idx := l.chunkOf(lba) + l.stMu.Lock() + defer l.stMu.Unlock() + if l.closed { + release() + return nil, errChunkLayerClosed + } + ref, named := l.head.Chunks[idx] + if !l.absent[idx] || l.localBlocks[lba] || !named { + release() + return nil, nil + } + f, _, err := l.hydrationFlightLocked(idx, ref) + if err != nil { + release() + return nil, err + } + l.wakeHydrationLocked() + // Close joins wg only after taking stMu and marking closed; every queued + // flight is settled by closeHydrationLocked, every running one by its worker. + l.wg.Add(1) + go func() { + defer l.wg.Done() + <-f.settled + release() + }() + return f, nil +} + // nextHydrateTarget returns a block of the lowest-index chunk that HEAD names, // is absent and has a block without a local extent version (localBlocks: a // chunk whose every block reached the extent needs no fetch; a write still only @@ -157,16 +229,19 @@ func (l *chunkLayerImpl) hydratableBlockLocked(idx uint64) (uint64, bool) { return 0, false } -// admitFill reserves one chunk of fill payload from the host limiter, if -// there is one; the returned release gives it back. -func (l *chunkLayerImpl) admitFill(ctx context.Context) (func(), error) { +// admitFill takes one background permit from the host limiter, if there is +// one: no cut payload (a fill/idle permit carries none and the limiter refuses +// one), the class from ctx. A revocation runs abort, which stops the walker. +// The returned release gives the permit back, once. +func (l *chunkLayerImpl) admitFill(ctx context.Context, abort func(error)) (func(), error) { host := l.cfg.Budget if host == nil { return func() {}, nil } - ticket, err := host.Admit(ctx, int64(l.chunkBlocks)*int64(l.blockSize), func(error) {}) + ticket, err := host.Admit(ctx, 0, abort) if err != nil { return nil, err } - return func() { host.Release(ticket) }, nil + var once sync.Once + return func() { once.Do(func() { host.Release(ticket) }) }, nil } diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go index 9ff3d672e6..b6bec6ebc5 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all_test.go +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -8,6 +8,8 @@ import ( "sync" "testing" "time" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" ) func countGets(r *fakeChunkRemote) map[string]int { @@ -29,6 +31,96 @@ func fastWalker(t *testing.T) { t.Cleanup(func() { hydrateAllMinBackoff, hydrateAllMaxBackoff = minB, maxB }) } +// walkRun is one HydrateAll call on its own goroutine. Its ctx is cancelled +// and its return joined (bounded) at cleanup, registered before launch. +type walkRun struct { + done chan struct{} + cancel context.CancelFunc + p HydrateProgress + err error +} + +func startWalker(t *testing.T, layer *chunkLayerImpl, parent context.Context) *walkRun { + t.Helper() + ctx, cancel := context.WithCancel(parent) + w := &walkRun{done: make(chan struct{}), cancel: cancel} + t.Cleanup(func() { + cancel() + select { + case <-w.done: + case <-time.After(ctLocalBound): + t.Error("cleanup: walker did not return") + } + }) + go func() { + w.p, w.err = layer.HydrateAll(ctx) + close(w.done) + }() + return w +} + +func (w *walkRun) wait(t *testing.T, what string) { + t.Helper() + select { + case <-w.done: + case <-time.After(ctLocalBound): + t.Fatalf("%s: walker did not return", what) + } +} + +func walkerSignal[T any](t *testing.T, ch <-chan T, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(ctLocalBound): + t.Fatalf("timed out waiting for %s", what) + } +} + +// waitUntil polls cond (bounded by ctLocalBound); permits are released +// asynchronously, when each flight settles. +func waitUntil(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(ctLocalBound) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting until %s", what) + } + time.Sleep(time.Millisecond) + } +} + +// fillLimiter is a real host limiter on pool dir with fillSlots fill permits. +func fillLimiter(t *testing.T, dir string, fillSlots int) *hostlimit.Limiter { + t.Helper() + c := hostlimit.DefaultConfig(dir) + c.FillSlots = fillSlots + l, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + t.Cleanup(l.Close) + return l +} + +// payloadRecorder passes admissions to a real Budget and records each payload. +type payloadRecorder struct { + Budget + mu sync.Mutex + payloads []int64 +} + +func (r *payloadRecorder) Admit(ctx context.Context, payload int64, abort func(error)) (uint64, error) { + r.mu.Lock() + r.payloads = append(r.payloads, payload) + r.mu.Unlock() + return r.Budget.Admit(ctx, payload, abort) +} + +func bgFill() context.Context { + return hostlimit.WithClass(context.Background(), hostlimit.BackgroundFill) +} + func TestHydrateAll_FillsEveryChunkOnceAndReadsTheHeadImage(t *testing.T) { fastWalker(t) s, layer, remote, _ := hydrationFixture(t, 2, 64) @@ -86,23 +178,24 @@ func TestHydrateAll_NeverOverwritesALocalWrite(t *testing.T) { } } +// The walker's deferral is witnessed (its pause hook fires) while the guest's +// fetch is held, before anything is allowed to progress. func TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice(t *testing.T) { fastWalker(t) s, layer, remote, registered := hydrationFixture(t, 2, 64) + paused := make(chan struct{}, 1) + layer.testHydrateAllPause = func() { + select { + case paused <- struct{}{}: + default: + } + } entered, release := holdNextGet(t, remote) guest := startHydrationRead(t, s, context.Background(), 5*ctChunkBlocks) waitHydrationRegistration(t, registered, 1) - <-entered // the guest's fetch of chunk 5 is held - type res struct { - p HydrateProgress - err error - } - walked := make(chan res, 1) - go func() { - p, err := layer.HydrateAll(context.Background()) - walked <- res{p, err} - }() - time.Sleep(30 * time.Millisecond) + walkerSignal(t, entered, "the guest's fetch of chunk 5") + w := startWalker(t, layer, context.Background()) + walkerSignal(t, paused, "the walker to yield to the held guest fetch") if n := len(countGets(remote)); n != 1 { t.Fatalf("the walker fetched while a guest was waiting: %d distinct gets", n) } @@ -110,14 +203,9 @@ func TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice(t *testing.T) { if r := hydrationOutcome(t, guest); r.err != nil { t.Fatalf("guest read: %v", r.err) } - var r res - select { - case r = <-walked: - case <-time.After(ctLocalBound): - t.Fatal("walker did not finish") - } - if r.err != nil || r.p.Remaining != 0 || r.p.Paused == 0 || r.p.Filled != ctNumBlocks/ctChunkBlocks-1 { - t.Fatalf("walker: %+v %v, want paused for the guest and the 7 other chunks filled", r.p, r.err) + w.wait(t, "after the guest fill") + if w.err != nil || w.p.Remaining != 0 || w.p.Paused == 0 || w.p.Filled != ctNumBlocks/ctChunkBlocks-1 { + t.Fatalf("walker: %+v %v, want paused for the guest and the 7 other chunks filled", w.p, w.err) } for key, n := range countGets(remote) { if n != 1 { @@ -134,12 +222,14 @@ type walkerBudget struct { admitted int released int classes []any + abort func(error) } -func (b *walkerBudget) Admit(ctx context.Context, _ int64, _ func(error)) (uint64, error) { +func (b *walkerBudget) Admit(ctx context.Context, _ int64, abort func(error)) (uint64, error) { b.mu.Lock() defer b.mu.Unlock() b.classes = append(b.classes, ctx.Value(walkerClassKey{})) + b.abort = abort if b.refuse > 0 { b.refuse-- return 0, errors.New("fill class over budget") @@ -154,6 +244,12 @@ func (b *walkerBudget) Release(uint64) { b.mu.Unlock() } +func (b *walkerBudget) counts() (admitted, released int) { + b.mu.Lock() + defer b.mu.Unlock() + return b.admitted, b.released +} + func TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass(t *testing.T) { fastWalker(t) _, layer, _, _ := hydrationFixture(t, 2, 64) @@ -164,10 +260,11 @@ func TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass(t *testin if err != nil || p.Remaining != 0 || p.Deferred != 2 { t.Fatalf("hydrate all: %+v %v, want 2 deferred then everything filled", p, err) } + waitUntil(t, "every permit is released", func() bool { a, r := budget.counts(); return a == r }) budget.mu.Lock() defer budget.mu.Unlock() - if budget.admitted != p.Filled || budget.released != budget.admitted { - t.Fatalf("budget admitted %d released %d, filled %d: every fill admitted once and released", budget.admitted, budget.released, p.Filled) + if budget.admitted != p.Filled { + t.Fatalf("budget admitted %d, filled %d: every fill admitted once", budget.admitted, p.Filled) } for _, c := range budget.classes { if c != "fill" { @@ -176,30 +273,115 @@ func TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass(t *testin } } -func TestHydrateAll_CancelReturnsTheRemainingCount(t *testing.T) { +func TestHydrateAll_CancelReturnsWhileTheFetchIsHeld(t *testing.T) { fastWalker(t) _, layer, remote, _ := hydrationFixture(t, 2, 64) - entered, release := holdNextGet(t, remote) - defer release() - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan HydrateProgress, 1) - go func() { - p, _ := layer.HydrateAll(ctx) - done <- p - }() - <-entered - cancel() - release() - select { - case p := <-done: - if p.Remaining == 0 { - t.Fatalf("cancelled walk reports nothing remaining: %+v", p) - } - case <-time.After(ctLocalBound): - t.Fatal("cancelled walker did not return") + entered, _ := holdNextGet(t, remote) + w := startWalker(t, layer, context.Background()) + walkerSignal(t, entered, "the walker's first fetch") + w.cancel() + w.wait(t, "cancel with the fetch still held") + if !errors.Is(w.err, context.Canceled) || w.p.Remaining == 0 { + t.Fatalf("cancelled walk: %+v %v, want context.Canceled and chunks remaining", w.p, w.err) } } +// The real limiter refuses a background permit that carries a cut payload: +// every fill must be admitted as a fill permit (no payload) under +// BackgroundFill, fill the HEAD image exactly, and give every permit back. +func TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + lim := fillLimiter(t, t.TempDir(), 2) + rec := &payloadRecorder{Budget: lim} + layer.cfg.Budget = rec + ctx, cancel := context.WithTimeout(bgFill(), ctLocalBound) + defer cancel() + p, err := layer.HydrateAll(ctx) + if err != nil || p.Remaining != 0 || p.Filled != ctNumBlocks/ctChunkBlocks || p.Deferred != 0 { + t.Fatalf("hydrate all under the real limiter: %+v %v", p, err) + } + for b := uint32(0); b < ctNumBlocks; b++ { + if got, err := s.Read(b); err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, byte(0x40+b))) { + t.Fatalf("block %d after hydrate: %v", b, err) + } + } + for key, n := range countGets(remote) { + if n != 1 { + t.Fatalf("chunk %s fetched %d times", key, n) + } + } + rec.mu.Lock() + for _, n := range rec.payloads { + if n != 0 { + t.Fatalf("fill admitted with a %d-byte cut payload", n) + } + } + rec.mu.Unlock() + waitUntil(t, "every fill permit is admitted once and released", func() bool { + st := lim.Snapshot().(hostlimit.Stats) + return st.Admitted == uint64(p.Filled) && st.Released == st.Admitted && st.Active == 0 && st.Skipped == 0 + }) +} + +// The permit follows the owned flight, not the walker's wait: a cancelled +// walker returns at once, but its fill permit stays taken until the held +// physical Get settles. +func TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + dir := t.TempDir() + layer.cfg.Budget = fillLimiter(t, dir, 1) + contender := fillLimiter(t, dir, 1) + entered, release := holdNextGet(t, remote) + w := startWalker(t, layer, bgFill()) + walkerSignal(t, entered, "the walker's fetch") + w.cancel() + w.wait(t, "cancel with the fetch still held") + if !errors.Is(w.err, context.Canceled) { + t.Fatalf("cancelled walk: %v", w.err) + } + if tk, err := contender.Acquire(context.Background(), hostlimit.BackgroundFill, nil); err == nil { + contender.Release(tk) + t.Fatal("the fill permit was free while the walker's Get was still running") + } else if !errors.Is(err, hostlimit.ErrBusy) { + t.Fatalf("contender: %v", err) + } + release() + waitUntil(t, "the permit is free after the Get settled", func() bool { + tk, err := contender.Acquire(context.Background(), hostlimit.BackgroundFill, nil) + if err == nil { + contender.Release(tk) + } + return err == nil + }) +} + +// A limiter revocation (the abort callback) stops the walker with the cause; +// the permit is still released only when the owned fetch settles. +func TestHydrateAll_RevocationStopsTheWalker(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + budget := &walkerBudget{} + layer.cfg.Budget = budget + entered, release := holdNextGet(t, remote) + w := startWalker(t, layer, context.Background()) + walkerSignal(t, entered, "the walker's fetch") + budget.mu.Lock() + abort := budget.abort + budget.mu.Unlock() + abort(hostlimit.ErrRevoked) + w.wait(t, "revocation with the fetch still held") + if !errors.Is(w.err, hostlimit.ErrRevoked) { + t.Fatalf("revoked walk: %v, want ErrRevoked", w.err) + } + if _, r := budget.counts(); r != 0 { + t.Fatal("permit released before the owned fetch settled") + } + release() + waitUntil(t, "the permit is released after the fetch settled", func() bool { _, r := budget.counts(); return r == 1 }) +} + func TestHydrateAll_StatsReportAbsentChunks(t *testing.T) { fastWalker(t) _, layer, _, _ := hydrationFixture(t, 2, 64) diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go index 2291ea22cc..acd4e3f8af 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -34,6 +34,7 @@ type chunkHydrationFlight struct { ctx context.Context cancel context.CancelFunc done chan struct{} + settled chan struct{} // closed once its I/O is over: after fillOnce, or removal unrun running bool waiters int err error @@ -76,39 +77,15 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b l.stMu.Unlock() return nil, hydrationPending(err) } - gen := l.absentGen[idx] - f := l.hydration[idx] - stale := f != nil && (f.gen != gen || f.ref != ref) - if stale { - f.cancel() - // The old worker remains owned and joined, but cannot delay a - // new generation or remove its replacement when it finishes. - delete(l.hydration, idx) - close(f.done) - f = nil + f, joined, err := l.hydrationFlightLocked(idx, ref) + if err != nil { + l.stats.Hydration.WaitRefusals++ + l.stMu.Unlock() + return nil, err } - if f != nil && !stale { + if joined { l.stats.Hydration.Joined++ } - if f == nil { - if len(l.hydration) >= l.cfg.HydrationQueueDepth { - l.stats.Hydration.WaitRefusals++ - l.stMu.Unlock() - return nil, hydrationPending(nil) - } - if !l.hydrationStarted { - l.hydration = make(map[uint64]*chunkHydrationFlight) - l.hydrationWake = make(chan struct{}, 1) - l.hydrationStarted = true - l.wg.Add(l.cfg.HydrationWorkers) - for i := 0; i < l.cfg.HydrationWorkers; i++ { - go l.hydrationWorker() - } - } - work, cancel := context.WithCancel(l.ctx) - f = &chunkHydrationFlight{idx: idx, gen: gen, ref: ref, ctx: work, cancel: cancel, done: make(chan struct{})} - l.hydration[idx] = f - } f.waiters++ l.wakeHydrationLocked() l.stMu.Unlock() @@ -138,7 +115,7 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b f.waiters-- closed := l.closed changed := l.absentGen[idx] != f.gen || l.head.Chunks[idx] != f.ref - err := f.err + err = f.err if !closed && !changed && errors.Is(err, ErrChunkHydrationPending) { l.stats.Hydration.WaitRefusals++ } @@ -157,6 +134,46 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b } } +// hydrationFlightLocked returns the flight for chunk idx's current absence +// (generation and HEAD ref): an existing one (joined) or a new queued one. A +// stale flight of an older generation is settled and replaced. It refuses with +// hydrationPending when the queue is full. The caller holds stMu, counts its +// own waiter and wakes the workers. +func (l *chunkLayerImpl) hydrationFlightLocked(idx uint64, ref chunkRef) (*chunkHydrationFlight, bool, error) { + gen := l.absentGen[idx] + f := l.hydration[idx] + if f != nil && (f.gen != gen || f.ref != ref) { + f.cancel() + // The old worker remains owned and joined, but cannot delay a + // new generation or remove its replacement when it finishes. + delete(l.hydration, idx) + close(f.done) + if !f.running { + close(f.settled) // never picked up: no I/O will run + } + f = nil + } + if f != nil { + return f, true, nil + } + if len(l.hydration) >= l.cfg.HydrationQueueDepth { + return nil, false, hydrationPending(nil) + } + if !l.hydrationStarted { + l.hydration = make(map[uint64]*chunkHydrationFlight) + l.hydrationWake = make(chan struct{}, 1) + l.hydrationStarted = true + l.wg.Add(l.cfg.HydrationWorkers) + for i := 0; i < l.cfg.HydrationWorkers; i++ { + go l.hydrationWorker() + } + } + work, cancel := context.WithCancel(l.ctx) + f = &chunkHydrationFlight{idx: idx, gen: gen, ref: ref, ctx: work, cancel: cancel, done: make(chan struct{}), settled: make(chan struct{})} + l.hydration[idx] = f + return f, false, nil +} + func (l *chunkLayerImpl) wakeHydrationLocked() { select { case l.hydrationWake <- struct{}{}: @@ -196,6 +213,7 @@ func (l *chunkLayerImpl) hydrationWorker() { resolved, err := l.fillOnce(fetch, next.idx, next.gen, next.ref) cancel() next.cancel() + close(next.settled) l.stMu.Lock() if hydrationContextCauseOnly(err) { err = hydrationPending(err) @@ -225,6 +243,7 @@ func (l *chunkLayerImpl) closeHydrationLocked() { f.err = errChunkLayerClosed delete(l.hydration, idx) close(f.done) + close(f.settled) } } } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 0ad915f960..3ed9ec97b5 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -127,6 +127,7 @@ type chunkLayerImpl struct { // Test-only scheduling hooks; nil in production. testHydrationWait func(uint64) // after promise registration, outside locks + testHydrateAllPause func() // HydrateAll yielded to a guest waiter, outside locks testCOWWait func() testCOWSaverWait func() testCOWRead func(idx uint64, saved bool) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index d4d621ecd1..ff5a22bbbf 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -187,6 +187,7 @@ stateDiagram-v2 - **Snapshot** (`Catalog.CreateSnapshot`): claim the name with an exclusive name record `{request, attempt}` (a retry gets its own attempt back); check the volume is not being deleted; write an intent with a deadline; re-check the deadline; exclusively create `snaps//` holding a copy of the HEAD root. An unknown outcome keeps the intent; the caller retries with the same request id. - **Fork** (`Catalog.Fork`): claim the parent snapshot, check the source is not being deleted, write the target `VOLUME` (origin fork), then a HEAD at gen 1, epoch 0, no holder, with the parent's `RemoteLSN` and references. No segment or chunk is copied: the fork's references are owner-qualified, so it reads the parent's objects, and its root alone keeps them live after the parent snapshot is deleted. +- **Restore** (`Catalog.Restore`, independent restore): the fork steps with `VOLUME` origin `restore`; the claim is the fork's (live until the target has a HEAD), and from then on the target's owner-qualified refs keep the source's chunks live, so deleting the source snapshot or volume mid-restore is normal. The background walker (`HydrateAll`) makes every chunk local through the shared fill flights, under one host fill permit per flight. Bounded batch cuts then upload the chunks under the target's own keys; when the resolved HEAD holds no ref to another volume, the write-once `RESTORE-INDEPENDENT` entry is created (`MarkIndependent`). Snapshots of the target are refused until then, and a snapshot image that still names another volume's chunks is refused even after it. An aborted first HEAD keeps the parent snapshot as `fork_parent` until the target is deleted. Model: `docs/spec/RestoreIndependence.tla`. - **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; a snapshot with a live fork claim is always kept; deletion uses the same conditional mark as `DeleteSnapshot`. - **GC** (`gc.go` `Collector.run`, operator-driven through `sw-block ops chunk gc`, preview by default; see also `core/frontend/chunkstore/GC.md`): - roots: every HEAD, every named snapshot (including one whose delete is still in progress), every snapshot attempt that is not aborted, live intents, and segment objects; an unreadable segment aborts the mark. A deleted snapshot's attempt stays a root for one grace period after its delete time, then stops counting (`Collector.snapshotAttemptHeads` in `gc_copy.go`); @@ -205,7 +206,7 @@ HEAD states: ```mermaid stateDiagram-v2 - [*] --> active: initial HEAD (gen 1, epoch 0) or fork HEAD + [*] --> active: initial HEAD (gen 1, epoch 0), fork or restore HEAD active --> active: holder's cut CAS (gen+1) active --> detached: Detach final cut detached --> active: takeover CAS (higher epoch, new holder) @@ -235,6 +236,21 @@ stateDiagram-v2 The attempt path is never removed, so a late create can never land after a delete. +Restore (target volume): + +```mermaid +stateDiagram-v2 + [*] --> Claimed: claim parent snapshot, write VOLUME (origin restore) + Claimed --> Restoring: first HEAD (parent's refs, owner-qualified); claim dropped + Claimed --> Aborted: GC tombstones the HEAD (parent kept as fork_parent) + Restoring --> Restoring: walker fills; batch cut replaces foreign refs with own keys + Restoring --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created + Independent --> [*] + Aborted --> [*]: target deleted +``` + +Snapshots of the target are refused in `Claimed` and `Restoring`. + ## 7. Lease, takeover and host moves **Host guard** (`core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard`, enabled with `blockvolume --workspace-lease`; see [workspace lease](../workspace-lease.md)): frontend I/O and cuts are admitted only with a granted, unexpired lease for the exact `{volume, replica, epoch}`. Validity is anchored to the renewal request's start time, and blockmaster's `ValidForNs` already subtracts half the clock-skew bound (`core/host/master/workspace_service.go` `leaseFact`). A late reply cannot extend admission. A fenced guard never reopens. The lease is 30 s (`core/authority/authority.go`, `workspaceTTL`); the skew bound defaults to 20 s (`blockmaster --workspace-max-clock-skew`). diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index aa90753dcb..7c0e2cb485 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -197,6 +197,7 @@ stateDiagram-v2 | Holder | HolderFenced | a conflicting HEAD owner (including a regressed epoch) or a displaced publication is observed; local data and unresolved cut intents remain | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | | Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | +| Holder | (background hydrate) | an independent restore's walker fills every HEAD-named absent chunk through the same shared fill flights (never a second fetch, never over a local write); it yields while any flight has guest waiters, takes one host fill permit per flight (no cut payload, class `BackgroundFill` from the caller) and the permit is released only when that flight's I/O is over, also when the walker returns early on cancel, revocation or close | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill`; `core/storage/chunk_hydration.go` `hydrationFlightLocked` | `INV-RESTORE-HYDRATE-001`, `INV-CUT-READMISS-001` | ### M5 The cut pipeline @@ -266,7 +267,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | +| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork or restore HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork`, `Restore` | `INV-WS-HEAD-CAS-001` | | `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | | `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | @@ -285,6 +286,9 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | +| published | restore | the fork steps with `VOLUME` origin `restore`: the claim is live until the target has a HEAD (the fork's semantics); after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-RESTORE-PARENT-HOLD-001` | +| restore | independent | the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs` | `INV-RESTORE-INDEPENDENT-001` | +| restore (not independent) | name held | refused: `CreateSnapshot` on a restore volume needs the marker, and the supplied image itself must hold no foreign ref; a refused request leaves no name or attempt | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-RESTORE-SNAPSHOT-001` | **Intents and key bindings.** @@ -519,7 +523,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | -| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | +| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. An owner-qualified ref roots the owner's key (load-bearing for forks and restores: a target's HEAD keeps the source's chunks live after the source snapshot and volume are gone). | M6 key: Bound → Tombstoned; M6 snapshot: published → fork \| restore | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`); `TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone` (`core/frontend/chunkstore/restore_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete`; `RestoreIndependence` `NoGap` (simulation) | ACTIVE | | `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | | `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | | `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | @@ -527,6 +531,10 @@ Notes: | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | +| `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` (simulation) | ACTIVE | +| `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`red_snap_during_restore`) | ACTIVE | +| `INV-RESTORE-PARENT-HOLD-001` | A restore target with an aborted first HEAD no longer has a live fork claim (any HEAD ends the claim), but retention still keeps the parent snapshot as `fork_parent` (the fork-record scan treats an aborted HEAD as no HEAD) until the target volume is deleted. | M6 snapshot: published (parent of an aborted restore) | `core/frontend/chunkstore/retention.go` `liveClaims`, `forkParentsNeeded` | `TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `ClaimUntilHead_Inv` (simulation) | ACTIVE | +| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | Notes: diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 0fb0a0bd28..c4381751e8 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -98,6 +98,7 @@ Two kinds of config are **expected to violate**: | `ReplicationFailover.tla` | `cfg/S6_*` | design-level | | `RetentionGCTiming.tla` | `cfg/S9_*` | | | `RetentionGCMulti.tla` | `cfg/S9b_*` | | +| `RestoreIndependence.tla` | `cfg/RestoreIndependence_*` | independent restore; simulation only so far | Each `.cfg` names its spec on its first line. @@ -116,6 +117,7 @@ length of TLC's shortest counterexample. | S5 | `ControlPlane` | Blockmaster authority store: one volume record `{epoch, holder, move journal}`, two retried move requests, durable Puts that succeed, fail, or land with the reply lost, and restarts. | `UniqueEpoch` (issued epochs strictly increase), `Idempotent` (one epoch per request id), `JournalComplete` | `S5_code` pass (298). **RED:** `S5_red_noUncertain` UniqueEpoch violated (5-step: a lost-reply Put, then a reservation from stale memory puts the old assignment back). `S5_red_noReserve` passes (the reservation step is not needed for these invariants). | `core/authority/authority.go:436` applyWithWorkspaceMove (uncertain refusal `:442-444`, Put `:564`, mark uncertain `:568`); `core/authority/workspace.go:309` prepareWorkspaceMoveLocked (expected line `:313`, resume a reserved entry `:324-333`, reserve max+1 `:344-355`), journal replay `:192-219`, persist and mark uncertain `:276-288` | | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | +| S10 | `RestoreIndependence` | Independent restore: claim, two-step fork, hydrate, bounded batch cuts (own keys uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref, claim drop; GC, source snapshot and volume delete, snapshot retention, and crashes with resume from remote facts at any point. `ClaimUntilHead` selects today's fork claim (dropped at the first HEAD); the strict variant keeps the claim until independent. | `NoGap` (the target's chunks are always rooted), `Independent`, `NoForeignList`, `ClaimUntilHead_Inv`, `LifecycleFree`, `StateRemote` | **Simulation only (proves nothing; not exhausted)**, 3 seeds x 60,000 traces, depth 40: `safe` (NIdx 3, Batch 1) no violation in about 812k states; `safe_b2` about 888k; `safe_n4` about 1.22M; `strict_claim_until_independent` about 421k-844k. **RED** (each violated in simulation): `red_drop_claim_at_fork` ClaimUntilHead_Inv; `red_cas_before_upload`, `red_no_intent` NoGap; `red_marker_early`, `red_marker_before_cas`, `red_snap_during_restore` Independent; `red_list_foreign` NoForeignList; `red_resume_local` StateRemote; `red_retention_ignores_marker` LifecycleFree. **Witnesses reached:** `wit_done`, `wit_crash_resume`. An exhaustive run is pending. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `retention.go` `liveClaims`, `forkParentsNeeded`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAll`. Batch cuts and the restore driver are not merged yet. | ## Limits From 6d42d08b0f31535ac445972fdf02ed11ca611db1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:36:33 -0800 Subject: [PATCH 6/8] restore: public comments state guarantees only; walker test allows a deferral Comments in the restore code, tests and spec header now say what the code guarantees, without review or design-note references. The real-limiter walker test no longer asserts zero deferrals: a permit is released asynchronously (when its flight settles, then closed by the limiter), so the next admission can find every fill slot still closing; it now requires the limiter's skips to equal the walker's deferrals (flaked 4 of 90 runs on Linux before). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/frontend/chunkstore/catalog.go | 4 ++-- seaweed-block/core/frontend/chunkstore/restore_test.go | 8 ++++---- seaweed-block/core/storage/chunk_hydrate_all.go | 2 +- seaweed-block/core/storage/chunk_hydrate_all_test.go | 6 ++++-- seaweed-block/docs/spec/RestoreIndependence.tla | 4 ++-- 5 files changed, 13 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index a9d0553b6e..2fff8ee9ef 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -874,7 +874,7 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe if v.Origin == OriginRestore { // A restore is independent only once its marker exists: a snapshot // taken before would keep naming the source's chunks for its whole - // retention, so it is refused until then (DESIGN-r2 open question a). + // retention, so it is refused until then. if _, independent, err := c.ReadIndependence(ctx, vol); err != nil { return SnapshotInfo{}, err } else if !independent { @@ -1206,7 +1206,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) // with Origin restore. The target serves at once (lazy fill); the restore // driver then hydrates every chunk, re-uploads the qualified ones under the // target's own keys in bounded batch cuts, and MarkIndependent records the -// end of the lineage once HEAD holds no qualified ref (DESIGN-r2, O-REC-2). +// end of the lineage once HEAD holds no ref to another volume. func (c *Catalog) Restore(ctx context.Context, req ForkRequest) (ForkResult, error) { return c.fork(ctx, req, OriginRestore) } diff --git a/seaweed-block/core/frontend/chunkstore/restore_test.go b/seaweed-block/core/frontend/chunkstore/restore_test.go index 6959ac850b..f94095ef68 100644 --- a/seaweed-block/core/frontend/chunkstore/restore_test.go +++ b/seaweed-block/core/frontend/chunkstore/restore_test.go @@ -154,7 +154,7 @@ func TestRestore_MarkIndependentOnlyWithoutQualifiedRefs(t *testing.T) { } } -// claude06 (verify side): deleting the source mid-restore is a normal state for every reader of T's fork record. +// Deleting the source mid-restore is a normal state for every reader of T's fork record. func TestRestore_SourceGoneIsNormal(t *testing.T) { f, b, c, _ := restoreFixture(t) ctx := context.Background() @@ -194,7 +194,7 @@ func TestRestore_SourceGoneIsNormal(t *testing.T) { } } -// claude05/claude06 load-bearing invariant for O-REC-2 option 1: after the restore's HEAD exists, the +// Load-bearing (the claim ends at the first HEAD): after the restore's HEAD exists, the // source snapshot and the source volume may both go; GC must keep every chunk T's HEAD names (qualified // refs resolve to the owner's bindings) until T's own batch cuts replace them. func TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone(t *testing.T) { @@ -237,7 +237,7 @@ func TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone(t *testing.T) { } } -// claude06 condition (3): a restore whose HEAD is absent or an aborted tombstone never attaches, like a fork. +// A restore whose HEAD is absent or an aborted tombstone never attaches, like a fork. func TestRestore_WithoutLiveHeadNeverAttaches(t *testing.T) { f, _, c, _ := catalogFixture(t) ctx := context.Background() @@ -264,7 +264,7 @@ func TestRestore_WithoutLiveHeadNeverAttaches(t *testing.T) { } } -// DESIGN-r2 open question (a), ruled: snapshots of a restore are refused until it is independent. +// Snapshots of a restore are refused until it is independent. func TestRestore_SnapshotsRefusedUntilIndependent(t *testing.T) { f, b, c, _ := restoreFixture(t) ctx := context.Background() diff --git a/seaweed-block/core/storage/chunk_hydrate_all.go b/seaweed-block/core/storage/chunk_hydrate_all.go index 01f9ad5ea2..5655491ec5 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all.go +++ b/seaweed-block/core/storage/chunk_hydrate_all.go @@ -28,7 +28,7 @@ var ( ) // HydrateAll makes every chunk local that HEAD names and the volume does not -// hold yet (an independent restore's background hydrate, O-REC-2). It walks +// hold yet (an independent restore's background hydrate). It walks // the absent chunks lowest index first through the same shared fill flights // as guest read misses (one fetch per chunk, the hydration queue bound and // the read-miss timeout apply), so it never fetches a chunk twice or races a diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go index b6bec6ebc5..5050c445d9 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all_test.go +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -298,7 +298,9 @@ func TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill(t *testing.T) { ctx, cancel := context.WithTimeout(bgFill(), ctLocalBound) defer cancel() p, err := layer.HydrateAll(ctx) - if err != nil || p.Remaining != 0 || p.Filled != ctNumBlocks/ctChunkBlocks || p.Deferred != 0 { + // A refusal is possible while an earlier permit is still being closed by + // the limiter; it is a deferral, and the limiter counts it as a skip. + if err != nil || p.Remaining != 0 || p.Filled != ctNumBlocks/ctChunkBlocks { t.Fatalf("hydrate all under the real limiter: %+v %v", p, err) } for b := uint32(0); b < ctNumBlocks; b++ { @@ -320,7 +322,7 @@ func TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill(t *testing.T) { rec.mu.Unlock() waitUntil(t, "every fill permit is admitted once and released", func() bool { st := lim.Snapshot().(hostlimit.Stats) - return st.Admitted == uint64(p.Filled) && st.Released == st.Admitted && st.Active == 0 && st.Skipped == 0 + return st.Admitted == uint64(p.Filled) && st.Released == st.Admitted && st.Active == 0 && st.Skipped == p.Deferred }) } diff --git a/seaweed-block/docs/spec/RestoreIndependence.tla b/seaweed-block/docs/spec/RestoreIndependence.tla index 0997891784..796850fe6a 100644 --- a/seaweed-block/docs/spec/RestoreIndependence.tla +++ b/seaweed-block/docs/spec/RestoreIndependence.tla @@ -1,7 +1,7 @@ ------------------------------ MODULE RestoreIndependence ------------------------------ (***************************************************************************) -(* Independent restore (O-REC-2): restore a snapshot into a volume that *) -(* ends up owning all its chunks, with no lineage to the source. *) +(* Independent restore: restore a snapshot into a volume that ends up *) +(* owning all its chunks, with no lineage to the source. *) (* Source volume V with HEAD and one sealed snapshot S; target T restored *) (* from S. T's HEAD maps indexes to fids; a fid is owned by V (a "@V/" *) (* ref) or by T. Steps: 0 claim S; 1 fork (T HEAD = S's fids, all V-owned) *) From dff8c712b3f5f5488c4aaa39c875e4214b245016 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:49:42 -0800 Subject: [PATCH 7/8] restore: bound the synchronous walker tests, join the dropIntent worker, ledger rows - Walker tests that call HydrateAll synchronously run under a ctLocalBound timeout, so a walker that never finishes fails instead of hanging. - The dropIntent test releases and joins its worker at cleanup (an unbounded delete, the failing case, no longer leaks a goroutine). - invariants.md: INV-RESTORE-PARENT-HOLD-001 is Go only (the model does not cover retention of an aborted target); new INV-CAT-INTENT-DROP-BOUNDED-001 row and M6 transition for the bounded catalog intent delete. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/restore_test.go | 24 +++++++++++++++---- .../core/storage/chunk_hydrate_all_test.go | 17 +++++++++---- seaweed-block/docs/design/invariants.md | 4 +++- 3 files changed, 35 insertions(+), 10 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/restore_test.go b/seaweed-block/core/frontend/chunkstore/restore_test.go index f94095ef68..347efc463a 100644 --- a/seaweed-block/core/frontend/chunkstore/restore_test.go +++ b/seaweed-block/core/frontend/chunkstore/restore_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "crypto/sha256" + "errors" "fmt" "path" "strings" @@ -292,18 +293,23 @@ func TestRestore_SnapshotsRefusedUntilIndependent(t *testing.T) { } } -// hangingDeleteFiler blocks DeleteEntry until its ctx ends and records whether -// that ctx carried a deadline. +// hangingDeleteFiler blocks DeleteEntry until its ctx ends (or the test +// releases it) and records whether that ctx carried a deadline. type hangingDeleteFiler struct { Filer hadDeadline chan bool + release chan struct{} } func (h hangingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { _, ok := ctx.Deadline() h.hadDeadline <- ok - <-ctx.Done() - return ctx.Err() + select { + case <-ctx.Done(): + return ctx.Err() + case <-h.release: + return errors.New("released by the test") + } } // dropIntent outlives a cancelled caller, but one unresponsive delete must still be bounded. @@ -311,11 +317,19 @@ func TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled(t *testing.T) { old := dropIntentTimeout dropIntentTimeout = 50 * time.Millisecond t.Cleanup(func() { dropIntentTimeout = old }) - h := hangingDeleteFiler{Filer: newFakeFiler(), hadDeadline: make(chan bool, 1)} + h := hangingDeleteFiler{Filer: newFakeFiler(), hadDeadline: make(chan bool, 1), release: make(chan struct{})} c := &Catalog{f: h} ctx, cancel := context.WithCancel(context.Background()) cancel() done := make(chan struct{}) + t.Cleanup(func() { // an unbounded delete (the failing case) is released and joined + close(h.release) + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("cleanup: dropIntent did not return") + } + }) go func() { c.dropIntent(ctx, "/vols/v1", "op-1"); close(done) }() select { case ok := <-h.hadDeadline: diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go index 5050c445d9..b184105503 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all_test.go +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -117,6 +117,15 @@ func (r *payloadRecorder) Admit(ctx context.Context, payload int64, abort func(e return r.Budget.Admit(ctx, payload, abort) } +// boundedCtx bounds a synchronous walk so that a walker that never finishes +// fails the test instead of hanging it. +func boundedCtx(t *testing.T, parent context.Context) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(parent, ctLocalBound) + t.Cleanup(cancel) + return ctx +} + func bgFill() context.Context { return hostlimit.WithClass(context.Background(), hostlimit.BackgroundFill) } @@ -124,7 +133,7 @@ func bgFill() context.Context { func TestHydrateAll_FillsEveryChunkOnceAndReadsTheHeadImage(t *testing.T) { fastWalker(t) s, layer, remote, _ := hydrationFixture(t, 2, 64) - ctx := context.Background() + ctx := boundedCtx(t, context.Background()) p, err := layer.HydrateAll(ctx) if err != nil || p.Remaining != 0 || p.Filled != ctNumBlocks/ctChunkBlocks { t.Fatalf("hydrate all: %+v %v, want %d filled, 0 remaining", p, err, ctNumBlocks/ctChunkBlocks) @@ -161,7 +170,7 @@ func TestHydrateAll_NeverOverwritesALocalWrite(t *testing.T) { if _, err := s.Write(ctChunkBlocks+1, makeBlock(ctBlockSize, 0xEF)); err != nil { // one block of chunk 1 t.Fatal(err) } - p, err := layer.HydrateAll(context.Background()) + p, err := layer.HydrateAll(boundedCtx(t, context.Background())) if err != nil || p.Remaining != 0 { t.Fatalf("hydrate all: %+v %v", p, err) } @@ -255,7 +264,7 @@ func TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass(t *testin _, layer, _, _ := hydrationFixture(t, 2, 64) budget := &walkerBudget{refuse: 2} layer.cfg.Budget = budget - ctx := context.WithValue(context.Background(), walkerClassKey{}, "fill") + ctx := boundedCtx(t, context.WithValue(context.Background(), walkerClassKey{}, "fill")) p, err := layer.HydrateAll(ctx) if err != nil || p.Remaining != 0 || p.Deferred != 2 { t.Fatalf("hydrate all: %+v %v, want 2 deferred then everything filled", p, err) @@ -390,7 +399,7 @@ func TestHydrateAll_StatsReportAbsentChunks(t *testing.T) { if n := layer.Stats().AbsentChunks; n != ctNumBlocks/ctChunkBlocks { t.Fatalf("absent before the walk: %d, want %d", n, ctNumBlocks/ctChunkBlocks) } - if _, err := layer.HydrateAll(context.Background()); err != nil { + if _, err := layer.HydrateAll(boundedCtx(t, context.Background())); err != nil { t.Fatal(err) } if n := layer.Stats().AbsentChunks; n != 0 { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7c0e2cb485..8dd9bd5a26 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -296,6 +296,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th |---|---|---|---|---| | — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | | intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | +| intent live | removed (catalog) | the operation's create is confirmed or can never apply; the delete outlives the caller's cancellation but is bounded by `dropIntentTimeout` | `core/frontend/chunkstore/catalog.go` `dropIntent` | `INV-CAT-INTENT-DROP-BOUNDED-001` | | intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | | — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | | bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` | @@ -533,8 +534,9 @@ Notes: | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | | `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` (simulation) | ACTIVE | | `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`red_snap_during_restore`) | ACTIVE | -| `INV-RESTORE-PARENT-HOLD-001` | A restore target with an aborted first HEAD no longer has a live fork claim (any HEAD ends the claim), but retention still keeps the parent snapshot as `fork_parent` (the fork-record scan treats an aborted HEAD as no HEAD) until the target volume is deleted. | M6 snapshot: published (parent of an aborted restore) | `core/frontend/chunkstore/retention.go` `liveClaims`, `forkParentsNeeded` | `TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `ClaimUntilHead_Inv` (simulation) | ACTIVE | +| `INV-RESTORE-PARENT-HOLD-001` | A restore target with an aborted first HEAD no longer has a live fork claim (any HEAD ends the claim), but retention still keeps the parent snapshot as `fork_parent` (the fork-record scan treats an aborted HEAD as no HEAD) until the target volume is deleted. | M6 snapshot: published (parent of an aborted restore) | `core/frontend/chunkstore/retention.go` `liveClaims`, `forkParentsNeeded` | `TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted` (`core/frontend/chunkstore/restore_test.go`) | — (Go only: the model's `ClaimUntilHead` does not cover retention of an aborted target) | ACTIVE | | `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | +| `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE | Notes: From 24bc9ecfdeaa695a960c12a758b932cf085467b8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:59:05 -0800 Subject: [PATCH 8/8] chunkstore: dropIntent test asserts a live, self-bounded delete context The test now checks that the context the filer receives is live on entry (it does not inherit the caller's cancellation) and ends with its own deadline (context.DeadlineExceeded), not Canceled. Release and bounded join at cleanup are kept. Mutants: inheriting the cancelled parent fails on entry; no deadline fails on the deadline check. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/restore_test.go | 33 +++++++++++++++---- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/restore_test.go b/seaweed-block/core/frontend/chunkstore/restore_test.go index 347efc463a..25588987c4 100644 --- a/seaweed-block/core/frontend/chunkstore/restore_test.go +++ b/seaweed-block/core/frontend/chunkstore/restore_test.go @@ -294,18 +294,26 @@ func TestRestore_SnapshotsRefusedUntilIndependent(t *testing.T) { } // hangingDeleteFiler blocks DeleteEntry until its ctx ends (or the test -// releases it) and records whether that ctx carried a deadline. +// releases it). It reports whether that ctx carried a deadline and was live on +// entry, then how it ended. type hangingDeleteFiler struct { Filer - hadDeadline chan bool - release chan struct{} + entered chan deleteEntry + ended chan error + release chan struct{} +} + +type deleteEntry struct { + hadDeadline bool + errAtEntry error } func (h hangingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { _, ok := ctx.Deadline() - h.hadDeadline <- ok + h.entered <- deleteEntry{hadDeadline: ok, errAtEntry: ctx.Err()} select { case <-ctx.Done(): + h.ended <- ctx.Err() return ctx.Err() case <-h.release: return errors.New("released by the test") @@ -317,7 +325,7 @@ func TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled(t *testing.T) { old := dropIntentTimeout dropIntentTimeout = 50 * time.Millisecond t.Cleanup(func() { dropIntentTimeout = old }) - h := hangingDeleteFiler{Filer: newFakeFiler(), hadDeadline: make(chan bool, 1), release: make(chan struct{})} + h := hangingDeleteFiler{Filer: newFakeFiler(), entered: make(chan deleteEntry, 1), ended: make(chan error, 1), release: make(chan struct{})} c := &Catalog{f: h} ctx, cancel := context.WithCancel(context.Background()) cancel() @@ -332,14 +340,25 @@ func TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled(t *testing.T) { }) go func() { c.dropIntent(ctx, "/vols/v1", "op-1"); close(done) }() select { - case ok := <-h.hadDeadline: - if !ok { + case e := <-h.entered: + if e.errAtEntry != nil { + t.Fatalf("the intent delete inherited the caller's cancellation: %v", e.errAtEntry) + } + if !e.hadDeadline { t.Fatal("the intent delete ran without any deadline") } case <-time.After(5 * time.Second): t.Fatal("dropIntent never reached the filer") } select { + case err := <-h.ended: + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("the intent delete ended with %v, want its own deadline (context.DeadlineExceeded)", err) + } + case <-time.After(5 * time.Second): + t.Fatal("the intent delete never ended: it is unbounded") + } + select { case <-done: case <-time.After(5 * time.Second): t.Fatal("dropIntent did not return: the delete is unbounded")