From 29c81a1dca5cf7db39bc59a0e6ee0bf44e88b139 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:23:16 -0800 Subject: [PATCH 1/9] storage: OwnBatch bounded re-own cut and a byte-paced walker (restore part B) OwnBatch(n, foreign) runs one ordinary cut whose candidates include up to n local chunks whose HEAD keys name another volume; streamCutPayloads uploads each under a new own key even when its bytes equal HEAD's, and the cut's one intent and HEAD CAS publish them (M6.Restore.Owning>Owning). An absent chunk is never fetched by a batch; with nothing to own no cut runs. HydrateAllAt paces the walker to a byte rate before admission (HydrateAll = unpaced). Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_cut_payload.go | 2 +- .../core/storage/chunk_hydrate_all.go | 25 +++++ .../core/storage/chunk_hydrate_all_test.go | 17 ++++ seaweed-block/core/storage/chunk_layer.go | 12 ++- seaweed-block/core/storage/chunk_own.go | 96 +++++++++++++++++++ seaweed-block/core/storage/chunk_own_test.go | 96 +++++++++++++++++++ 6 files changed, 246 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_own.go create mode 100644 seaweed-block/core/storage/chunk_own_test.go diff --git a/seaweed-block/core/storage/chunk_cut_payload.go b/seaweed-block/core/storage/chunk_cut_payload.go index 3cac8535be..6e66f07433 100644 --- a/seaweed-block/core/storage/chunk_cut_payload.go +++ b/seaweed-block/core/storage/chunk_cut_payload.go @@ -58,7 +58,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, return err } ref, had := head.Chunks[c.idx] - if !c.zero && !(had && ref.SHA256 == c.sum) { + if !c.zero && !(had && ref.SHA256 == c.sum && !l.owning(c.idx)) { c.key, c.size = keys[i], len(c.data) once.Do(func() { intent, intentErr = l.remote.PutIntent(ctx, chunkIntent{Gen: head.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys}) diff --git a/seaweed-block/core/storage/chunk_hydrate_all.go b/seaweed-block/core/storage/chunk_hydrate_all.go index 5655491ec5..17fae0e4b3 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all.go +++ b/seaweed-block/core/storage/chunk_hydrate_all.go @@ -47,7 +47,16 @@ var ( // 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) { + return l.HydrateAllAt(ctx, 0) +} + +// HydrateAllAt is HydrateAll paced to at most bytesPerSecond of fill payload +// (one chunk per fill), counted from its start; 0 means unpaced. The pace +// applies before admission, so a paced walker holds no permit while it waits. +func (l *chunkLayerImpl) HydrateAllAt(ctx context.Context, bytesPerSecond int64) (HydrateProgress, error) { var p HydrateProgress + start := time.Now() + started := int64(0) // fills started, for the pace walk, stop := context.WithCancelCause(ctx) defer stop(nil) backoff := hydrateAllMinBackoff @@ -89,6 +98,21 @@ func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error } continue } + if bytesPerSecond > 0 && started > 0 { + due := start.Add(time.Duration(float64(started*int64(l.chunkBlocks)*int64(l.blockSize)) / float64(bytesPerSecond) * float64(time.Second))) + if d := time.Until(due); d > 0 { + t := time.NewTimer(d) + select { + case <-t.C: + case <-walk.Done(): + t.Stop() + return quit(context.Cause(walk)) + case <-l.ctx.Done(): + t.Stop() + return quit(errChunkLayerClosed) + } + } + } release, err := l.admitFill(walk, stop) if err != nil { p.Deferred++ @@ -110,6 +134,7 @@ func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error if f == nil { continue // resolved meanwhile } + started++ select { case <-f.done: case <-walk.Done(): diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go index b184105503..34e981ea67 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all_test.go +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -406,3 +406,20 @@ func TestHydrateAll_StatsReportAbsentChunks(t *testing.T) { t.Fatalf("absent after the walk: %d, want 0", n) } } + +// The walker's byte pace bounds the fill rate: 8 chunks at 4 chunks/s take +// at least (8-1)/4 s. +func TestHydrateAll_PacedByByteRate(t *testing.T) { + fastWalker(t) + _, layer, _, _ := hydrationFixture(t, 2, 64) + rate := int64(4 * ctChunkBytes) + start := time.Now() + p, err := layer.HydrateAllAt(boundedCtx(t, context.Background()), rate) + took := time.Since(start) + if err != nil || p.Remaining != 0 { + t.Fatalf("paced walk: %+v %v", p, err) + } + if min := time.Duration(p.Filled-1) * time.Second / 4; took < min { + t.Fatalf("%d fills at %d B/s took %v, want at least %v", p.Filled, rate, took, min) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 3ed9ec97b5..f98da1e83f 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -116,6 +116,9 @@ type chunkLayerImpl struct { dirty map[uint64]bool // chunks dirtied since the cut in progress or the last HEAD inflight map[uint64]bool // chunks captured by a cut whose HEAD is not yet installed allDirty bool // a BASE block landed: every chunk is dirty + // own names the chunks OwnBatch re-uploads under this layer's own keys in + // the cut it runs (set and cleared under capMu, read under stMu). + own map[uint64]bool cutLSN uint64 // H of the latest cut taken (in flight or installed) // chunkMut counts the mutations of each chunk: every dirty-map insert @@ -850,6 +853,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch candidates[i] = true } } + for idx := range l.own { + if !l.absent[idx] { // a re-own reads the local copy, never fetches + candidates[idx] = true + } + } // A staged chunk stands for the barrier copy while no write reached // it since staging (its version is unchanged) and HEAD is the one it // was compared against. @@ -973,7 +981,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch c.birth = births[c.idx] ref, had := baseHead.Chunks[c.idx] switch { - case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum: + case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum && c.key == "": + // A chunk equal to HEAD is skipped unless streamCutPayloads + // uploaded it under a new key: a re-owned chunk (OwnBatch). st.UnchangedChunks++ continue case c.zero: diff --git a/seaweed-block/core/storage/chunk_own.go b/seaweed-block/core/storage/chunk_own.go new file mode 100644 index 0000000000..e86ebd408a --- /dev/null +++ b/seaweed-block/core/storage/chunk_own.go @@ -0,0 +1,96 @@ +package storage + +import ( + "context" + "sort" +) + +// OwnProgress reports one OwnBatch call. +// - Owned: foreign chunks this call's cut re-uploaded under own keys. +// - Remaining: chunks HEAD still names with a foreign key after the call. +// - NotLocal: of those, chunks not local yet (the hydrate walker fills them). +type OwnProgress struct { + Owned int + Remaining int + NotLocal int +} + +// OwnBatch runs one bounded cut (M6.Restore.Owning>Owning): it picks up to n +// chunks, lowest index first, whose HEAD key is foreign (foreign reports +// whether a key names another volume's object) and that are local, and cuts +// with them as candidates: each is uploaded under a new own key under the +// cut's intent and published by the cut's one HEAD CAS, even when its bytes +// equal HEAD's. Absent chunks are skipped (never fetched by the cut). The cut +// is an ordinary cut, so guest writes since the last HEAD go with it. With +// nothing to own it runs no cut. A failed cut leaves HEAD as it was; the next +// call picks again from the current HEAD. +func (l *chunkLayerImpl) OwnBatch(ctx context.Context, n int, foreign func(key string) bool) (OwnProgress, error) { + l.capMu.Lock() + defer l.capMu.Unlock() + l.stMu.Lock() + var picked []uint64 + for _, idx := range sortedForeign(l.head.Chunks, foreign) { + if len(picked) < n && !l.absent[idx] { + picked = append(picked, idx) + } + } + if len(picked) == 0 { + p := l.ownProgressLocked(foreign) + l.stMu.Unlock() + return p.OwnProgress, nil + } + l.own = make(map[uint64]bool, len(picked)) + for _, idx := range picked { + l.own[idx] = true + } + l.stMu.Unlock() + _, err := l.captureLocked(ctx, false) + l.stMu.Lock() + l.own = nil + p := l.ownProgressLocked(foreign) + l.stMu.Unlock() + if err == nil { + for _, idx := range picked { + if ref, ok := p.head[idx]; !ok || !foreign(ref.Key) { + p.Owned++ + } + } + } + return p.OwnProgress, err +} + +type ownCount struct { + OwnProgress + head map[uint64]chunkRef +} + +// ownProgressLocked counts HEAD's foreign chunks. Caller holds stMu. +func (l *chunkLayerImpl) ownProgressLocked(foreign func(string) bool) ownCount { + c := ownCount{head: l.head.Chunks} + for _, idx := range sortedForeign(l.head.Chunks, foreign) { + c.Remaining++ + if l.absent[idx] { + c.NotLocal++ + } + } + return c +} + +func sortedForeign(chunks map[uint64]chunkRef, foreign func(string) bool) []uint64 { + var out []uint64 + for idx, ref := range chunks { + if foreign(ref.Key) { + out = append(out, idx) + } + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// owning reports whether chunk idx is re-owned by the running OwnBatch cut: +// it is uploaded under a new own key even when its bytes equal HEAD's. +func (l *chunkLayerImpl) owning(idx uint64) bool { + l.stMu.Lock() + defer l.stMu.Unlock() + return l.own[idx] +} diff --git a/seaweed-block/core/storage/chunk_own_test.go b/seaweed-block/core/storage/chunk_own_test.go new file mode 100644 index 0000000000..fa986a0df5 --- /dev/null +++ b/seaweed-block/core/storage/chunk_own_test.go @@ -0,0 +1,96 @@ +package storage + +import ( + "bytes" + "context" + "strings" + "testing" +) + +func seedForeign(key string) bool { return strings.HasPrefix(key, "seed/") } + +func ownCtx(t *testing.T) context.Context { return boundedCtx(t, context.Background()) } + +// M6.Restore.Owning>Owning: each batch is one cut that re-uploads at most n +// foreign chunks under own keys, the image unchanged, until none is left. +func TestOwnBatch_BoundedBatchesReplaceEveryForeignKey(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + before := remote.stats() + want := remote.imageOf(t, before.head) + if p, err := layer.HydrateAll(ownCtx(t)); err != nil || p.Remaining != 0 { + t.Fatalf("hydrate: %+v %v", p, err) + } + total := ctNumBlocks / ctChunkBlocks + left := total + for left > 0 { + puts := remote.stats().puts + cas := remote.stats().cas + p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign) + if err != nil { + t.Fatal(err) + } + step := min(3, left) + if p.Owned != step || p.Remaining != left-step || p.NotLocal != 0 { + t.Fatalf("batch: %+v, want %d owned and %d remaining", p, step, left-step) + } + if got := remote.stats().puts - puts; got != step { + t.Fatalf("batch uploaded %d chunks, want exactly %d (bounded)", got, step) + } + if got := remote.stats().cas - cas; got != 1 { + t.Fatalf("batch made %d HEAD CAS, want one", got) + } + left -= step + } + after := remote.stats().head + for idx, ref := range after.Chunks { + if seedForeign(ref.Key) { + t.Fatalf("chunk %d still foreign after the last batch: %s", idx, ref.Key) + } + } + if !bytes.Equal(remote.imageOf(t, after), want) { + t.Fatal("owning changed the volume image") + } + cas := remote.stats().cas + if p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign); err != nil || p != (OwnProgress{}) || remote.stats().cas != cas { + t.Fatalf("nothing left to own must run no cut: %+v %v", p, err) + } +} + +// A chunk not local yet is never fetched by a batch: it waits for the walker. +func TestOwnBatch_SkipsChunksNotLocal(t *testing.T) { + _, layer, remote, _ := hydrationFixture(t, 2, 64) + before := remote.stats() + p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign) + total := ctNumBlocks / ctChunkBlocks + if err != nil || p.Owned != 0 || p.Remaining != total || p.NotLocal != total { + t.Fatalf("batch before any hydration: %+v %v", p, err) + } + after := remote.stats() + if after.cas != before.cas || after.gets != before.gets { + t.Fatalf("a batch with nothing local cut or fetched: cas %d->%d gets %d->%d", before.cas, after.cas, before.gets, after.gets) + } +} + +// A batch is an ordinary cut: a guest write since the last HEAD goes with it. +func TestOwnBatch_CarriesGuestWrites(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + if _, err := layer.HydrateAll(ownCtx(t)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(ctChunkBlocks*6+1, makeBlock(ctBlockSize, 0xAB)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := layer.OwnBatch(ownCtx(t), 2, seedForeign); err != nil { + t.Fatal(err) + } + img := remote.imageOf(t, remote.stats().head) + off := (ctChunkBlocks*6 + 1) * ctBlockSize + if !bytes.Equal(img[off:off+ctBlockSize], makeBlock(ctBlockSize, 0xAB)) { + t.Fatal("the guest write did not reach HEAD with the batch") + } +} From 8a886ff6da58ef7b255022f02898a089ddce3bed Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:23:16 -0800 Subject: [PATCH 2/9] restore: driver, /chunk/restore and sw-block ops chunk restore (part B) The driver walks (64 MiB/s, BackgroundFill), cuts bounded batches (64 chunks) until no foreign ref is left, then writes RESTORE-INDEPENDENT (M6.Restore Restoring>Hydrating>Owning>Owning>Independent). It decides only from the target's VOLUME, HEAD and marker, so a rerun resumes from the remote state and a deleted source is a normal state. POST /chunk/restore starts or joins one background run per volume and returns its status; GET (or statusOnly) reports it; sw-block ops chunk restore calls it. Docs: M6 restore rows, INV-RESTORE-OWN-BATCH-001 and INV-RESTORE-DRIVER-001, the restore quantities, the workspace design diagram. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk.go | 4 +- seaweed-block/cmd/sw-block/chunk_restore.go | 30 ++ .../cmd/sw-block/chunk_restore_test.go | 39 +++ .../core/frontend/durable/provider_restore.go | 51 ++++ .../core/host/volume/chunk_control.go | 6 +- .../core/host/volume/chunk_restore.go | 234 ++++++++++++++ .../core/host/volume/chunk_restore_test.go | 287 ++++++++++++++++++ .../docs/design/agent-workspace-design.md | 8 +- seaweed-block/docs/design/invariants.md | 12 +- 9 files changed, 662 insertions(+), 9 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/chunk_restore.go create mode 100644 seaweed-block/cmd/sw-block/chunk_restore_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_restore.go create mode 100644 seaweed-block/core/host/volume/chunk_restore.go create mode 100644 seaweed-block/core/host/volume/chunk_restore_test.go diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 80cc5f67ad..9b604371f0 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -44,7 +44,7 @@ var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { func runOpsChunk(args []string, stdout, stderr io.Writer) int { if len(args) == 0 { - return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|volume-delete", false) + return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|volume-delete|restore", false) } switch args[0] { case "gc": @@ -69,6 +69,8 @@ func runOpsChunk(args []string, stdout, stderr io.Writer) int { return chunkRetain(args[1:], stdout, stderr) case "volume-delete": return chunkVolumeDelete(args[1:], stdout, stderr) + case "restore": + return chunkRestore(args[1:], stdout, stderr) default: return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, fmt.Sprintf("unknown subcommand %q", args[0]), false) } diff --git a/seaweed-block/cmd/sw-block/chunk_restore.go b/seaweed-block/cmd/sw-block/chunk_restore.go new file mode 100644 index 0000000000..4a94e2f456 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_restore.go @@ -0,0 +1,30 @@ +package main + +import ( + "io" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// chunkRestore starts (or joins) the independent-restore driver of a volume +// restored from a snapshot and prints its status; with --status it only +// prints the status. The driver runs in blockvolume and outlives this call. +func chunkRestore(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("restore", stderr) + var ( + volumeID, statusAddr string + statusOnly bool + ) + fs.StringVar(&volumeID, "volume", "", "restored volume id") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") + fs.BoolVar(&statusOnly, "status", false, "print the restore status without starting a run") + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if volumeID == "" || statusAddr == "" { + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false) + } + body := map[string]any{"volumeID": volumeID, "statusOnly": statusOnly} + return chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr) +} diff --git a/seaweed-block/cmd/sw-block/chunk_restore_test.go b/seaweed-block/cmd/sw-block/chunk_restore_test.go new file mode 100644 index 0000000000..2c9c32f1c2 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_restore_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestOpsChunk_RestoreStartsAndReportsStatus(t *testing.T) { + var got []map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/chunk/restore" || r.Method != http.MethodPost { + http.Error(w, "unexpected "+r.Method+" "+r.URL.Path, http.StatusNotFound) + return + } + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + got = append(got, body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"volumeID":"v2","phase":"owning","running":true,"foreign":3}`)) + })) + defer srv.Close() + for _, args := range [][]string{{"restore", "--volume", "v2", "--status-addr", srv.URL}, {"restore", "--volume", "v2", "--status-addr", srv.URL, "--status"}} { + var out, errb bytes.Buffer + if code := runOpsChunk(args, &out, &errb); code != 0 || !strings.Contains(out.String(), `"phase":"owning"`) { + t.Fatalf("%v: exit %d out %q err %q", args, code, out.String(), errb.String()) + } + } + if len(got) != 2 || got[0]["volumeID"] != "v2" || got[0]["statusOnly"] != false || got[1]["statusOnly"] != true { + t.Fatalf("requests %v: want a start, then a status-only call", got) + } + var out, errb bytes.Buffer + if code := runOpsChunk([]string{"restore", "--status-addr", srv.URL}, &out, &errb); code == 0 { + t.Fatal("restore without --volume must be refused") + } +} diff --git a/seaweed-block/core/frontend/durable/provider_restore.go b/seaweed-block/core/frontend/durable/provider_restore.go new file mode 100644 index 0000000000..fde0c680aa --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_restore.go @@ -0,0 +1,51 @@ +package durable + +import ( + "context" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// chunkRestorer is the chunk layer's independent-restore surface. +type chunkRestorer interface { + HydrateAllAt(ctx context.Context, bytesPerSecond int64) (storage.HydrateProgress, error) + OwnBatch(ctx context.Context, n int, foreign func(key string) bool) (storage.OwnProgress, error) +} + +func (p *DurableProvider) restorer(volumeID string) (chunkRestorer, error) { + _, layer, err := p.chunkHandle(volumeID) + if err != nil { + return nil, err + } + r, ok := layer.(chunkRestorer) + if !ok { + return nil, fmt.Errorf("durable: volume %s: chunk layer has no restore surface: %w", volumeID, ErrNotChunkVolume) + } + return r, nil +} + +// HydrateVolume makes every HEAD-named absent chunk of volumeID local +// (M6.Restore.Restoring>Hydrating), paced to bytesPerSecond, under the +// host limiter's BackgroundFill class. +func (p *DurableProvider) HydrateVolume(ctx context.Context, volumeID string, bytesPerSecond int64) (storage.HydrateProgress, error) { + r, err := p.restorer(volumeID) + if err != nil { + return storage.HydrateProgress{}, err + } + return r.HydrateAllAt(hostlimit.WithClass(ctx, hostlimit.BackgroundFill), bytesPerSecond) +} + +// OwnVolumeBatch runs one bounded cut of volumeID that re-uploads up to n +// local chunks with foreign HEAD keys under own keys +// (M6.Restore.Owning>Owning). +func (p *DurableProvider) OwnVolumeBatch(ctx context.Context, volumeID string, n int, foreign func(string) bool) (storage.OwnProgress, error) { + r, err := p.restorer(volumeID) + if err != nil { + return storage.OwnProgress{}, err + } + ctx, cancel := p.chunkCutContext(ctx) + defer cancel() + return r.OwnBatch(ctx, n, foreign) +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c1e4029609..ab9dfb6499 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -231,6 +231,7 @@ func (s *StatusServer) chunkMux() http.Handler { mux.HandleFunc("/chunk/snapshots", s.handleChunkSnapshots) mux.HandleFunc("/chunk/snapshot/delete", s.handleChunkSnapshotDelete) mux.HandleFunc("/chunk/detach", s.handleChunkDetach) + mux.HandleFunc("/chunk/restore", s.handleChunkRestore) // Any other /chunk path: a typed JSON 404, like every other /chunk // error, not net/http's plain-text page. mux.HandleFunc("/chunk/", func(w http.ResponseWriter, r *http.Request) { @@ -589,8 +590,9 @@ type ChunkProvider interface { var errFrozenDetachUnsupported = errors.New("frozen detach unsupported by provider") type chunkControl struct { - p ChunkProvider - cat *chunkstore.Catalog + p ChunkProvider + cat *chunkstore.Catalog + restores restoreRuns } // NewChunkControl serves the routes from a durable provider (cut, detach) diff --git a/seaweed-block/core/host/volume/chunk_restore.go b/seaweed-block/core/host/volume/chunk_restore.go new file mode 100644 index 0000000000..eb334788df --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_restore.go @@ -0,0 +1,234 @@ +package volume + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "sync" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Independent restore driver (M6.Restore). A restored volume serves at once; +// the driver then makes every chunk local (Restoring>Hydrating), re-uploads +// the chunks whose HEAD keys name another volume under the volume's own keys +// in bounded batch cuts (Hydrating>Owning, Owning>Owning; the walker and the +// batches may overlap), and writes the independence marker once HEAD holds +// no foreign ref (Owning>Independent). Every decision is read from the +// target's own facts (its VOLUME, HEAD and marker), never from the source, so +// a rerun after a crash resumes where the remote state is, and a deleted +// source snapshot or volume is a normal state. + +// Restore quantities (invariants.md Part E). +const ( + DefaultRestoreBatchChunks = 64 + DefaultRestoreBytesPerSecond = 64 << 20 +) + +// RestoreProvider is the chunk layer's restore surface for an attached volume. +type RestoreProvider interface { + HydrateVolume(ctx context.Context, volumeID string, bytesPerSecond int64) (storage.HydrateProgress, error) + OwnVolumeBatch(ctx context.Context, volumeID string, n int, foreign func(string) bool) (storage.OwnProgress, error) +} + +// RestoreConfig bounds one restore run; zero fields take the defaults. +type RestoreConfig struct { + BatchChunks int + BytesPerSecond int64 +} + +// Restore phases. +const ( + RestoreHydrating = "hydrating" + RestoreOwning = "owning" + RestoreIndependent = "independent" + RestoreFailed = "failed" +) + +// RestoreStatus is the body of /chunk/restore. +type RestoreStatus struct { + VolumeID string `json:"volumeID"` + Phase string `json:"phase"` + Running bool `json:"running"` + Filled int `json:"filled"` // chunks the walker made local + Owned int `json:"owned"` // chunks re-uploaded under own keys + Foreign int `json:"foreign"` // HEAD chunks still naming another volume + NotLocal int `json:"notLocal"` // of those, not local yet + Batches int `json:"batches"` // batch cuts run + MarkedGen uint64 `json:"markedGen"` // HEAD gen the marker names (independent) + ErrorCode string `json:"errorCode,omitempty"` + ErrorText string `json:"error,omitempty"` +} + +// foreignKey reports whether key names another volume's object: an +// owner-qualified key whose owner is not vol. +func foreignKey(vol string) func(string) bool { + own := "@" + vol + "/" + return func(key string) bool { return strings.HasPrefix(key, "@") && !strings.HasPrefix(key, own) } +} + +var ( + errRestoreStuck = errors.New("restore: foreign chunks remain but none is local and the walker fills none") + errNotRestore = errors.New("restore: not a restore") +) + +// runRestore drives one restore of vol to independence, reporting progress. +func runRestore(ctx context.Context, cat *chunkstore.Catalog, p RestoreProvider, vol string, cfg RestoreConfig, report func(RestoreStatus)) (RestoreStatus, error) { + if cfg.BatchChunks <= 0 { + cfg.BatchChunks = DefaultRestoreBatchChunks + } + if cfg.BytesPerSecond <= 0 { + cfg.BytesPerSecond = DefaultRestoreBytesPerSecond + } + st := RestoreStatus{VolumeID: vol, Phase: RestoreHydrating, Running: true} + if m, ok, err := cat.ReadIndependence(ctx, vol); err != nil { + return st, err + } else if ok { + st.Phase, st.MarkedGen = RestoreIndependent, m.HeadGen + return st, nil + } + v, ok, err := cat.ReadVolume(ctx, vol) + if err != nil { + return st, err + } + if !ok || v.Origin != chunkstore.OriginRestore { + return st, fmt.Errorf("volume %s was not made by restore: %w", vol, errNotRestore) + } + foreign := foreignKey(vol) + for stalls := 0; ; { + h, err := p.HydrateVolume(ctx, vol, cfg.BytesPerSecond) + st.Filled += h.Filled + report(st) + if err != nil { + return st, err + } + st.Phase = RestoreOwning + progressed := h.Filled > 0 + for { + o, err := p.OwnVolumeBatch(ctx, vol, cfg.BatchChunks, foreign) + st.Owned, st.Foreign, st.NotLocal = st.Owned+o.Owned, o.Remaining, o.NotLocal + if o.Owned > 0 { + st.Batches++ + progressed = true + } + report(st) + if err != nil { + return st, err + } + if o.Remaining == 0 { + m, err := cat.MarkIndependent(ctx, vol) + if err != nil { + return st, err + } + st.Phase, st.MarkedGen, st.Running = RestoreIndependent, m.HeadGen, false + report(st) + return st, nil + } + if o.Owned == 0 { + break // what is left is not local: walk again + } + } + if !progressed { + if stalls++; stalls > 2 { + return st, errRestoreStuck + } + } else { + stalls = 0 + } + } +} + +// restoreRuns holds at most one running restore per volume and the last +// status of each. +type restoreRuns struct { + mu sync.Mutex + runs map[string]*RestoreStatus +} + +// Restore reports vol's restore status and, with start, starts a run unless +// one is running (POST /chunk/restore). A run outlives the request; it ends +// independent, or failed with the error (a later start resumes from the +// target's remote facts). +func (c *chunkControl) Restore(ctx context.Context, vol string, start bool) (RestoreStatus, error) { + p, ok := c.p.(RestoreProvider) + if !ok { + return RestoreStatus{}, fmt.Errorf("restore: provider has no restore surface: %w", errNotRestore) + } + c.restores.mu.Lock() + defer c.restores.mu.Unlock() + if c.restores.runs == nil { + c.restores.runs = map[string]*RestoreStatus{} + } + cur := c.restores.runs[vol] + if cur != nil && (cur.Running || !start) { + return *cur, nil + } + if !start { + return RestoreStatus{VolumeID: vol}, nil + } + st := &RestoreStatus{VolumeID: vol, Phase: RestoreHydrating, Running: true} + c.restores.runs[vol] = st + report := func(s RestoreStatus) { + c.restores.mu.Lock() + *st = s + c.restores.mu.Unlock() + } + go func() { + final, err := runRestore(context.Background(), c.cat, p, vol, RestoreConfig{}, report) + final.Running = false + if err != nil { + _, code, _ := chunkErrorCode(err) + final.Phase, final.ErrorCode, final.ErrorText = RestoreFailed, code, err.Error() + } + report(final) + }() + return *st, nil +} + +// handleChunkRestore serves GET /chunk/restore?volume=V (status) and +// POST /chunk/restore {"volumeID": V} (start or join a run; with +// "statusOnly": true, status only). Both answer 200 with the status. +func (s *StatusServer) handleChunkRestore(w http.ResponseWriter, r *http.Request) { + method := http.MethodGet + if r.Method == http.MethodPost { + method = http.MethodPost + } + if !s.chunkAdmit(w, r, method) { + return + } + vol := r.URL.Query().Get("volume") + if method == http.MethodPost { + var req struct { + VolumeID string `json:"volumeID"` + StatusOnly bool `json:"statusOnly"` + TimeoutMs int64 `json:"timeoutMs"` + } + if !decodeChunkBody(w, r, &req) { + return + } + vol = req.VolumeID + if req.StatusOnly { + method = http.MethodGet + } + } + ctl := s.chunkTarget(w, vol) + if ctl == nil { + return + } + rc, ok := ctl.(interface { + Restore(context.Context, string, bool) (RestoreStatus, error) + }) + if !ok { + writeChunkErr(w, http.StatusNotFound, codeNotFound, false, "restore is not served here") + return + } + st, err := rc.Restore(r.Context(), vol, method == http.MethodPost) + if err != nil { + writeChunkFailure(w, err) + return + } + writeChunkJSON(w, http.StatusOK, st) +} diff --git a/seaweed-block/core/host/volume/chunk_restore_test.go b/seaweed-block/core/host/volume/chunk_restore_test.go new file mode 100644 index 0000000000..b4eebd880c --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_restore_test.go @@ -0,0 +1,287 @@ +package volume + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "path" + "sort" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const restoreBase = "/swblock/chunks" + +var restoreGeo = chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} + +// sourceReadGuard fails every catalog read of the source volume's own +// entries (VOLUME, HEAD, snapshots) once armed; chunk bindings stay readable +// (hydration reads the source's chunks through T's qualified refs). +type sourceReadGuard struct { + *adapterManifestFiler + armed bool + reads []string +} + +func (g *sourceReadGuard) denied(dir string) bool { + src := path.Join(restoreBase, "v1") + return g.armed && (dir == src || strings.HasPrefix(dir, src+"/snap")) +} + +func (g *sourceReadGuard) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if g.denied(dir) { + g.reads = append(g.reads, path.Join(dir, name)) + return nil, errors.New("test: the restore driver read the source") + } + return g.adapterManifestFiler.LookupEntry(ctx, dir, name) +} + +func (g *sourceReadGuard) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + if g.denied(dir) { + g.reads = append(g.reads, dir) + return nil, errors.New("test: the restore driver listed the source") + } + return g.adapterManifestFiler.ListEntries(ctx, dir, prefix, after, limit) +} + +// fakeRestoreProvider stands in for the chunk layer: the walk makes every +// chunk local, and a batch is one HEAD CAS replacing up to n foreign keys. +type fakeRestoreProvider struct { + r *chunkstore.ChunkRemote + local bool + hydrations int + batches int + failAtBatch int // a batch with this 1-based number fails (0: never) +} + +func (p *fakeRestoreProvider) HydrateVolume(ctx context.Context, vol string, bps int64) (storage.HydrateProgress, error) { + p.hydrations++ + if bps != DefaultRestoreBytesPerSecond { + return storage.HydrateProgress{}, fmt.Errorf("walker pace %d, want the default %d", bps, DefaultRestoreBytesPerSecond) + } + if p.local { + return storage.HydrateProgress{}, nil + } + h, err := p.r.GetHead(ctx) + if err != nil { + return storage.HydrateProgress{}, err + } + p.local = true + return storage.HydrateProgress{Filled: len(h.Chunks)}, nil +} + +func (p *fakeRestoreProvider) OwnVolumeBatch(ctx context.Context, vol string, n int, foreign func(string) bool) (storage.OwnProgress, error) { + h, err := p.r.GetHead(ctx) + if err != nil { + return storage.OwnProgress{}, err + } + var todo []uint64 + for idx, ref := range h.Chunks { + if foreign(ref.Key) { + todo = append(todo, idx) + } + } + sort.Slice(todo, func(i, j int) bool { return todo[i] < todo[j] }) + if !p.local || len(todo) == 0 { + nl := 0 + if !p.local { + nl = len(todo) + } + return storage.OwnProgress{Remaining: len(todo), NotLocal: nl}, nil + } + p.batches++ + if p.batches == p.failAtBatch { + return storage.OwnProgress{Remaining: len(todo)}, errors.New("test: batch cut failed") + } + next := storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}} + for idx, ref := range h.Chunks { + next.Chunks[idx] = ref + } + owned := 0 + for _, idx := range todo { + if owned == n { + break + } + data, err := p.r.Get(ctx, h.Chunks[idx].Key) + if err != nil { + return storage.OwnProgress{}, err + } + key := fmt.Sprintf("chunks/e3/c%d/b%d", idx, p.batches) + if err := p.r.Put(ctx, key, data); err != nil { + return storage.OwnProgress{}, err + } + next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + owned++ + } + next, intents, err := p.r.PrepareManifest(ctx, h, next, uint64(restoreGeo.BlockSize)*uint64(restoreGeo.ChunkBlocks)) + if err != nil { + return storage.OwnProgress{}, err + } + if _, err := p.r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next); err != nil { + return storage.OwnProgress{}, err + } + for _, id := range intents { + _ = p.r.DeleteIntent(ctx, id) + } + return storage.OwnProgress{Owned: owned, Remaining: len(todo) - owned}, nil +} + +// restoreFixtureHost publishes source v1 (chunks), snapshots it and restores +// it into v2; it returns the guard filer, the catalog and v2's provider. +func restoreFixtureHost(t *testing.T, chunks int) (*sourceReadGuard, *chunkstore.Catalog, *fakeRestoreProvider) { + t.Helper() + ctx := context.Background() + f := &sourceReadGuard{adapterManifestFiler: &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}}} + cat, err := chunkstore.NewCatalog(f, restoreBase) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", restoreGeo); err != nil { + t.Fatal(err) + } + r1, err := chunkstore.NewChunkRemote(f, f, path.Join(restoreBase, "v1")) + if err != nil { + t.Fatal(err) + } + cur, err := r1.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} + for idx := 0; idx < chunks; idx++ { + data := make([]byte, int(restoreGeo.BlockSize)*int(restoreGeo.ChunkBlocks)) + data[0] = byte(0x60 + idx) + key := fmt.Sprintf("chunks/e1/c%d/k", idx) + if err := r1.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + h.Chunks[uint64(idx)] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + h, intents, err := r1.PrepareManifest(ctx, cur, h, uint64(restoreGeo.BlockSize)*uint64(restoreGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } + if h.Gen, err = r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil { + t.Fatal(err) + } + for _, id := range intents { + _ = r1.DeleteIntent(ctx, id) + } + if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if _, err := cat.Restore(ctx, chunkstore.ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs"}); err != nil { + t.Fatal(err) + } + r2, err := chunkstore.NewChunkRemote(f, f, path.Join(restoreBase, "v2")) + if err != nil { + t.Fatal(err) + } + return f, cat, &fakeRestoreProvider{r: r2} +} + +func noReport(RestoreStatus) {} + +// The driver walks, cuts bounded batches until no foreign ref is left and +// writes the marker, reading only the target's facts (Restoring>Hydrating> +// Owning>Owning>Independent). +func TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly(t *testing.T) { + f, cat, p := restoreFixtureHost(t, 5) + f.armed = true // from here, any read of the source's catalog entries fails + ctx := context.Background() + st, err := runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err != nil { + t.Fatalf("restore: %+v %v (source reads %v)", st, err, f.reads) + } + if len(f.reads) != 0 { + t.Fatalf("the driver read the source: %v", f.reads) + } + if st.Phase != RestoreIndependent || st.Owned != 5 || st.Foreign != 0 || st.Batches != 3 || st.Filled != 5 { + t.Fatalf("status %+v, want independent after 3 batches of at most 2", st) + } + m, ok, err := cat.ReadIndependence(ctx, "v2") + if err != nil || !ok || m.HeadGen != st.MarkedGen { + t.Fatalf("marker: %+v ok=%v %v", m, ok, err) + } + again, err := runRestore(ctx, cat, p, "v2", RestoreConfig{}, noReport) + if err != nil || again.Phase != RestoreIndependent || p.batches != 3 { + t.Fatalf("a rerun of an independent restore must do nothing: %+v %v", again, err) + } +} + +// A failed batch leaves HEAD as it was; the next run resumes from the +// target's HEAD and finishes. +func TestRestoreDriver_ResumesAfterAFailedBatch(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 5) + ctx := context.Background() + p.failAtBatch = 2 + st, err := runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err == nil || st.Owned != 2 || st.Foreign != 3 { + t.Fatalf("first run: %+v %v, want the failure after 2 owned", st, err) + } + if _, ok, _ := cat.ReadIndependence(ctx, "v2"); ok { + t.Fatal("marker written with foreign refs left") + } + p.failAtBatch = 0 + st, err = runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err != nil || st.Phase != RestoreIndependent || st.Owned != 3 { + t.Fatalf("resumed run: %+v %v, want the 3 left owned and the marker", st, err) + } +} + +// Only a restore volume is driven. +func TestRestoreDriver_RefusesAVolumeNotMadeByRestore(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 1) + if _, err := runRestore(context.Background(), cat, p, "v1", RestoreConfig{}, noReport); !errors.Is(err, errNotRestore) { + t.Fatalf("driving the source volume: %v, want not a restore", err) + } +} + +// POST /chunk/restore starts one background run; GET reports it. +func TestRestoreDriver_ChunkControlStartsOneRunAndReportsIt(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 3) + ctl := &chunkControl{p: restoreOnlyProvider{p}, cat: cat} + ctx := context.Background() + if st, err := ctl.Restore(ctx, "v2", false); err != nil || st.Phase != "" { + t.Fatalf("status before any run: %+v %v", st, err) + } + if _, err := ctl.Restore(ctx, "v2", true); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for { + st, err := ctl.Restore(ctx, "v2", false) + if err != nil { + t.Fatal(err) + } + if !st.Running { + if st.Phase != RestoreIndependent || st.Owned != 3 { + t.Fatalf("final status %+v", st) + } + break + } + if time.Now().After(deadline) { + t.Fatalf("restore still running: %+v", st) + } + time.Sleep(time.Millisecond) + } +} + +// restoreOnlyProvider is a ChunkProvider whose cut and detach are unused. +type restoreOnlyProvider struct{ *fakeRestoreProvider } + +func (restoreOnlyProvider) CutVolume(context.Context, string, uint64) (storage.ChunkCutResult, error) { + return storage.ChunkCutResult{}, errors.New("unused") +} +func (restoreOnlyProvider) DetachVolume(context.Context, string) (storage.ChunkCutResult, uint64, error) { + return storage.ChunkCutResult{}, 0, errors.New("unused") +} + +var _ RestoreProvider = (*durable.DurableProvider)(nil) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 480573c503..c537e968ec 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -243,13 +243,15 @@ 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 + Restoring --> Hydrating: driver starts the paced walker + Hydrating --> Owning: batch cuts start (the walker may still run) + Owning --> Owning: one bounded batch cut replaces up to N foreign refs with own keys + Owning --> 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`. +Snapshots of the target are refused until `Independent`. The driver (`core/host/volume/chunk_restore.go`) runs these steps from the target's own facts; `POST /chunk/restore` starts it and `sw-block ops chunk restore` calls it. ### Attached-volume scheduling diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ba83dc3ba6..e94549d468 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -293,7 +293,10 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | 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 (Restoring) | Hydrating | M6.Restore.Restoring>Hydrating: the driver starts the walker, paced at a byte rate under the BackgroundFill class | `core/host/volume/chunk_restore.go` `runRestore`; `core/frontend/durable/provider_restore.go` `HydrateVolume`; `core/storage/chunk_hydrate_all.go` `HydrateAllAt` | `INV-RESTORE-HYDRATE-001`, `INV-RESTORE-DRIVER-001` | +| restore (Hydrating) | Owning | M6.Restore.Hydrating>Owning: batch cuts start once chunks are local; the walker and the batches may overlap | `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-DRIVER-001` | +| restore (Owning) | Owning | M6.Restore.Owning>Owning: one bounded batch cut re-uploads at most N local chunks with foreign keys under own keys (one intent, one HEAD CAS); absent chunks wait for the walker | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `INV-RESTORE-OWN-BATCH-001` | +| restore (Owning) | Independent | M6.Restore.Owning>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`; `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-INDEPENDENT-001`, `INV-RESTORE-DRIVER-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.** @@ -382,7 +385,7 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage. ## Part B. Invariant ledger -135 rows: 116 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 120 new. +137 rows: 118 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 122 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -576,11 +579,14 @@ Notes: | `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` | 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`) | — (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-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`, `HydrateAllAt`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | +| `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | ACTIVE | +| `INV-RESTORE-DRIVER-001` | The restore driver decides only from the target's VOLUME, HEAD and marker (never the source), writes the marker only after a batch leaves no foreign ref, and a rerun resumes from the target's remote state. | M6.Restore (all transitions) | `core/host/volume/chunk_restore.go` `runRestore`, `chunkControl.Restore` | `TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly`, `TestRestoreDriver_ResumesAfterAFailedBatch`, `TestRestoreDriver_RefusesAVolumeNotMadeByRestore` (`core/host/volume/chunk_restore_test.go`) | `RestoreIndependence` `Independent`, `StateRemote` | 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: +- Restore quantities: batch size N = `DefaultRestoreBatchChunks` (64 chunks per batch cut) and the walker pace = `DefaultRestoreBytesPerSecond` (64 MiB/s, plus the host limiter's BackgroundFill class), both in `core/host/volume/chunk_restore.go`. They move to the quantity table when it exists. ### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing From 5184b1c1196f1ae503910545cdba1f2e298007db Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:25:28 -0800 Subject: [PATCH 3/9] storage: keep the re-own decisions out of captureLocked The re-own candidates join through captureCandidates (addOwnCandidatesLocked) and the HEAD-equal skip is a predicate (unchangedFromHead) in chunk_own.go: captureLocked gains no branch. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 10 ++-------- seaweed-block/core/storage/chunk_own.go | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index f98da1e83f..7650cb3912 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -408,6 +408,7 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { absent[idx] = true } } + l.addOwnCandidatesLocked(out) l.stMu.Unlock() l.s.mu.RLock() for idx, e := range l.s.v3.mapEntries { @@ -853,11 +854,6 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch candidates[i] = true } } - for idx := range l.own { - if !l.absent[idx] { // a re-own reads the local copy, never fetches - candidates[idx] = true - } - } // A staged chunk stands for the barrier copy while no write reached // it since staging (its version is unchanged) and HEAD is the one it // was compared against. @@ -981,9 +977,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch c.birth = births[c.idx] ref, had := baseHead.Chunks[c.idx] switch { - case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum && c.key == "": - // A chunk equal to HEAD is skipped unless streamCutPayloads - // uploaded it under a new key: a re-owned chunk (OwnBatch). + case c.zero && !had, unchangedFromHead(c, ref, had): st.UnchangedChunks++ continue case c.zero: diff --git a/seaweed-block/core/storage/chunk_own.go b/seaweed-block/core/storage/chunk_own.go index e86ebd408a..5f9188f8b4 100644 --- a/seaweed-block/core/storage/chunk_own.go +++ b/seaweed-block/core/storage/chunk_own.go @@ -94,3 +94,22 @@ func (l *chunkLayerImpl) owning(idx uint64) bool { defer l.stMu.Unlock() return l.own[idx] } + +// addOwnCandidatesLocked adds the running OwnBatch's chunks to a cut's +// candidates: a re-own reads the local copy, so an absent chunk is left out. +// Caller holds stMu. +func (l *chunkLayerImpl) addOwnCandidatesLocked(out map[uint64]bool) { + for idx := range l.own { + if !l.absent[idx] { + out[idx] = true + } + } +} + +// unchangedFromHead reports whether a captured chunk equals HEAD's and was +// not uploaded: such a chunk keeps its HEAD ref. A re-owned chunk equal to +// HEAD was uploaded by streamCutPayloads under a new own key (c.key set), so +// it is published like a changed chunk. +func unchangedFromHead(c capturedChunk, ref chunkRef, had bool) bool { + return had && !c.zero && ref.SHA256 == c.sum && c.key == "" +} From c041d9e28e2b822721aa8a030cf6f90f2f1e0329 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 01:23:17 -0800 Subject: [PATCH 4/9] spec: RestoreIndependence no-claim variant (exhausted) replaces the claim-era model The model this part rests on, as checked (no-claim variant; only comment lines changed: seat and note names removed), with its 26 configurations: the no-claim safe cfgs exhausted with no error (360 k to 2.75 M states), the boundary G >= D on one clock (ForkDelete's G >= D + E + P with E = P = 0), 13 reds and 2 witnesses on their properties, and the claim-frame regression cfgs. The claim-era configurations not re-run against this spec are removed. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/spec/README.md | 2 +- .../docs/spec/RestoreIndependence.tla | 107 ++++++++++++++++-- ...fg => RestoreIndependence_nc_bnd_G0D1.cfg} | 11 +- .../cfg/RestoreIndependence_nc_bnd_G1D1.cfg | 30 +++++ .../cfg/RestoreIndependence_nc_bnd_G2D3.cfg | 30 +++++ .../cfg/RestoreIndependence_nc_bnd_G3D3.cfg | 30 +++++ ...reIndependence_nc_red_CasBeforeUpload.cfg} | 10 +- .../cfg/RestoreIndependence_nc_red_GltD.cfg | 30 +++++ ...estoreIndependence_nc_red_ListForeign.cfg} | 10 +- ...reIndependence_nc_red_MarkerBeforeCas.cfg} | 10 +- ...estoreIndependence_nc_red_MarkerEarly.cfg} | 10 +- ...> RestoreIndependence_nc_red_NoIntent.cfg} | 10 +- ...estoreIndependence_nc_red_ResumeLocal.cfg} | 10 +- ...Independence_nc_red_SnapDuringRestore.cfg} | 10 +- .../RestoreIndependence_nc_red_noDeadline.cfg | 30 +++++ .../RestoreIndependence_nc_red_notRooted.cfg | 30 +++++ ...toreIndependence_nc_red_resumeNoReread.cfg | 30 +++++ .../spec/cfg/RestoreIndependence_nc_safe.cfg | 30 +++++ .../cfg/RestoreIndependence_nc_safe_G3D2.cfg | 30 +++++ ...cfg => RestoreIndependence_nc_safe_b2.cfg} | 12 +- ...cfg => RestoreIndependence_nc_safe_n4.cfg} | 12 +- .../RestoreIndependence_nc_wit_DelInFork.cfg | 31 +++++ ...estoreIndependence_nc_wit_FailNotFound.cfg | 31 +++++ ...t.cfg => RestoreIndependence_oldframe.cfg} | 8 ++ .../cfg/RestoreIndependence_oldframe_drop.cfg | 31 +++++ ....cfg => RestoreIndependence_opt1_safe.cfg} | 8 +- ...eIndependence_red_DropClaimAtFork_gap.cfg} | 10 +- ...ependence_red_retention_ignores_marker.cfg | 24 ---- .../spec/cfg/RestoreIndependence_safe.cfg | 11 +- 30 files changed, 574 insertions(+), 66 deletions(-) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_wit_crash_resume.cfg => RestoreIndependence_nc_bnd_G0D1.cfg} (74%) create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_cas_before_upload.cfg => RestoreIndependence_nc_red_CasBeforeUpload.cfg} (74%) create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_list_foreign.cfg => RestoreIndependence_nc_red_ListForeign.cfg} (74%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_marker_before_cas.cfg => RestoreIndependence_nc_red_MarkerBeforeCas.cfg} (74%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_marker_early.cfg => RestoreIndependence_nc_red_MarkerEarly.cfg} (74%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_no_intent.cfg => RestoreIndependence_nc_red_NoIntent.cfg} (74%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_resume_local.cfg => RestoreIndependence_nc_red_ResumeLocal.cfg} (74%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_snap_during_restore.cfg => RestoreIndependence_nc_red_SnapDuringRestore.cfg} (74%) create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg rename seaweed-block/docs/spec/cfg/{RestoreIndependence_safe_b2.cfg => RestoreIndependence_nc_safe_b2.cfg} (69%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_safe_n4.cfg => RestoreIndependence_nc_safe_n4.cfg} (69%) create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg rename seaweed-block/docs/spec/cfg/{RestoreIndependence_strict_claim_until_independent.cfg => RestoreIndependence_oldframe.cfg} (76%) create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg rename seaweed-block/docs/spec/cfg/{RestoreIndependence_wit_done.cfg => RestoreIndependence_opt1_safe.cfg} (78%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_drop_claim_at_fork.cfg => RestoreIndependence_red_DropClaimAtFork_gap.cfg} (72%) delete mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e94549d468..e04cf77a34 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -577,7 +577,7 @@ Notes: | `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` | 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-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` (`nc_red_SnapDuringRestore`) | 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`, `HydrateAllAt`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | | `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | ACTIVE | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 920aa86a83..0ca7540f3b 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -117,7 +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` | **Exhaustive (TLC breadth-first, complete state graph, no error)** at MaxCrash 2, MaxGc 3 (4 for `n4`): option 1 (claim dropped at the first HEAD, the code): `safe` (NIdx 3, Batch 1) 3,639 distinct states; `safe_b2` 4,492; `safe_n4` (NIdx 4, Batch 2) 25,240. Strict variant `strict_claim_until_independent` 1,599 (and 2,003 / 9,838 at the `b2` / `n4` sizes, not shipped as cfgs here). **RED** (each violated at its invariant): `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`. Limits: no guest writes to the target while it takes ownership, GC acts immediately (no grace), one restore per snapshot. | `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. | +| S10 | `RestoreIndependence` | Independent restore: fork of a sealed snapshot, hydrate, bounded batch cuts (own fids uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref; GC, source delete, snapshot retention, and crashes with resume from remote facts at any point. `NoClaim` (the code): no claim; the fork window is safe by two time rules on one clock, ForkEnd only while now < readAt + D and a deleted snapshot rooted while now < delAt + G. The older claim variants stay as regression configurations. | `NoGap`, `Independent`, `NoForeignList`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)**, no-claim: `nc_safe` 405,198 distinct states; `nc_safe_b2` 504,097; `nc_safe_n4` 2,752,518; `nc_safe_G3D2` 379,500; boundary `nc_bnd_G1D1` 444,564 and `nc_bnd_G3D3` 360,615 safe, `nc_bnd_G0D1` and `nc_bnd_G2D3` violate NoGap: safe iff G >= D on one clock, which is `ForkDelete`'s G >= D + E + P with E = P = 0 (the production inequality is ForkDelete's). **RED** (each violated): `nc_red_CasBeforeUpload`, `nc_red_NoIntent`, `nc_red_GltD`, `nc_red_noDeadline`, `nc_red_notRooted`, `nc_red_resumeNoReread` NoGap; `nc_red_MarkerEarly`, `nc_red_MarkerBeforeCas`, `nc_red_SnapDuringRestore` Independent; `nc_red_ListForeign` NoForeignList; `nc_red_ResumeLocal` StateRemote. **Witnesses reached:** `nc_wit_DelInFork` (the source snapshot deleted inside the fork window and the restore completes), `nc_wit_FailNotFound`. Regression (claim frame): `safe` 1,599, `opt1_safe` 3,639, `oldframe` 1,599 safe; `oldframe_drop`, `red_DropClaimAtFork_gap` violate NoGap. Limits: no guest writes to the target while it takes ownership, GC acts immediately, one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAllAt`; `core/storage/chunk_own.go` `OwnBatch`; `core/host/volume/chunk_restore.go` `runRestore` | ## Limits diff --git a/seaweed-block/docs/spec/RestoreIndependence.tla b/seaweed-block/docs/spec/RestoreIndependence.tla index 796850fe6a..66b87257ff 100644 --- a/seaweed-block/docs/spec/RestoreIndependence.tla +++ b/seaweed-block/docs/spec/RestoreIndependence.tla @@ -1,7 +1,6 @@ ------------------------------ MODULE RestoreIndependence ------------------------------ (***************************************************************************) -(* Independent restore: restore a snapshot into a volume that ends up *) -(* owning all its chunks, with no lineage to the source. *) +(* Independent restore of a snapshot into a new volume. *) (* 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) *) @@ -12,8 +11,14 @@ (* 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 *) +(* Reuse: the fid/owner/root vocabulary of the chunk GC model; this *) (* spec models only what the restore adds, not the superseded list/grace. *) +(* NOCLAIM: with NoClaim = TRUE claims are removed; *) +(* a snapshot delete never looks at a fork. Safety of the ForkBegin.. *) +(* ForkEnd window comes from two time rules on one clock: (D) ForkEnd only *) +(* while now < readAt + D, else ForkFail; (G) a deleted S stays a GC root *) +(* while now < delAt + G. With NoClaim = FALSE nothing below changes the *) +(* old model (Tick, ForkFail, ForkNotFound disabled; new variables fixed). *) (***************************************************************************) EXTENDS Integers, FiniteSets, TLC @@ -33,7 +38,15 @@ CONSTANTS 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 + NoIntent, \* uploaded batch fids are not rooted by an intent before the HEAD CAS + \* ---- NOCLAIM variant; old cfgs: NoClaim = FALSE, D = G = MaxTick = 0, the three below TRUE ---- + NoClaim, \* TRUE: no claim ever holds S; DeleteS needs only slive; time rules D and G apply + D, \* fork deadline: ForkEnd only while now < readAt + D (read only when NoClaim) + G, \* grace: a deleted S stays a root while now < delAt + G (read only when NoClaim) + MaxTick, \* bound of the clock (Tick is enabled only when NoClaim) + ForkChecksDeadline,\* design TRUE; mutant FALSE = ForkEnd at any time + DeletedRooted, \* design TRUE; mutant FALSE = a deleted S stops being a root at once + ResumeRereads \* design TRUE; mutant FALSE = a resume in the fork window reuses the old read (fresh deadline, S not re-read) Idx == 1..NIdx VF == [i \in Idx |-> <<"V", i>>] \* the source fid of index i @@ -41,6 +54,7 @@ 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>>] +None == -1 \* nc: "no tick" encoding for readAt / delAt VARIABLES store, \* Fids -> "none" | "pres" | "del" @@ -54,40 +68,70 @@ VARIABLES 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 + crashes, gcs, + \* ---- nc (all fixed at their Init value when NoClaim = FALSE) ---- + now, \* the one clock + readAt, \* tick at which the current fork attempt read S (None if no attempt in progress) + delAt, \* tick at which S was deleted (None while S lives) + sdelfk, \* history: S was deleted while step = "fk" (for the witness) + ffail \* history: a fork attempt failed on its deadline (for the witness) -vars == <> +tvars == <> +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} +\* nc rule G: a deleted S stays a root for G ticks (FALSE whenever NoClaim = FALSE) +SGrace == NoClaim /\ DeletedRooted /\ ~ slive /\ delAt # None /\ now < delAt + G Roots == (IF vlive THEN SFids ELSE {}) - \cup (IF slive THEN SFids ELSE {}) + \cup (IF (slive \/ SGrace) 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) +\* nc: with NoClaim the snapshot delete never looks at a fork +SDeletable == slive /\ (NoClaim \/ ~ SHeld) +\* nc rule D (TRUE whenever NoClaim = FALSE) +DeadlineOK == (~ NoClaim) \/ (~ ForkChecksDeadline) \/ (now < readAt + D) 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 + /\ now = 0 /\ readAt = None /\ delAt = None /\ sdelfk = FALSE /\ ffail = FALSE \* step 0: S is sealed (given) and claimed -Claim == step = "start" /\ slive /\ claim' = TRUE /\ step' = "c" +\* nc: the step is kept (S found, step counter) but takes no claim +Claim == step = "start" /\ slive /\ claim' = (~ NoClaim) /\ step' = "c" /\ UNCHANGED <> + /\ UNCHANGED tvars \* 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. +\* nc: ForkBegin reads S (requires S live) and records readAt; ForkEnd only within the deadline ForkBegin == step = "c" /\ step' = "fk" + /\ (NoClaim => slive) /\ claim' = (IF DropClaimAtFork THEN FALSE ELSE claim) + /\ readAt' = (IF NoClaim THEN now ELSE readAt) /\ UNCHANGED <> -ForkEnd == step = "fk" /\ thead' = VF /\ step' = "own" + /\ UNCHANGED <> +ForkEnd == step = "fk" /\ DeadlineOK /\ thead' = VF /\ step' = "own" /\ claim' = (IF ClaimUntilHead THEN FALSE ELSE claim) /\ UNCHANGED <> + /\ UNCHANGED tvars +\* nc: past the deadline the fork fails cleanly: T stays without a HEAD, a retry is a new ForkBegin +ForkFail == NoClaim /\ step = "fk" /\ now >= readAt + D + /\ step' = "c" /\ readAt' = None /\ ffail' = TRUE + /\ UNCHANGED <> + /\ UNCHANGED <> +\* nc: a (re)try that re-reads S and finds it gone ends with "not found" (terminal) +ForkNotFound == NoClaim /\ step = "c" /\ ~ slive /\ step' = "nf" + /\ UNCHANGED <> + /\ UNCHANGED tvars \* 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} @@ -96,6 +140,7 @@ Upload(B) == step = "own" /\ up = {} /\ ~ CasBeforeUpload /\ store' = [f \in Fids |-> IF f \in {TF[j] : j \in B} THEN "pres" ELSE store[f]] /\ up' = {TF[j] : j \in B} /\ UNCHANGED <> + /\ UNCHANGED tvars \* 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]] @@ -103,50 +148,75 @@ Cas == step = "own" /\ up # {} /\ up' = {} /\ localdone' = (localdone \/ \A i \in Idx : (thead[i][1] = "V") => (TF[i] \in up)) /\ UNCHANGED <> + /\ UNCHANGED tvars \* 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 <> + /\ UNCHANGED tvars UploadLate == CasBeforeUpload /\ step = "own" /\ \E i \in Idx : thead[i] = TF[i] /\ store[TF[i]] = "none" /\ store' = [store EXCEPT ![TF[i]] = "pres"] /\ UNCHANGED <> + /\ UNCHANGED tvars \* 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 <> + /\ UNCHANGED tvars DropClaim == marker /\ claim /\ claim' = FALSE /\ UNCHANGED <> + /\ UNCHANGED tvars \* a snapshot of T: refused before the marker (unless the mutant allows it) SnapT == tsnap = {} /\ thead # NoHead /\ (marker \/ SnapDuringRestore) /\ tsnap' = THeadFids /\ UNCHANGED <> + /\ UNCHANGED tvars \* crash of the restore process; the new owner resumes from remote facts (thead, marker) +\* nc: a resume in the fork window (no HEAD) is a retry that re-reads S (back to "c", new +\* ForkBegin requires S live); mutant ~ResumeRereads: stays "fk" with a fresh deadline (readAt = now) +\* and the content read before the crash 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") + ELSE IF marker THEN "done" + ELSE IF thead = NoHead THEN (IF (NoClaim /\ ResumeRereads) THEN "c" ELSE "fk") + ELSE "own") + /\ readAt' = (IF (NoClaim /\ thead = NoHead) THEN (IF ResumeRereads THEN None ELSE now) ELSE readAt) /\ crashes' = crashes + 1 /\ UNCHANGED <> + /\ UNCHANGED <> \* user deletes V; retention deletes S when nothing holds it DeleteV == vlive /\ vlive' = FALSE /\ UNCHANGED <> -DeleteS == slive /\ ~ SHeld /\ slive' = FALSE + /\ UNCHANGED tvars +\* nc: whenever S is live (SDeletable = slive); records delAt and whether a fork was in its window +DeleteS == SDeletable /\ slive' = FALSE + /\ delAt' = (IF NoClaim THEN now ELSE delAt) + /\ sdelfk' = (IF (NoClaim /\ step = "fk") THEN TRUE ELSE sdelfk) /\ UNCHANGED <> + /\ 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 <> + /\ UNCHANGED tvars + +\* nc: time advances by one tick (never when NoClaim = FALSE) +Tick == NoClaim /\ now < MaxTick /\ now' = now + 1 + /\ UNCHANGED <> + /\ UNCHANGED <> Next == Claim \/ ForkBegin \/ ForkEnd \/ Cas \/ Marker \/ DropClaim \/ SnapT \/ Crash \/ DeleteV \/ DeleteS \/ Gc \/ UploadLate \/ (\E B \in BatchSet : Upload(B) \/ CasEarly(B)) + \/ ForkFail \/ ForkNotFound \/ Tick Spec == Init /\ [][Next]_vars @@ -163,11 +233,24 @@ ClaimUntilIndependent == (thead # NoHead /\ ~ marker) => claim ClaimUntilHead_Inv == (step = "fk") => claim \* lifecycle independence: after the marker and the claim drop, nothing of T holds S LifecycleFree == (marker /\ ~ claim) => ~ SHeld +\* nc replacement of LifecycleFree: nothing ever holds S; S is deletable at every moment it lives +LifecycleFreeNC == NoClaim => (~ claim /\ (SDeletable = slive)) +\* nc frame check for old cfgs: with NoClaim = FALSE the new variables never move +OldFrame == (~ NoClaim) => (now = 0 /\ readAt = None /\ delAt = None /\ ~ sdelfk /\ ~ ffail) \* 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 +TypeOK == /\ step \in {"start", "c", "fk", "own", "done", "nf"} /\ up \subseteq Fids /\ tsnap \subseteq Fids + /\ now \in 0..MaxTick /\ readAt \in {None} \cup (0..MaxTick) /\ delAt \in {None} \cup (0..MaxTick) + /\ sdelfk \in BOOLEAN /\ ffail \in BOOLEAN \* 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) +\* nc witnesses: S deleted inside the fork window and the restore still completes, every block present, +\* every V fid physically gone +W_nc_DelInFork == ~ (sdelfk /\ marker /\ step = "done" /\ ~ vlive /\ ~ slive + /\ (\A i \in Idx : store[VF[i]] = "del") + /\ (\A i \in Idx : store[thead[i]] = "pres")) +\* nc witness: a fork failed on its deadline and a retry found S gone +W_nc_FailNotFound == ~ (ffail /\ step = "nf") ============================================================================= diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg index 1ab2298c47..8102f6b6cf 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg @@ -14,12 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 1 + G = 0 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote - W_CrashResume diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg new file mode 100644 index 0000000000..5b319dceb8 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg @@ -0,0 +1,30 @@ +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 + NoClaim = TRUE + D = 1 + G = 1 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg new file mode 100644 index 0000000000..959c1e147f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg @@ -0,0 +1,30 @@ +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 + NoClaim = TRUE + D = 3 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg new file mode 100644 index 0000000000..dabec4a948 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg @@ -0,0 +1,30 @@ +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 + NoClaim = TRUE + D = 3 + G = 3 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg index 70a61b6cee..b398ea33a7 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg new file mode 100644 index 0000000000..d5a4f2f982 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg @@ -0,0 +1,30 @@ +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 + NoClaim = TRUE + D = 2 + G = 1 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg index 82592e7bc4..460f66230b 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg index 560a8c4cc7..088e125bd2 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg index 38b2ecc46a..de0c18acac 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg index b2ed698e1f..a9584e358a 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = TRUE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg index 383cbda367..a5690276cb 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg index dce285726d..00961ba3fb 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg new file mode 100644 index 0000000000..1d114c2163 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg @@ -0,0 +1,30 @@ +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 + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = FALSE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg new file mode 100644 index 0000000000..cd8b15a2c1 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg @@ -0,0 +1,30 @@ +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 + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = FALSE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg new file mode 100644 index 0000000000..a623dd8f51 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg @@ -0,0 +1,30 @@ +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 + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg new file mode 100644 index 0000000000..fef3519c2c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg @@ -0,0 +1,30 @@ +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 + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg new file mode 100644 index 0000000000..24ee54e48a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg @@ -0,0 +1,30 @@ +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 + NoClaim = TRUE + D = 2 + G = 3 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg similarity index 69% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg index bf269afeae..9b33687854 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg @@ -12,13 +12,19 @@ CONSTANTS ResumeLocal = FALSE SnapDuringRestore = FALSE RetentionIgnoresMarker = FALSE - ClaimUntilHead = TRUE + ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilHead_Inv - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg similarity index 69% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg index 34c9db075b..c0c370f29e 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg @@ -12,13 +12,19 @@ CONSTANTS ResumeLocal = FALSE SnapDuringRestore = FALSE RetentionIgnoresMarker = FALSE - ClaimUntilHead = TRUE + ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilHead_Inv - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg new file mode 100644 index 0000000000..79708ebd36 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg @@ -0,0 +1,31 @@ +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 + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote + W_nc_DelInFork diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg new file mode 100644 index 0000000000..74cc24ef9f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg @@ -0,0 +1,31 @@ +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 + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote + W_nc_FailNotFound diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg similarity index 76% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg index 9590e854ad..ae5548a57e 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg @@ -14,6 +14,13 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap @@ -22,3 +29,4 @@ INVARIANTS ClaimUntilIndependent LifecycleFree StateRemote + OldFrame diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg new file mode 100644 index 0000000000..33e1c88fdb --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg @@ -0,0 +1,31 @@ +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 = FALSE + NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFree + StateRemote + OldFrame diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg similarity index 78% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg index 3d9c60ac18..c4f0281674 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg @@ -14,6 +14,13 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = TRUE NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap @@ -22,4 +29,3 @@ INVARIANTS ClaimUntilHead_Inv LifecycleFree StateRemote - W_Done diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg similarity index 72% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg index 5dae146b29..6bd867a906 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg @@ -12,13 +12,19 @@ CONSTANTS ResumeLocal = FALSE SnapDuringRestore = FALSE RetentionIgnoresMarker = FALSE - ClaimUntilHead = TRUE + ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilHead_Inv 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 deleted file mode 100644 index 6c115a1f13..0000000000 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg +++ /dev/null @@ -1,24 +0,0 @@ -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_safe.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg index 682ed72f1f..5327a664e4 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg @@ -12,13 +12,20 @@ CONSTANTS ResumeLocal = FALSE SnapDuringRestore = FALSE RetentionIgnoresMarker = FALSE - ClaimUntilHead = TRUE + ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilHead_Inv + ClaimUntilIndependent LifecycleFree StateRemote From 7a9d0f7008ab6c22b1f9e96f073101d56fff21b6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 02:17:05 -0800 Subject: [PATCH 5/9] fold: re-own fully local absent chunks, drop keyless cached payloads, owner-bound driver, stricter tests - OwnBatch, its cut candidates and its progress use one predicate: a chunk is local when present or when every block was written locally (a guest overwrite flushed before the walker reached it), so such a chunk is owned with no fetch instead of stalling the driver. - OwnBatch drops a remembered payload of a picked chunk that matched HEAD and was never uploaded (no key), so the cut reads and uploads it under an own key. - The driver runs inside the serving provider's lifetime (DurableProvider GoOwned: ctx ends at Close, Close joins it); a closed provider admits none. - Tests (each red without its fix): fully overwritten absent chunk owned with no Get; equal keyless payload from a failed cut still re-owned; a second start joins the running run (one walk); owner close cancels and joins a run held in a provider call and no marker follows; Close joins GoOwned; the pacing test requires all 8 fills and Gets and witnesses admission times. - Restore diagram and bullet without claims (same text as the snapshot-delete change). Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider_restore.go | 23 +++ .../frontend/durable/provider_restore_test.go | 44 +++++ .../core/host/volume/chunk_restore.go | 26 ++- .../core/host/volume/chunk_restore_test.go | 162 ++++++++++++++---- .../core/storage/chunk_hydrate_all_test.go | 46 ++++- seaweed-block/core/storage/chunk_own.go | 35 +++- seaweed-block/core/storage/chunk_own_test.go | 96 +++++++++++ .../docs/design/agent-workspace-design.md | 8 +- 8 files changed, 389 insertions(+), 51 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/provider_restore_test.go diff --git a/seaweed-block/core/frontend/durable/provider_restore.go b/seaweed-block/core/frontend/durable/provider_restore.go index fde0c680aa..6956c2d0f5 100644 --- a/seaweed-block/core/frontend/durable/provider_restore.go +++ b/seaweed-block/core/frontend/durable/provider_restore.go @@ -2,6 +2,7 @@ package durable import ( "context" + "errors" "fmt" "github.com/seaweedfs/seaweed-block/core/hostlimit" @@ -49,3 +50,25 @@ func (p *DurableProvider) OwnVolumeBatch(ctx context.Context, volumeID string, n defer cancel() return r.OwnBatch(ctx, n, foreign) } + +// ErrProviderClosed refuses work admitted after Close. +var ErrProviderClosed = errors.New("durable: provider closed") + +// GoOwned runs fn on its own goroutine inside the provider's lifetime: its +// ctx ends when Close starts, and Close waits for fn to return before it +// closes any store. A restore driver runs this way, so it never outlives the +// volume it drives. +func (p *DurableProvider) GoOwned(fn func(ctx context.Context)) error { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return ErrProviderClosed + } + p.inflight.Add(1) + p.mu.Unlock() + go func() { + defer p.inflight.Done() + fn(p.closeCtx) + }() + return nil +} diff --git a/seaweed-block/core/frontend/durable/provider_restore_test.go b/seaweed-block/core/frontend/durable/provider_restore_test.go new file mode 100644 index 0000000000..63cc0ab70f --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_restore_test.go @@ -0,0 +1,44 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// A goroutine started with GoOwned sees its ctx end when Close starts, and +// Close returns only after it has returned; after Close nothing is admitted. +func TestDurableProvider_GoOwnedIsCancelledAndJoinedByClose(t *testing.T) { + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 64}, v1View()) + if err != nil { + t.Fatal(err) + } + started, finished := make(chan struct{}), make(chan struct{}) + if err := p.GoOwned(func(ctx context.Context) { + close(started) + <-ctx.Done() + time.Sleep(20 * time.Millisecond) // still settling when Close is called + close(finished) + }); err != nil { + t.Fatal(err) + } + <-started + closed := make(chan struct{}) + go func() { _ = p.Close(); close(closed) }() + select { + case <-closed: + select { + case <-finished: + default: + t.Fatal("Close returned before the owned goroutine finished") + } + case <-time.After(5 * time.Second): + t.Fatal("Close did not return") + } + if err := p.GoOwned(func(context.Context) {}); !errors.Is(err, durable.ErrProviderClosed) { + t.Fatalf("GoOwned after Close: %v, want ErrProviderClosed", err) + } +} diff --git a/seaweed-block/core/host/volume/chunk_restore.go b/seaweed-block/core/host/volume/chunk_restore.go index eb334788df..94521f0134 100644 --- a/seaweed-block/core/host/volume/chunk_restore.go +++ b/seaweed-block/core/host/volume/chunk_restore.go @@ -149,12 +149,13 @@ type restoreRuns struct { } // Restore reports vol's restore status and, with start, starts a run unless -// one is running (POST /chunk/restore). A run outlives the request; it ends -// independent, or failed with the error (a later start resumes from the -// target's remote facts). +// one is running (POST /chunk/restore). A run outlives the request but not +// the serving provider (RestoreOwner); it ends independent, or failed with +// the error (a later start resumes from the target's remote facts). func (c *chunkControl) Restore(ctx context.Context, vol string, start bool) (RestoreStatus, error) { p, ok := c.p.(RestoreProvider) - if !ok { + owner, owned := c.p.(RestoreOwner) + if !ok || !owned { return RestoreStatus{}, fmt.Errorf("restore: provider has no restore surface: %w", errNotRestore) } c.restores.mu.Lock() @@ -176,18 +177,29 @@ func (c *chunkControl) Restore(ctx context.Context, vol string, start bool) (Res *st = s c.restores.mu.Unlock() } - go func() { - final, err := runRestore(context.Background(), c.cat, p, vol, RestoreConfig{}, report) + run := func(ctx context.Context) { + final, err := runRestore(ctx, c.cat, p, vol, RestoreConfig{}, report) final.Running = false if err != nil { _, code, _ := chunkErrorCode(err) final.Phase, final.ErrorCode, final.ErrorText = RestoreFailed, code, err.Error() } report(final) - }() + } + if err := owner.GoOwned(run); err != nil { + delete(c.restores.runs, vol) + return RestoreStatus{}, err + } return *st, nil } +// RestoreOwner runs the driver inside the serving volume's lifetime: the +// driver's ctx ends when the owner closes, and the owner waits for it +// (DurableProvider.GoOwned). +type RestoreOwner interface { + GoOwned(fn func(ctx context.Context)) error +} + // handleChunkRestore serves GET /chunk/restore?volume=V (status) and // POST /chunk/restore {"volumeID": V} (start or join a run; with // "statusOnly": true, status only). Both answer 200 with the status. diff --git a/seaweed-block/core/host/volume/chunk_restore_test.go b/seaweed-block/core/host/volume/chunk_restore_test.go index b4eebd880c..17b264e38a 100644 --- a/seaweed-block/core/host/volume/chunk_restore_test.go +++ b/seaweed-block/core/host/volume/chunk_restore_test.go @@ -8,6 +8,7 @@ import ( "path" "sort" "strings" + "sync" "testing" "time" @@ -59,10 +60,24 @@ type fakeRestoreProvider struct { hydrations int batches int failAtBatch int // a batch with this 1-based number fails (0: never) + mu sync.Mutex + entered chan struct{} // if set, HydrateVolume signals entry and + gate chan struct{} // then waits for gate or its ctx } func (p *fakeRestoreProvider) HydrateVolume(ctx context.Context, vol string, bps int64) (storage.HydrateProgress, error) { + p.mu.Lock() p.hydrations++ + entered, gate := p.entered, p.gate + p.mu.Unlock() + if entered != nil { + entered <- struct{}{} + select { + case <-gate: + case <-ctx.Done(): + return storage.HydrateProgress{}, ctx.Err() + } + } if bps != DefaultRestoreBytesPerSecond { return storage.HydrateProgress{}, fmt.Errorf("walker pace %d, want the default %d", bps, DefaultRestoreBytesPerSecond) } @@ -244,38 +259,44 @@ func TestRestoreDriver_RefusesAVolumeNotMadeByRestore(t *testing.T) { } } -// POST /chunk/restore starts one background run; GET reports it. -func TestRestoreDriver_ChunkControlStartsOneRunAndReportsIt(t *testing.T) { - _, cat, p := restoreFixtureHost(t, 3) - ctl := &chunkControl{p: restoreOnlyProvider{p}, cat: cat} - ctx := context.Background() - if st, err := ctl.Restore(ctx, "v2", false); err != nil || st.Phase != "" { - t.Fatalf("status before any run: %+v %v", st, err) - } - if _, err := ctl.Restore(ctx, "v2", true); err != nil { - t.Fatal(err) - } - deadline := time.Now().Add(5 * time.Second) - for { - st, err := ctl.Restore(ctx, "v2", false) - if err != nil { - t.Fatal(err) - } - if !st.Running { - if st.Phase != RestoreIndependent || st.Owned != 3 { - t.Fatalf("final status %+v", st) - } - break - } - if time.Now().After(deadline) { - t.Fatalf("restore still running: %+v", st) - } - time.Sleep(time.Millisecond) +// testOwner runs owned goroutines until close, which cancels and joins them +// (bounded), like DurableProvider.Close. +type testOwner struct { + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup +} + +func newTestOwner(t *testing.T) *testOwner { + o := &testOwner{} + o.ctx, o.cancel = context.WithCancel(context.Background()) + t.Cleanup(func() { o.close(t) }) + return o +} + +func (o *testOwner) GoOwned(fn func(context.Context)) error { + o.wg.Add(1) + go func() { defer o.wg.Done(); fn(o.ctx) }() + return nil +} + +func (o *testOwner) close(t *testing.T) { + o.cancel() + done := make(chan struct{}) + go func() { o.wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("owned restore run did not return after close") } } -// restoreOnlyProvider is a ChunkProvider whose cut and detach are unused. -type restoreOnlyProvider struct{ *fakeRestoreProvider } +// restoreOnlyProvider is a ChunkProvider (cut and detach unused) with the +// restore surface and an owner. +type restoreOnlyProvider struct { + *fakeRestoreProvider + *testOwner +} func (restoreOnlyProvider) CutVolume(context.Context, string, uint64) (storage.ChunkCutResult, error) { return storage.ChunkCutResult{}, errors.New("unused") @@ -284,4 +305,87 @@ func (restoreOnlyProvider) DetachVolume(context.Context, string) (storage.ChunkC return storage.ChunkCutResult{}, 0, errors.New("unused") } +func waitRestore(t *testing.T, ctl *chunkControl, vol string) RestoreStatus { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + st, err := ctl.Restore(context.Background(), vol, false) + if err != nil { + t.Fatal(err) + } + if !st.Running { + return st + } + if time.Now().After(deadline) { + t.Fatalf("restore still running: %+v", st) + } + time.Sleep(time.Millisecond) + } +} + +// POST /chunk/restore starts one background run: a second start while the +// first is held joins it (one walk), and the run is reported to the end. +func TestRestoreDriver_ChunkControlStartsOneRunAndReportsIt(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 3) + owner := newTestOwner(t) + p.entered, p.gate = make(chan struct{}, 2), make(chan struct{}) + release := func() { + select { + case <-p.gate: + default: + close(p.gate) + } + } + t.Cleanup(release) // registered before launch; the owner joins after it + ctl := &chunkControl{p: restoreOnlyProvider{p, owner}, cat: cat} + ctx := context.Background() + if st, err := ctl.Restore(ctx, "v2", false); err != nil || st.Phase != "" { + t.Fatalf("status before any run: %+v %v", st, err) + } + if _, err := ctl.Restore(ctx, "v2", true); err != nil { + t.Fatal(err) + } + select { + case <-p.entered: + case <-time.After(5 * time.Second): + t.Fatal("the run never reached the walker") + } + if st, err := ctl.Restore(ctx, "v2", true); err != nil || !st.Running { + t.Fatalf("second start while the first runs: %+v %v, want it joined", st, err) + } + release() + st := waitRestore(t, ctl, "v2") + p.mu.Lock() + walks := p.hydrations + p.mu.Unlock() + if walks != 1 || st.Phase != RestoreIndependent || st.Owned != 3 { + t.Fatalf("walks=%d status %+v, want one run to independence", walks, st) + } +} + +// Closing the serving owner cancels a run held in a provider call and joins +// it: the run ends failed and publishes no marker after the close. +func TestRestoreDriver_OwnerCloseCancelsAndJoinsTheRun(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 3) + owner := newTestOwner(t) + p.entered, p.gate = make(chan struct{}, 1), make(chan struct{}) // gate never opens + ctl := &chunkControl{p: restoreOnlyProvider{p, owner}, cat: cat} + if _, err := ctl.Restore(context.Background(), "v2", true); err != nil { + t.Fatal(err) + } + select { + case <-p.entered: + case <-time.After(5 * time.Second): + t.Fatal("the run never reached the walker") + } + owner.close(t) // cancel and bounded join, like DurableProvider.Close + st, err := ctl.Restore(context.Background(), "v2", false) + if err != nil || st.Running || st.Phase != RestoreFailed { + t.Fatalf("status after the owner closed: %+v %v, want a finished failed run", st, err) + } + if _, ok, _ := cat.ReadIndependence(context.Background(), "v2"); ok { + t.Fatal("a marker was published after the owner closed") + } +} + var _ RestoreProvider = (*durable.DurableProvider)(nil) diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go index 34e981ea67..bed6e2297b 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all_test.go +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -411,15 +411,47 @@ func TestHydrateAll_StatsReportAbsentChunks(t *testing.T) { // at least (8-1)/4 s. func TestHydrateAll_PacedByByteRate(t *testing.T) { fastWalker(t) - _, layer, _, _ := hydrationFixture(t, 2, 64) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + budget := &timedBudget{} + layer.cfg.Budget = budget // admission times witness the pace rate := int64(4 * ctChunkBytes) - start := time.Now() p, err := layer.HydrateAllAt(boundedCtx(t, context.Background()), rate) - took := time.Since(start) - if err != nil || p.Remaining != 0 { - t.Fatalf("paced walk: %+v %v", p, err) + want := ctNumBlocks / ctChunkBlocks + if err != nil || p.Remaining != 0 || p.Filled != want { + t.Fatalf("paced walk: %+v %v, want all %d chunks filled", p, err, want) } - if min := time.Duration(p.Filled-1) * time.Second / 4; took < min { - t.Fatalf("%d fills at %d B/s took %v, want at least %v", p.Filled, rate, took, min) + gets := 0 + for _, n := range countGets(remote) { + gets += n + } + if gets != want { + t.Fatalf("%d remote Gets, want %d", gets, want) + } + budget.mu.Lock() + defer budget.mu.Unlock() + if len(budget.at) != want { + t.Fatalf("%d admissions, want %d", len(budget.at), want) + } + for i := 1; i < len(budget.at); i++ { + // fill i is admitted no earlier than i chunks at the rate from the start + due := budget.at[0].Add(time.Duration(i) * time.Second / 4) + if budget.at[i].Before(due.Add(-10 * time.Millisecond)) { + t.Fatalf("fill %d admitted %v after the first, before its pace time %v", i, budget.at[i].Sub(budget.at[0]), due.Sub(budget.at[0])) + } } } + +// timedBudget admits every fill and records when. +type timedBudget struct { + mu sync.Mutex + at []time.Time +} + +func (b *timedBudget) Admit(context.Context, int64, func(error)) (uint64, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.at = append(b.at, time.Now()) + return uint64(len(b.at)), nil +} +func (b *timedBudget) ReserveCOW(uint64, int64) error { return nil } +func (b *timedBudget) Release(uint64) {} diff --git a/seaweed-block/core/storage/chunk_own.go b/seaweed-block/core/storage/chunk_own.go index 5f9188f8b4..6b004e08ee 100644 --- a/seaweed-block/core/storage/chunk_own.go +++ b/seaweed-block/core/storage/chunk_own.go @@ -17,7 +17,8 @@ type OwnProgress struct { // OwnBatch runs one bounded cut (M6.Restore.Owning>Owning): it picks up to n // chunks, lowest index first, whose HEAD key is foreign (foreign reports -// whether a key names another volume's object) and that are local, and cuts +// whether a key names another volume's object) and that are local (present, +// or every block written locally), and cuts // with them as candidates: each is uploaded under a new own key under the // cut's intent and published by the cut's one HEAD CAS, even when its bytes // equal HEAD's. Absent chunks are skipped (never fetched by the cut). The cut @@ -30,7 +31,7 @@ func (l *chunkLayerImpl) OwnBatch(ctx context.Context, n int, foreign func(key s l.stMu.Lock() var picked []uint64 for _, idx := range sortedForeign(l.head.Chunks, foreign) { - if len(picked) < n && !l.absent[idx] { + if len(picked) < n && l.chunkLocalLocked(idx) { picked = append(picked, idx) } } @@ -42,6 +43,12 @@ func (l *chunkLayerImpl) OwnBatch(ctx context.Context, n int, foreign func(key s l.own = make(map[uint64]bool, len(picked)) for _, idx := range picked { l.own[idx] = true + // A payload remembered from an earlier failed cut that matched HEAD + // was never uploaded (no key, data discarded): reusing it would skip + // the re-own upload. Drop it, so this cut reads and uploads the chunk. + if sc, ok := l.reusable[idx]; ok && sc.key == "" { + delete(l.reusable, idx) + } } l.stMu.Unlock() _, err := l.captureLocked(ctx, false) @@ -69,7 +76,7 @@ func (l *chunkLayerImpl) ownProgressLocked(foreign func(string) bool) ownCount { c := ownCount{head: l.head.Chunks} for _, idx := range sortedForeign(l.head.Chunks, foreign) { c.Remaining++ - if l.absent[idx] { + if !l.chunkLocalLocked(idx) { c.NotLocal++ } } @@ -100,12 +107,32 @@ func (l *chunkLayerImpl) owning(idx uint64) bool { // Caller holds stMu. func (l *chunkLayerImpl) addOwnCandidatesLocked(out map[uint64]bool) { for idx := range l.own { - if !l.absent[idx] { + if l.chunkLocalLocked(idx) { out[idx] = true } } } +// chunkLocalLocked reports whether a re-own can read chunk idx without a +// fetch: it is present, or absent with every block written locally (a guest +// overwrite flushed before the walker reached it). Caller holds stMu. +func (l *chunkLayerImpl) chunkLocalLocked(idx uint64) bool { + if !l.absent[idx] { + return true + } + 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 false + } + } + return true +} + // unchangedFromHead reports whether a captured chunk equals HEAD's and was // not uploaded: such a chunk keeps its HEAD ref. A re-owned chunk equal to // HEAD was uploaded by streamCutPayloads under a new own key (c.key set), so diff --git a/seaweed-block/core/storage/chunk_own_test.go b/seaweed-block/core/storage/chunk_own_test.go index fa986a0df5..a1a902d597 100644 --- a/seaweed-block/core/storage/chunk_own_test.go +++ b/seaweed-block/core/storage/chunk_own_test.go @@ -3,8 +3,10 @@ package storage import ( "bytes" "context" + "errors" "strings" "testing" + "time" ) func seedForeign(key string) bool { return strings.HasPrefix(key, "seed/") } @@ -94,3 +96,97 @@ func TestOwnBatch_CarriesGuestWrites(t *testing.T) { t.Fatal("the guest write did not reach HEAD with the batch") } } + +// A chunk whose every block the guest overwrote and flushed before the walker +// reached it stays absent but is fully local: a batch owns it with no fetch +// (codex01 #340 S1: otherwise nothing ever cuts it and the driver stalls). +func TestOwnBatch_OwnsAFullyOverwrittenAbsentChunkWithoutAFetch(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + const idx = 3 + for i := uint32(0); i < ctChunkBlocks; i++ { + if _, err := s.Write(idx*ctChunkBlocks+i, makeBlock(ctBlockSize, 0xC0+byte(i))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + layer.stMu.Lock() + absent := layer.absent[idx] + layer.stMu.Unlock() + if !absent { + t.Fatal("fixture: the overwritten chunk must still be absent") + } + if _, err := layer.HydrateAll(ownCtx(t)); err != nil { + t.Fatal(err) + } + seedKey := remote.stats().head.Chunks[idx].Key + // The stall needs this chunk to be the only foreign one left: then no + // other pick triggers the cut that would carry its guest write. + onlyThis := func(key string) bool { return key == seedKey } + p, err := layer.OwnBatch(ownCtx(t), 3, onlyThis) + if err != nil || p.Owned != 1 || p.Remaining != 0 { + t.Fatalf("batch with only the fully overwritten chunk foreign: %+v %v, want it owned", p, err) + } + if n := countGets(remote)[seedKey]; n != 0 { + t.Fatalf("the fully overwritten chunk was fetched %d times", n) + } + img := remote.imageOf(t, remote.stats().head) + for i := 0; i < ctChunkBlocks; i++ { + off := (idx*ctChunkBlocks + i) * ctBlockSize + if !bytes.Equal(img[off:off+ctBlockSize], makeBlock(ctBlockSize, 0xC0+byte(i))) { + t.Fatalf("block %d of the overwritten chunk is not the guest's in HEAD", i) + } + } +} + +// A failed ordinary cut remembers an equal-to-HEAD chunk without a key; the +// next batch must still upload it under an own key (codex01 #340 S2). +func TestOwnBatch_UploadsAChunkRememberedEqualByAFailedCut(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + if _, err := layer.HydrateAll(ownCtx(t)); err != nil { + t.Fatal(err) + } + same := makeBlock(ctBlockSize, 0x40) // block 0 rewritten with HEAD's own bytes + if _, err := s.Write(0, same); err != nil { + t.Fatal(err) + } + if _, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0xEE)); err != nil { // chunk 1 changed + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + remote.mu.Lock() + remote.failPut = errors.New("test: put refused") + remote.mu.Unlock() + failCtx, cancelFail := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancelFail() + if _, err := layer.Cut(failCtx); err == nil { + t.Fatal("fixture: the ordinary cut must fail") + } + remote.mu.Lock() + remote.failPut = nil + remote.mu.Unlock() + layer.stMu.Lock() + sc, kept := layer.reusable[0] + layer.stMu.Unlock() + if !kept || sc.key != "" { + t.Fatalf("fixture: the failed cut must remember chunk 0 equal and keyless: kept=%v key=%q", kept, sc.key) + } + p, err := layer.OwnBatch(ownCtx(t), 1, seedForeign) + if err != nil || p.Owned != 1 { + t.Fatalf("batch after the failed cut: %+v %v, want chunk 0 owned", p, err) + } + if k := remote.stats().head.Chunks[0].Key; seedForeign(k) { + t.Fatalf("chunk 0 still names the foreign key %s", k) + } + if !bytes.Equal(remote.imageOf(t, remote.stats().head)[:ctBlockSize], same) { + t.Fatal("chunk 0's bytes changed") + } +} diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index c537e968ec..31935923de 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -187,7 +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`. +- **Restore** (`Catalog.Restore`, independent restore): the fork steps with `VOLUME` origin `restore`; until its first HEAD the parent stays rooted by GC's grace after any delete, 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. 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`); @@ -240,9 +240,9 @@ 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) + [*] --> Forking: read the parent snapshot, write VOLUME (origin restore) + Forking --> Restoring: first HEAD (parent's refs, owner-qualified) before read time + deadline + Forking --> Aborted: GC tombstones the HEAD Restoring --> Hydrating: driver starts the paced walker Hydrating --> Owning: batch cuts start (the walker may still run) Owning --> Owning: one bounded batch cut replaces up to N foreign refs with own keys From ef9155e6607714a53c3f253bd4c741039a735b50 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 02:48:26 -0800 Subject: [PATCH 6/9] test: give the failing-cut fixture 2 s (300 ms was tight on a loaded runner) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_own_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_own_test.go b/seaweed-block/core/storage/chunk_own_test.go index a1a902d597..75e8496a76 100644 --- a/seaweed-block/core/storage/chunk_own_test.go +++ b/seaweed-block/core/storage/chunk_own_test.go @@ -165,7 +165,7 @@ func TestOwnBatch_UploadsAChunkRememberedEqualByAFailedCut(t *testing.T) { remote.mu.Lock() remote.failPut = errors.New("test: put refused") remote.mu.Unlock() - failCtx, cancelFail := context.WithTimeout(context.Background(), 300*time.Millisecond) + failCtx, cancelFail := context.WithTimeout(context.Background(), 2*time.Second) defer cancelFail() if _, err := layer.Cut(failCtx); err == nil { t.Fatal("fixture: the ordinary cut must fail") From 7fa772b97596242fb9ba26eec011e2a33f093709 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 03:08:35 -0800 Subject: [PATCH 7/9] test fold: pace origin before the call, GoOwned held settlement, owner-close teardown order - The pacing test measures each admission from a time taken before the call, a lower bound of the walker's own start, keeping the exact 8 fills, Gets and admissions. - The GoOwned test bounds every wait, pre-registers release and a bounded join of Close, and witnesses that Close does not return while the owned goroutine is held after its ctx ended (no sleep). - The owner-close driver test releases the held provider call before the owner's join at teardown, so its red case cannot leave a worker behind. Co-Authored-By: Claude Opus 5.5 --- .../frontend/durable/provider_restore_test.go | 45 +++++++++++++------ .../core/host/volume/chunk_restore_test.go | 5 ++- .../core/storage/chunk_hydrate_all_test.go | 10 +++-- 3 files changed, 42 insertions(+), 18 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_restore_test.go b/seaweed-block/core/frontend/durable/provider_restore_test.go index 63cc0ab70f..f52f111b48 100644 --- a/seaweed-block/core/frontend/durable/provider_restore_test.go +++ b/seaweed-block/core/frontend/durable/provider_restore_test.go @@ -10,34 +10,53 @@ import ( ) // A goroutine started with GoOwned sees its ctx end when Close starts, and -// Close returns only after it has returned; after Close nothing is admitted. +// Close does not return while it is still settling; after Close nothing is +// admitted. func TestDurableProvider_GoOwnedIsCancelledAndJoinedByClose(t *testing.T) { p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 64}, v1View()) if err != nil { t.Fatal(err) } - started, finished := make(chan struct{}), make(chan struct{}) + started, cancelled, release := make(chan struct{}), make(chan struct{}), make(chan struct{}) + closed := make(chan struct{}) + released := false + t.Cleanup(func() { // registered before launch: release, then a bounded join of Close + if !released { + close(release) + } + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Error("cleanup: Close did not return") + } + }) if err := p.GoOwned(func(ctx context.Context) { close(started) <-ctx.Done() - time.Sleep(20 * time.Millisecond) // still settling when Close is called - close(finished) + close(cancelled) + <-release // held settlement: Close must wait for this }); err != nil { t.Fatal(err) } - <-started - closed := make(chan struct{}) + wait := func(ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(5 * time.Second): + t.Fatalf("timed out waiting for %s", what) + } + } + wait(started, "the owned goroutine to start") go func() { _ = p.Close(); close(closed) }() + wait(cancelled, "Close to cancel the owned goroutine's ctx") select { case <-closed: - select { - case <-finished: - default: - t.Fatal("Close returned before the owned goroutine finished") - } - case <-time.After(5 * time.Second): - t.Fatal("Close did not return") + t.Fatal("Close returned while the owned goroutine was still settling") + default: } + released = true + close(release) + wait(closed, "Close to return after the owned goroutine returned") if err := p.GoOwned(func(context.Context) {}); !errors.Is(err, durable.ErrProviderClosed) { t.Fatalf("GoOwned after Close: %v, want ErrProviderClosed", err) } diff --git a/seaweed-block/core/host/volume/chunk_restore_test.go b/seaweed-block/core/host/volume/chunk_restore_test.go index 17b264e38a..d70420b8b4 100644 --- a/seaweed-block/core/host/volume/chunk_restore_test.go +++ b/seaweed-block/core/host/volume/chunk_restore_test.go @@ -368,7 +368,10 @@ func TestRestoreDriver_ChunkControlStartsOneRunAndReportsIt(t *testing.T) { func TestRestoreDriver_OwnerCloseCancelsAndJoinsTheRun(t *testing.T) { _, cat, p := restoreFixtureHost(t, 3) owner := newTestOwner(t) - p.entered, p.gate = make(chan struct{}, 1), make(chan struct{}) // gate never opens + p.entered, p.gate = make(chan struct{}, 1), make(chan struct{}) // opened only at teardown + // Registered after the owner: it runs first, so a run that ignored the + // owner's cancel (the red case) is released before the owner's join. + t.Cleanup(func() { close(p.gate) }) ctl := &chunkControl{p: restoreOnlyProvider{p, owner}, cat: cat} if _, err := ctl.Restore(context.Background(), "v2", true); err != nil { t.Fatal(err) diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go index bed6e2297b..9efd0c2d57 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all_test.go +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -415,6 +415,7 @@ func TestHydrateAll_PacedByByteRate(t *testing.T) { budget := &timedBudget{} layer.cfg.Budget = budget // admission times witness the pace rate := int64(4 * ctChunkBytes) + origin := time.Now() // a lower bound of the walker's own pace start p, err := layer.HydrateAllAt(boundedCtx(t, context.Background()), rate) want := ctNumBlocks / ctChunkBlocks if err != nil || p.Remaining != 0 || p.Filled != want { @@ -433,10 +434,11 @@ func TestHydrateAll_PacedByByteRate(t *testing.T) { t.Fatalf("%d admissions, want %d", len(budget.at), want) } for i := 1; i < len(budget.at); i++ { - // fill i is admitted no earlier than i chunks at the rate from the start - due := budget.at[0].Add(time.Duration(i) * time.Second / 4) - if budget.at[i].Before(due.Add(-10 * time.Millisecond)) { - t.Fatalf("fill %d admitted %v after the first, before its pace time %v", i, budget.at[i].Sub(budget.at[0]), due.Sub(budget.at[0])) + // fill i is admitted no earlier than i chunks at the rate after the + // walker started, and the walker started after origin + due := origin.Add(time.Duration(i) * time.Second / 4) + if budget.at[i].Before(due) { + t.Fatalf("fill %d admitted %v after the call, before its pace time %v", i, budget.at[i].Sub(origin), due.Sub(origin)) } } } From daad372367ff7a310c3c818009240102cbc93e8c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 03:18:11 -0800 Subject: [PATCH 8/9] test fold: GoOwned ordering witness and a once-only Close in cleanup The test records the owned goroutine's settlement and Close's return with sequence numbers and requires settlement first; before releasing it gives a Close that does not join 200 ms to return while the goroutine is held. One Close launcher (sync.OnceFunc) serves the body and the pre-registered cleanup, which always cancels, releases and joins, also when GoOwned or the start wait fails. Co-Authored-By: Claude Opus 5.5 --- .../frontend/durable/provider_restore_test.go | 62 ++++++++++++------- 1 file changed, 40 insertions(+), 22 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_restore_test.go b/seaweed-block/core/frontend/durable/provider_restore_test.go index f52f111b48..5f57567ab5 100644 --- a/seaweed-block/core/frontend/durable/provider_restore_test.go +++ b/seaweed-block/core/frontend/durable/provider_restore_test.go @@ -3,6 +3,8 @@ package durable_test import ( "context" "errors" + "sync" + "sync/atomic" "testing" "time" @@ -10,20 +12,26 @@ import ( ) // A goroutine started with GoOwned sees its ctx end when Close starts, and -// Close does not return while it is still settling; after Close nothing is -// admitted. +// Close returns only after it has returned (ordering witnessed by sequence +// numbers); after Close nothing is admitted. func TestDurableProvider_GoOwnedIsCancelledAndJoinedByClose(t *testing.T) { p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 64}, v1View()) if err != nil { t.Fatal(err) } - started, cancelled, release := make(chan struct{}), make(chan struct{}), make(chan struct{}) - closed := make(chan struct{}) - released := false - t.Cleanup(func() { // registered before launch: release, then a bounded join of Close - if !released { - close(release) - } + var seq, settledAt, closedAt atomic.Int64 + started, cancelled, release, closed := make(chan struct{}), make(chan struct{}), make(chan struct{}), make(chan struct{}) + releaseOnce := sync.OnceFunc(func() { close(release) }) + startClose := sync.OnceFunc(func() { // one Close, launched by the body or by cleanup + go func() { + _ = p.Close() + closedAt.Store(seq.Add(1)) + close(closed) + }() + }) + t.Cleanup(func() { // registered before launch: always cancels, releases and joins + startClose() + releaseOnce() select { case <-closed: case <-time.After(5 * time.Second): @@ -35,28 +43,38 @@ func TestDurableProvider_GoOwnedIsCancelledAndJoinedByClose(t *testing.T) { <-ctx.Done() close(cancelled) <-release // held settlement: Close must wait for this + settledAt.Store(seq.Add(1)) }); err != nil { t.Fatal(err) } - wait := func(ch <-chan struct{}, what string) { + wait := func(ch <-chan struct{}, d time.Duration, what string) bool { t.Helper() select { case <-ch: - case <-time.After(5 * time.Second): - t.Fatalf("timed out waiting for %s", what) + return true + case <-time.After(d): + return false } } - wait(started, "the owned goroutine to start") - go func() { _ = p.Close(); close(closed) }() - wait(cancelled, "Close to cancel the owned goroutine's ctx") - select { - case <-closed: - t.Fatal("Close returned while the owned goroutine was still settling") - default: + if !wait(started, 5*time.Second, "start") { + t.Fatal("the owned goroutine never started") + } + startClose() + if !wait(cancelled, 5*time.Second, "cancel") { + t.Fatal("Close did not cancel the owned goroutine's ctx") + } + // Adverse schedule for a Close that does not join: give it time to + // return while the goroutine is still held. + if wait(closed, 200*time.Millisecond, "early close") { + t.Fatal("Close returned while the owned goroutine was still held") + } + releaseOnce() + if !wait(closed, 5*time.Second, "close") { + t.Fatal("Close did not return after the owned goroutine returned") + } + if s, c := settledAt.Load(), closedAt.Load(); s == 0 || c <= s { + t.Fatalf("Close returned (seq %d) before the owned goroutine settled (seq %d)", c, s) } - released = true - close(release) - wait(closed, "Close to return after the owned goroutine returned") if err := p.GoOwned(func(context.Context) {}); !errors.Is(err, durable.ErrProviderClosed) { t.Fatalf("GoOwned after Close: %v, want ErrProviderClosed", err) } From 827cec9752177e4c284c44f3de7b1c83032a52da Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 05:20:09 -0800 Subject: [PATCH 9/9] docs: restore the S11 ForkDelete row dropped in the merge (verbatim from main) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/spec/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 9a280f9a02..2dee559ccc 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -119,6 +119,7 @@ length of TLC's shortest counterexample. | 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: fork of a sealed snapshot, hydrate, bounded batch cuts (own fids uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref; GC, source delete, snapshot retention, and crashes with resume from remote facts at any point. `NoClaim` (the code): no claim; the fork window is safe by two time rules on one clock, ForkEnd only while now < readAt + D and a deleted snapshot rooted while now < delAt + G. The older claim variants stay as regression configurations. | `NoGap`, `Independent`, `NoForeignList`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)**, no-claim: `nc_safe` 405,198 distinct states; `nc_safe_b2` 504,097; `nc_safe_n4` 2,752,518; `nc_safe_G3D2` 379,500; boundary `nc_bnd_G1D1` 444,564 and `nc_bnd_G3D3` 360,615 safe, `nc_bnd_G0D1` and `nc_bnd_G2D3` violate NoGap: safe iff G >= D on one clock, which is `ForkDelete`'s G >= D + E + P with E = P = 0 (the production inequality is ForkDelete's). **RED** (each violated): `nc_red_CasBeforeUpload`, `nc_red_NoIntent`, `nc_red_GltD`, `nc_red_noDeadline`, `nc_red_notRooted`, `nc_red_resumeNoReread` NoGap; `nc_red_MarkerEarly`, `nc_red_MarkerBeforeCas`, `nc_red_SnapDuringRestore` Independent; `nc_red_ListForeign` NoForeignList; `nc_red_ResumeLocal` StateRemote. **Witnesses reached:** `nc_wit_DelInFork` (the source snapshot deleted inside the fork window and the restore completes), `nc_wit_FailNotFound`. Regression (claim frame): `safe` 1,599, `opt1_safe` 3,639, `oldframe` 1,599 safe; `oldframe_drop`, `red_DropClaimAtFork_gap` violate NoGap. Limits: no guest writes to the target while it takes ownership, GC acts immediately, one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAllAt`; `core/storage/chunk_own.go` `OwnBatch`; `core/host/volume/chunk_restore.go` `runRestore` | +| S11 | `ForkDelete` | Fork or restore against snapshot delete with no claim: the fork reads the parent, may crash and retry (a retry re-reads it), and publishes only before its read time + D, as one atomic step or check-then-publish with up to P ticks between; delete stamps its time; GC (one atomic step) keeps a deleted attempt rooted while its clock is below delete time + G. Three clocks with pairwise skew up to E. | `NoGap` (a published fork HEAD names only existing chunks) | **Exhaustive (TLC breadth-first, complete state graph, no error)**: all 11 safe cfgs, from `safe_D2E0G2` (18,672 distinct states) to `safe_na_P2_D1E2G5` (15,730,209), including every boundary G = D + E + P (atomic and two-step, NC = 2). **RED**, each violating NoGap: the boundary minus one (`red_bnd_*`, `red_na_P*`), `red_noDeadlineCheck`, `red_deletedNotRooted`, `red_noRetryReread`. **Witnesses reached:** `wit_benefit`, `wit_benefit_na_P1`, `wit_deadlineLoss`, `wit_gcDeletes`, `wit_retryNotFound`. Safe iff G >= D + E + P. | `core/frontend/chunkstore/catalog.go` `Fork` (deadline start before `readForkParent`, publish before start + deadline); `retention.go` `markDeleting` (no claim); `gc.go` `NewCollector` (grace >= deadline + skew + CAS apply bound); `gc_copy.go` `snapshotAttemptHeads` (deleted attempt rooted for grace) | ## Limits