From 88aea4c7ed8a03526d596822c393ef28fafb7368 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:23:53 -0800 Subject: [PATCH] restore: fold review of part A (fill permit, permit ownership, stale snapshot image, docs) - HydrateAll admits each fill as a background fill permit with no cut payload (the real limiter refuses a payload for BackgroundFill, so no fill ever ran), and the permit now belongs to the flight: the walker queues the shared flight without becoming a waiter and a layer-owned goroutine releases the permit when the flight's I/O is over (new settled signal, closed by the worker after fillOnce or when an unrun flight is removed), also after an early return on cancel, revocation or close. The limiter's abort callback stops the walker. The flight lookup is factored into hydrationFlightLocked (shared with OnReadMissContext, no behaviour change there). - CreateSnapshot on a restore volume also checks the supplied image: a cut saved before the marker that still names another volume's chunks is refused. - dropIntent keeps outliving the caller's cancellation but is bounded by dropIntentTimeout (it had no deadline at all). - Tests: the real hostlimit limiter (fill permits, payload 0, all released), permit held while a cancelled walker's Get is held, revocation, a witnessed pause for guests, cancel returning while the Get is held, bounded joins; stale pre-independence image refused; aborted first HEAD keeps the parent as fork_parent until the target is deleted; dropIntent bounded. - Docs: invariants.md M4/M6 rows and INV-RESTORE-* rows, GC owner rooting recorded as load-bearing in INV-GC-REACHABLE-001; restore diagram in the workspace design; RestoreIndependence in docs/spec/README.md (simulation). Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 18 +- .../core/frontend/chunkstore/restore.go | 31 +- .../core/frontend/chunkstore/restore_test.go | 111 ++++++++ .../core/storage/chunk_hydrate_all.go | 135 +++++++-- .../core/storage/chunk_hydrate_all_test.go | 264 +++++++++++++++--- seaweed-block/core/storage/chunk_hydration.go | 81 ++++-- seaweed-block/core/storage/chunk_layer.go | 1 + .../docs/design/agent-workspace-design.md | 18 +- seaweed-block/docs/design/invariants.md | 12 +- seaweed-block/docs/spec/README.md | 2 + 10 files changed, 555 insertions(+), 118 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index c4ca9e9b8b..a9d0553b6e 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -753,11 +753,18 @@ func (c *Catalog) AbortSnapshot(ctx context.Context, vol, name, attempt string) // is confirmed or can never apply. It never touches another attempt's // intent, even under the same operation: an earlier attempt's create may // still be held by the server and land later (W5 rule). A failed delete -// leaves the intent, which only over-protects. +// leaves the intent, which only over-protects. The delete outlives the +// caller's cancellation (cleanup after a refused or cancelled request) but is +// bounded by dropIntentTimeout, so it can never hang on an unresponsive filer. func (c *Catalog) dropIntent(ctx context.Context, root, id string) { - _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(root, intentsDir), id, nil) + dctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dropIntentTimeout) + defer cancel() + _ = c.f.DeleteEntry(dctx, path.Join(root, intentsDir), id, nil) } +// dropIntentTimeout bounds one intent delete (a var so tests can shorten it). +var dropIntentTimeout = 30 * time.Second + type createOutcome int const ( @@ -873,6 +880,13 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe } else if !independent { return SnapshotInfo{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s is still being restored: snapshots are refused until it is independent", vol) } + // The supplied image need not be the current HEAD: a cut taken before + // the marker may still name the source's chunks. Check the image itself. + if q, err := c.foreignRefsOf(ctx, vol, head); err != nil { + return SnapshotInfo{}, err + } else if q > 0 { + return SnapshotInfo{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s: snapshot image gen %d holds %d refs to another volume", vol, head.Gen, q) + } } // Take the name: this request's record, or an earlier attempt's of it. diff --git a/seaweed-block/core/frontend/chunkstore/restore.go b/seaweed-block/core/frontend/chunkstore/restore.go index 4ba43e7b6a..22a12d1f83 100644 --- a/seaweed-block/core/frontend/chunkstore/restore.go +++ b/seaweed-block/core/frontend/chunkstore/restore.go @@ -88,20 +88,11 @@ func (c *Catalog) MarkIndependent(ctx context.Context, vol string) (RestoreIndep if !has || h.State == storage.ChunkHeadAborted || headDeletingOrDeleted(h) { return RestoreIndependence{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s has no live HEAD", vol) } - // The manifest segments name chunk refs too: check the resolved HEAD (every - // segment key and every chunk ref inside), as GC and usage resolve it. - if c.blobs == nil { - return RestoreIndependence{}, errors.New("chunkstore: restore marker needs the segment reader") - } - r, err := NewChunkRemote(c.f, c.blobs, path.Join(c.base, vol)) + q, err := c.foreignRefsOf(ctx, vol, h) if err != nil { return RestoreIndependence{}, err } - resolved, err := r.resolveManifest(ctx, h) - if err != nil { - return RestoreIndependence{}, remoteErr(err, "resolve HEAD of %s", vol) - } - if q := ForeignRefs(resolved, vol); q > 0 { + if q > 0 { return RestoreIndependence{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s: HEAD gen %d still holds %d refs to another volume", vol, h.Gen, q) } m := RestoreIndependence{Format: volumeFormat, VolumeID: vol, HeadGen: h.Gen, MarkedNs: c.now().UnixNano()} @@ -152,3 +143,21 @@ func (c *Catalog) ReadIndependence(ctx context.Context, vol string) (RestoreInde } return m, true, nil } + +// foreignRefsOf counts the refs to other volumes in image h of vol, resolved: +// the manifest segments name chunk refs too, so every segment key and every +// chunk ref inside is checked, as GC and usage resolve it. +func (c *Catalog) foreignRefsOf(ctx context.Context, vol string, h storage.ChunkHead) (int, error) { + if c.blobs == nil { + return 0, errors.New("chunkstore: restore independence needs the segment reader") + } + r, err := NewChunkRemote(c.f, c.blobs, path.Join(c.base, vol)) + if err != nil { + return 0, err + } + resolved, err := r.resolveManifest(ctx, h) + if err != nil { + return 0, remoteErr(err, "resolve gen %d of %s", h.Gen, vol) + } + return ForeignRefs(resolved, vol), nil +} diff --git a/seaweed-block/core/frontend/chunkstore/restore_test.go b/seaweed-block/core/frontend/chunkstore/restore_test.go index b30af27438..6959ac850b 100644 --- a/seaweed-block/core/frontend/chunkstore/restore_test.go +++ b/seaweed-block/core/frontend/chunkstore/restore_test.go @@ -291,3 +291,114 @@ func TestRestore_SnapshotsRefusedUntilIndependent(t *testing.T) { t.Fatalf("a snapshot of an independent restore names %d foreign refs", ForeignRefs(s.Head(), "v2")) } } + +// hangingDeleteFiler blocks DeleteEntry until its ctx ends and records whether +// that ctx carried a deadline. +type hangingDeleteFiler struct { + Filer + hadDeadline chan bool +} + +func (h hangingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { + _, ok := ctx.Deadline() + h.hadDeadline <- ok + <-ctx.Done() + return ctx.Err() +} + +// dropIntent outlives a cancelled caller, but one unresponsive delete must still be bounded. +func TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled(t *testing.T) { + old := dropIntentTimeout + dropIntentTimeout = 50 * time.Millisecond + t.Cleanup(func() { dropIntentTimeout = old }) + h := hangingDeleteFiler{Filer: newFakeFiler(), hadDeadline: make(chan bool, 1)} + c := &Catalog{f: h} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + done := make(chan struct{}) + go func() { c.dropIntent(ctx, "/vols/v1", "op-1"); close(done) }() + select { + case ok := <-h.hadDeadline: + if !ok { + t.Fatal("the intent delete ran without any deadline") + } + case <-time.After(5 * time.Second): + t.Fatal("dropIntent never reached the filer") + } + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("dropIntent did not return: the delete is unbounded") + } +} + +// A cut image saved before the marker still names the source's chunks: the +// marker must not let it become a snapshot. +func TestRestore_SnapshotOfAStalePreIndependenceImageRefused(t *testing.T) { + f, b, c, _ := restoreFixture(t) + ctx := context.Background() + r2, _ := NewChunkRemote(f, b, catBase+"/v2") + stale, _ := r2.GetHead(ctx) + h := ownAll(t, f, b, "v2") + if _, err := c.MarkIndependent(ctx, "v2"); err != nil { + t.Fatal(err) + } + req := SnapshotRequest{Name: "stale", RequestID: "s"} + if _, err := c.CreateSnapshot(ctx, "v2", req, stale); CodeOf(err) != CodeRestoreIncomplete { + t.Fatalf("stale foreign image after the marker: %v, want %s", err, CodeRestoreIncomplete) + } + if _, ok, err := c.SnapshotReplay(ctx, "v2", req); err != nil || ok { + t.Fatalf("a refused snapshot must leave nothing: ok=%v err=%v", ok, err) + } + if list, _, err := c.ListSnapshots(ctx, "v2", ListOptions{}); err != nil || len(list) != 0 { + t.Fatalf("snapshots after the refusal: %v %v", list, err) + } + if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "own", RequestID: "o"}, h); err != nil { + t.Fatalf("the own image must still be accepted: %v", err) + } +} + +// Retention disposition with an aborted first HEAD on a restore target: the +// fork claim alone no longer holds the parent (liveClaims counts any HEAD, +// aborted included), but the fork-record scan does (forkParentsNeeded treats +// an aborted HEAD as no HEAD), so the parent snapshot is kept as fork_parent +// until the aborted target is deleted. That conservative hold is the rule. +func TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted(t *testing.T) { + f, c, _, _ := retentionFixture(t, 1) + ctx := context.Background() + if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy + t.Fatal(err) + } + for _, vol := range []string{"v1", "v2"} { + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + } + holdFirst(f, catBase+"/v2/HEAD") + if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s00", Target: "v2", RequestID: "rs"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("restore with a held HEAD create: %v", err) + } + if claimed, err := c.AbortFork(ctx, "v2"); err != nil || !claimed { + t.Fatalf("abort the unpublished restore: claimed=%v %v", claimed, err) + } + if live, err := c.liveClaims(ctx, "v1", "s00", []string{forkClaim("v2", "rs")}); err != nil || len(live) != 0 { + t.Fatalf("claim on an aborted target: live=%v %v, want not live (any HEAD ends the claim)", live, err) + } + res, err := c.Retain(ctx, "v1", false) + if err != nil { + t.Fatal(err) + } + if k := kept(res.Decisions); len(k) != 1 || k["s00"] == nil || k["s00"][0] != keepForkParent || len(res.Deleted) != 0 { + t.Fatalf("aborted restore: kept %v deleted %v; want s00 kept as fork_parent", k, res.Deleted) + } + if s, err := c.allSnapshots(ctx, "v1"); err != nil || len(s) != 1 { + t.Fatalf("parent after retention: %v %v", s, err) + } + if _, err := c.DeleteVolume(ctx, "v2", nil); err != nil { + t.Fatalf("delete the aborted restore: %v", err) + } + res, err = c.Retain(ctx, "v1", false) + if err != nil || len(res.Deleted) != 1 || res.Deleted[0] != "s00" { + t.Fatalf("after the target is gone: deleted %v (%v), want s00", res.Deleted, err) + } +} diff --git a/seaweed-block/core/storage/chunk_hydrate_all.go b/seaweed-block/core/storage/chunk_hydrate_all.go index 094ec50b24..01f9ad5ea2 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all.go +++ b/seaweed-block/core/storage/chunk_hydrate_all.go @@ -3,6 +3,7 @@ package storage import ( "context" "errors" + "sync" "time" ) @@ -31,14 +32,29 @@ var ( // the absent chunks lowest index first through the same shared fill flights // as guest read misses (one fetch per chunk, the hydration queue bound and // the read-miss timeout apply), so it never fetches a chunk twice or races a -// guest fill. It yields while any flight has guest waiters, and admits each -// fill through the host limiter (cfg.Budget) with ctx: the caller sets the -// limiter class on ctx (hostlimit.WithClass(ctx, hostlimit.BackgroundFill)). -// It returns when nothing is absent, when ctx ends, or on a fill error that -// is not a retryable pending state; the caller may call it again. +// guest fill. It yields while any flight has guest waiters; its own flights +// have no waiters, so workers serve guest flights first. +// +// Each fill holds one host-limiter permit (cfg.Budget), admitted with ctx and +// no cut payload, the background fill/idle contract (hostlimit Acquire): the +// caller sets the class on ctx (hostlimit.WithClass(ctx, +// hostlimit.BackgroundFill)). The permit belongs to the flight, not the wait: +// it is released only when the flight's I/O is over, also when the walker +// returns early on cancellation, revocation or close. The limiter's abort +// callback (revocation) stops the walker, which then returns the cause. +// +// It returns when nothing is absent, when ctx ends or the permit is revoked, +// or on a fill error that is not a retryable pending state; the caller may +// call it again. func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error) { var p HydrateProgress + walk, stop := context.WithCancelCause(ctx) + defer stop(nil) backoff := hydrateAllMinBackoff + quit := func(err error) (HydrateProgress, error) { + p.Remaining = l.absentHydratable() + return p, err + } wait := func() error { t := time.NewTimer(backoff) defer t.Stop() @@ -48,16 +64,15 @@ func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error select { case <-t.C: return nil - case <-ctx.Done(): - return ctx.Err() + case <-walk.Done(): + return context.Cause(walk) case <-l.ctx.Done(): return errChunkLayerClosed } } for { - if err := ctx.Err(); err != nil { - p.Remaining = l.absentHydratable() - return p, err + if walk.Err() != nil { + return quit(context.Cause(walk)) } lba, ok, guests := l.nextHydrateTarget() if !ok { @@ -66,40 +81,97 @@ func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error } if guests > 0 { p.Paused++ + if hook := l.testHydrateAllPause; hook != nil { + hook() + } if err := wait(); err != nil { - p.Remaining = l.absentHydratable() - return p, err + return quit(err) } continue } - release, err := l.admitFill(ctx) + release, err := l.admitFill(walk, stop) if err != nil { p.Deferred++ if err := wait(); err != nil { - p.Remaining = l.absentHydratable() - return p, err + return quit(err) } continue } - _, err = l.OnReadMissContext(ctx, lba) - release() + f, err := l.startWalkerFill(lba, release) + if err != nil { + if errors.Is(err, ErrChunkHydrationPending) { + if err := wait(); err != nil { // queue full: retry later + return quit(err) + } + continue + } + return quit(err) + } + if f == nil { + continue // resolved meanwhile + } + select { + case <-f.done: + case <-walk.Done(): + return quit(context.Cause(walk)) + case <-l.ctx.Done(): + return quit(errChunkLayerClosed) + } + l.stMu.Lock() + changed := l.absentGen[f.idx] != f.gen || l.head.Chunks[f.idx] != f.ref + ferr := f.err + l.stMu.Unlock() switch { - case err == nil: + case changed: + // a newer absence or HEAD: the next pass looks again + case ferr == nil: p.Filled++ backoff = hydrateAllMinBackoff - case errors.Is(err, ErrChunkHydrationPending): - // queue full or the read-miss timeout: retry the same chunk later - if err := wait(); err != nil { - p.Remaining = l.absentHydratable() - return p, err + case errors.Is(ferr, ErrChunkHydrationPending): + if err := wait(); err != nil { // the read-miss timeout: retry later + return quit(err) } default: - p.Remaining = l.absentHydratable() - return p, err + return quit(ferr) } } } +// startWalkerFill queues (or joins) the fill flight of lba's chunk without +// becoming a waiter, and hands the permit's release to the flight's +// settlement: a layer-owned goroutine releases it once the flight's I/O is +// over, whatever the walker does meanwhile. A nil flight means nothing is to +// fetch any more (release already called). +func (l *chunkLayerImpl) startWalkerFill(lba uint64, release func()) (*chunkHydrationFlight, error) { + idx := l.chunkOf(lba) + l.stMu.Lock() + defer l.stMu.Unlock() + if l.closed { + release() + return nil, errChunkLayerClosed + } + ref, named := l.head.Chunks[idx] + if !l.absent[idx] || l.localBlocks[lba] || !named { + release() + return nil, nil + } + f, _, err := l.hydrationFlightLocked(idx, ref) + if err != nil { + release() + return nil, err + } + l.wakeHydrationLocked() + // Close joins wg only after taking stMu and marking closed; every queued + // flight is settled by closeHydrationLocked, every running one by its worker. + l.wg.Add(1) + go func() { + defer l.wg.Done() + <-f.settled + release() + }() + return f, nil +} + // nextHydrateTarget returns a block of the lowest-index chunk that HEAD names, // is absent and has a block without a local extent version (localBlocks: a // chunk whose every block reached the extent needs no fetch; a write still only @@ -157,16 +229,19 @@ func (l *chunkLayerImpl) hydratableBlockLocked(idx uint64) (uint64, bool) { return 0, false } -// admitFill reserves one chunk of fill payload from the host limiter, if -// there is one; the returned release gives it back. -func (l *chunkLayerImpl) admitFill(ctx context.Context) (func(), error) { +// admitFill takes one background permit from the host limiter, if there is +// one: no cut payload (a fill/idle permit carries none and the limiter refuses +// one), the class from ctx. A revocation runs abort, which stops the walker. +// The returned release gives the permit back, once. +func (l *chunkLayerImpl) admitFill(ctx context.Context, abort func(error)) (func(), error) { host := l.cfg.Budget if host == nil { return func() {}, nil } - ticket, err := host.Admit(ctx, int64(l.chunkBlocks)*int64(l.blockSize), func(error) {}) + ticket, err := host.Admit(ctx, 0, abort) if err != nil { return nil, err } - return func() { host.Release(ticket) }, nil + var once sync.Once + return func() { once.Do(func() { host.Release(ticket) }) }, nil } diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go index 9ff3d672e6..b6bec6ebc5 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all_test.go +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -8,6 +8,8 @@ import ( "sync" "testing" "time" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" ) func countGets(r *fakeChunkRemote) map[string]int { @@ -29,6 +31,96 @@ func fastWalker(t *testing.T) { t.Cleanup(func() { hydrateAllMinBackoff, hydrateAllMaxBackoff = minB, maxB }) } +// walkRun is one HydrateAll call on its own goroutine. Its ctx is cancelled +// and its return joined (bounded) at cleanup, registered before launch. +type walkRun struct { + done chan struct{} + cancel context.CancelFunc + p HydrateProgress + err error +} + +func startWalker(t *testing.T, layer *chunkLayerImpl, parent context.Context) *walkRun { + t.Helper() + ctx, cancel := context.WithCancel(parent) + w := &walkRun{done: make(chan struct{}), cancel: cancel} + t.Cleanup(func() { + cancel() + select { + case <-w.done: + case <-time.After(ctLocalBound): + t.Error("cleanup: walker did not return") + } + }) + go func() { + w.p, w.err = layer.HydrateAll(ctx) + close(w.done) + }() + return w +} + +func (w *walkRun) wait(t *testing.T, what string) { + t.Helper() + select { + case <-w.done: + case <-time.After(ctLocalBound): + t.Fatalf("%s: walker did not return", what) + } +} + +func walkerSignal[T any](t *testing.T, ch <-chan T, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(ctLocalBound): + t.Fatalf("timed out waiting for %s", what) + } +} + +// waitUntil polls cond (bounded by ctLocalBound); permits are released +// asynchronously, when each flight settles. +func waitUntil(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(ctLocalBound) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting until %s", what) + } + time.Sleep(time.Millisecond) + } +} + +// fillLimiter is a real host limiter on pool dir with fillSlots fill permits. +func fillLimiter(t *testing.T, dir string, fillSlots int) *hostlimit.Limiter { + t.Helper() + c := hostlimit.DefaultConfig(dir) + c.FillSlots = fillSlots + l, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + t.Cleanup(l.Close) + return l +} + +// payloadRecorder passes admissions to a real Budget and records each payload. +type payloadRecorder struct { + Budget + mu sync.Mutex + payloads []int64 +} + +func (r *payloadRecorder) Admit(ctx context.Context, payload int64, abort func(error)) (uint64, error) { + r.mu.Lock() + r.payloads = append(r.payloads, payload) + r.mu.Unlock() + return r.Budget.Admit(ctx, payload, abort) +} + +func bgFill() context.Context { + return hostlimit.WithClass(context.Background(), hostlimit.BackgroundFill) +} + func TestHydrateAll_FillsEveryChunkOnceAndReadsTheHeadImage(t *testing.T) { fastWalker(t) s, layer, remote, _ := hydrationFixture(t, 2, 64) @@ -86,23 +178,24 @@ func TestHydrateAll_NeverOverwritesALocalWrite(t *testing.T) { } } +// The walker's deferral is witnessed (its pause hook fires) while the guest's +// fetch is held, before anything is allowed to progress. func TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice(t *testing.T) { fastWalker(t) s, layer, remote, registered := hydrationFixture(t, 2, 64) + paused := make(chan struct{}, 1) + layer.testHydrateAllPause = func() { + select { + case paused <- struct{}{}: + default: + } + } entered, release := holdNextGet(t, remote) guest := startHydrationRead(t, s, context.Background(), 5*ctChunkBlocks) waitHydrationRegistration(t, registered, 1) - <-entered // the guest's fetch of chunk 5 is held - type res struct { - p HydrateProgress - err error - } - walked := make(chan res, 1) - go func() { - p, err := layer.HydrateAll(context.Background()) - walked <- res{p, err} - }() - time.Sleep(30 * time.Millisecond) + walkerSignal(t, entered, "the guest's fetch of chunk 5") + w := startWalker(t, layer, context.Background()) + walkerSignal(t, paused, "the walker to yield to the held guest fetch") if n := len(countGets(remote)); n != 1 { t.Fatalf("the walker fetched while a guest was waiting: %d distinct gets", n) } @@ -110,14 +203,9 @@ func TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice(t *testing.T) { if r := hydrationOutcome(t, guest); r.err != nil { t.Fatalf("guest read: %v", r.err) } - var r res - select { - case r = <-walked: - case <-time.After(ctLocalBound): - t.Fatal("walker did not finish") - } - if r.err != nil || r.p.Remaining != 0 || r.p.Paused == 0 || r.p.Filled != ctNumBlocks/ctChunkBlocks-1 { - t.Fatalf("walker: %+v %v, want paused for the guest and the 7 other chunks filled", r.p, r.err) + w.wait(t, "after the guest fill") + if w.err != nil || w.p.Remaining != 0 || w.p.Paused == 0 || w.p.Filled != ctNumBlocks/ctChunkBlocks-1 { + t.Fatalf("walker: %+v %v, want paused for the guest and the 7 other chunks filled", w.p, w.err) } for key, n := range countGets(remote) { if n != 1 { @@ -134,12 +222,14 @@ type walkerBudget struct { admitted int released int classes []any + abort func(error) } -func (b *walkerBudget) Admit(ctx context.Context, _ int64, _ func(error)) (uint64, error) { +func (b *walkerBudget) Admit(ctx context.Context, _ int64, abort func(error)) (uint64, error) { b.mu.Lock() defer b.mu.Unlock() b.classes = append(b.classes, ctx.Value(walkerClassKey{})) + b.abort = abort if b.refuse > 0 { b.refuse-- return 0, errors.New("fill class over budget") @@ -154,6 +244,12 @@ func (b *walkerBudget) Release(uint64) { b.mu.Unlock() } +func (b *walkerBudget) counts() (admitted, released int) { + b.mu.Lock() + defer b.mu.Unlock() + return b.admitted, b.released +} + func TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass(t *testing.T) { fastWalker(t) _, layer, _, _ := hydrationFixture(t, 2, 64) @@ -164,10 +260,11 @@ func TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass(t *testin if err != nil || p.Remaining != 0 || p.Deferred != 2 { t.Fatalf("hydrate all: %+v %v, want 2 deferred then everything filled", p, err) } + waitUntil(t, "every permit is released", func() bool { a, r := budget.counts(); return a == r }) budget.mu.Lock() defer budget.mu.Unlock() - if budget.admitted != p.Filled || budget.released != budget.admitted { - t.Fatalf("budget admitted %d released %d, filled %d: every fill admitted once and released", budget.admitted, budget.released, p.Filled) + if budget.admitted != p.Filled { + t.Fatalf("budget admitted %d, filled %d: every fill admitted once", budget.admitted, p.Filled) } for _, c := range budget.classes { if c != "fill" { @@ -176,30 +273,115 @@ func TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass(t *testin } } -func TestHydrateAll_CancelReturnsTheRemainingCount(t *testing.T) { +func TestHydrateAll_CancelReturnsWhileTheFetchIsHeld(t *testing.T) { fastWalker(t) _, layer, remote, _ := hydrationFixture(t, 2, 64) - entered, release := holdNextGet(t, remote) - defer release() - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan HydrateProgress, 1) - go func() { - p, _ := layer.HydrateAll(ctx) - done <- p - }() - <-entered - cancel() - release() - select { - case p := <-done: - if p.Remaining == 0 { - t.Fatalf("cancelled walk reports nothing remaining: %+v", p) - } - case <-time.After(ctLocalBound): - t.Fatal("cancelled walker did not return") + entered, _ := holdNextGet(t, remote) + w := startWalker(t, layer, context.Background()) + walkerSignal(t, entered, "the walker's first fetch") + w.cancel() + w.wait(t, "cancel with the fetch still held") + if !errors.Is(w.err, context.Canceled) || w.p.Remaining == 0 { + t.Fatalf("cancelled walk: %+v %v, want context.Canceled and chunks remaining", w.p, w.err) } } +// The real limiter refuses a background permit that carries a cut payload: +// every fill must be admitted as a fill permit (no payload) under +// BackgroundFill, fill the HEAD image exactly, and give every permit back. +func TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + lim := fillLimiter(t, t.TempDir(), 2) + rec := &payloadRecorder{Budget: lim} + layer.cfg.Budget = rec + ctx, cancel := context.WithTimeout(bgFill(), ctLocalBound) + defer cancel() + p, err := layer.HydrateAll(ctx) + if err != nil || p.Remaining != 0 || p.Filled != ctNumBlocks/ctChunkBlocks || p.Deferred != 0 { + t.Fatalf("hydrate all under the real limiter: %+v %v", p, err) + } + for b := uint32(0); b < ctNumBlocks; b++ { + if got, err := s.Read(b); err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, byte(0x40+b))) { + t.Fatalf("block %d after hydrate: %v", b, err) + } + } + for key, n := range countGets(remote) { + if n != 1 { + t.Fatalf("chunk %s fetched %d times", key, n) + } + } + rec.mu.Lock() + for _, n := range rec.payloads { + if n != 0 { + t.Fatalf("fill admitted with a %d-byte cut payload", n) + } + } + rec.mu.Unlock() + waitUntil(t, "every fill permit is admitted once and released", func() bool { + st := lim.Snapshot().(hostlimit.Stats) + return st.Admitted == uint64(p.Filled) && st.Released == st.Admitted && st.Active == 0 && st.Skipped == 0 + }) +} + +// The permit follows the owned flight, not the walker's wait: a cancelled +// walker returns at once, but its fill permit stays taken until the held +// physical Get settles. +func TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + dir := t.TempDir() + layer.cfg.Budget = fillLimiter(t, dir, 1) + contender := fillLimiter(t, dir, 1) + entered, release := holdNextGet(t, remote) + w := startWalker(t, layer, bgFill()) + walkerSignal(t, entered, "the walker's fetch") + w.cancel() + w.wait(t, "cancel with the fetch still held") + if !errors.Is(w.err, context.Canceled) { + t.Fatalf("cancelled walk: %v", w.err) + } + if tk, err := contender.Acquire(context.Background(), hostlimit.BackgroundFill, nil); err == nil { + contender.Release(tk) + t.Fatal("the fill permit was free while the walker's Get was still running") + } else if !errors.Is(err, hostlimit.ErrBusy) { + t.Fatalf("contender: %v", err) + } + release() + waitUntil(t, "the permit is free after the Get settled", func() bool { + tk, err := contender.Acquire(context.Background(), hostlimit.BackgroundFill, nil) + if err == nil { + contender.Release(tk) + } + return err == nil + }) +} + +// A limiter revocation (the abort callback) stops the walker with the cause; +// the permit is still released only when the owned fetch settles. +func TestHydrateAll_RevocationStopsTheWalker(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + budget := &walkerBudget{} + layer.cfg.Budget = budget + entered, release := holdNextGet(t, remote) + w := startWalker(t, layer, context.Background()) + walkerSignal(t, entered, "the walker's fetch") + budget.mu.Lock() + abort := budget.abort + budget.mu.Unlock() + abort(hostlimit.ErrRevoked) + w.wait(t, "revocation with the fetch still held") + if !errors.Is(w.err, hostlimit.ErrRevoked) { + t.Fatalf("revoked walk: %v, want ErrRevoked", w.err) + } + if _, r := budget.counts(); r != 0 { + t.Fatal("permit released before the owned fetch settled") + } + release() + waitUntil(t, "the permit is released after the fetch settled", func() bool { _, r := budget.counts(); return r == 1 }) +} + func TestHydrateAll_StatsReportAbsentChunks(t *testing.T) { fastWalker(t) _, layer, _, _ := hydrationFixture(t, 2, 64) diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go index 2291ea22cc..acd4e3f8af 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -34,6 +34,7 @@ type chunkHydrationFlight struct { ctx context.Context cancel context.CancelFunc done chan struct{} + settled chan struct{} // closed once its I/O is over: after fillOnce, or removal unrun running bool waiters int err error @@ -76,39 +77,15 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b l.stMu.Unlock() return nil, hydrationPending(err) } - gen := l.absentGen[idx] - f := l.hydration[idx] - stale := f != nil && (f.gen != gen || f.ref != ref) - if stale { - f.cancel() - // The old worker remains owned and joined, but cannot delay a - // new generation or remove its replacement when it finishes. - delete(l.hydration, idx) - close(f.done) - f = nil + f, joined, err := l.hydrationFlightLocked(idx, ref) + if err != nil { + l.stats.Hydration.WaitRefusals++ + l.stMu.Unlock() + return nil, err } - if f != nil && !stale { + if joined { l.stats.Hydration.Joined++ } - if f == nil { - if len(l.hydration) >= l.cfg.HydrationQueueDepth { - l.stats.Hydration.WaitRefusals++ - l.stMu.Unlock() - return nil, hydrationPending(nil) - } - if !l.hydrationStarted { - l.hydration = make(map[uint64]*chunkHydrationFlight) - l.hydrationWake = make(chan struct{}, 1) - l.hydrationStarted = true - l.wg.Add(l.cfg.HydrationWorkers) - for i := 0; i < l.cfg.HydrationWorkers; i++ { - go l.hydrationWorker() - } - } - work, cancel := context.WithCancel(l.ctx) - f = &chunkHydrationFlight{idx: idx, gen: gen, ref: ref, ctx: work, cancel: cancel, done: make(chan struct{})} - l.hydration[idx] = f - } f.waiters++ l.wakeHydrationLocked() l.stMu.Unlock() @@ -138,7 +115,7 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b f.waiters-- closed := l.closed changed := l.absentGen[idx] != f.gen || l.head.Chunks[idx] != f.ref - err := f.err + err = f.err if !closed && !changed && errors.Is(err, ErrChunkHydrationPending) { l.stats.Hydration.WaitRefusals++ } @@ -157,6 +134,46 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b } } +// hydrationFlightLocked returns the flight for chunk idx's current absence +// (generation and HEAD ref): an existing one (joined) or a new queued one. A +// stale flight of an older generation is settled and replaced. It refuses with +// hydrationPending when the queue is full. The caller holds stMu, counts its +// own waiter and wakes the workers. +func (l *chunkLayerImpl) hydrationFlightLocked(idx uint64, ref chunkRef) (*chunkHydrationFlight, bool, error) { + gen := l.absentGen[idx] + f := l.hydration[idx] + if f != nil && (f.gen != gen || f.ref != ref) { + f.cancel() + // The old worker remains owned and joined, but cannot delay a + // new generation or remove its replacement when it finishes. + delete(l.hydration, idx) + close(f.done) + if !f.running { + close(f.settled) // never picked up: no I/O will run + } + f = nil + } + if f != nil { + return f, true, nil + } + if len(l.hydration) >= l.cfg.HydrationQueueDepth { + return nil, false, hydrationPending(nil) + } + if !l.hydrationStarted { + l.hydration = make(map[uint64]*chunkHydrationFlight) + l.hydrationWake = make(chan struct{}, 1) + l.hydrationStarted = true + l.wg.Add(l.cfg.HydrationWorkers) + for i := 0; i < l.cfg.HydrationWorkers; i++ { + go l.hydrationWorker() + } + } + work, cancel := context.WithCancel(l.ctx) + f = &chunkHydrationFlight{idx: idx, gen: gen, ref: ref, ctx: work, cancel: cancel, done: make(chan struct{}), settled: make(chan struct{})} + l.hydration[idx] = f + return f, false, nil +} + func (l *chunkLayerImpl) wakeHydrationLocked() { select { case l.hydrationWake <- struct{}{}: @@ -196,6 +213,7 @@ func (l *chunkLayerImpl) hydrationWorker() { resolved, err := l.fillOnce(fetch, next.idx, next.gen, next.ref) cancel() next.cancel() + close(next.settled) l.stMu.Lock() if hydrationContextCauseOnly(err) { err = hydrationPending(err) @@ -225,6 +243,7 @@ func (l *chunkLayerImpl) closeHydrationLocked() { f.err = errChunkLayerClosed delete(l.hydration, idx) close(f.done) + close(f.settled) } } } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 0ad915f960..3ed9ec97b5 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -127,6 +127,7 @@ type chunkLayerImpl struct { // Test-only scheduling hooks; nil in production. testHydrationWait func(uint64) // after promise registration, outside locks + testHydrateAllPause func() // HydrateAll yielded to a guest waiter, outside locks testCOWWait func() testCOWSaverWait func() testCOWRead func(idx uint64, saved bool) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index d4d621ecd1..ff5a22bbbf 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -187,6 +187,7 @@ stateDiagram-v2 - **Snapshot** (`Catalog.CreateSnapshot`): claim the name with an exclusive name record `{request, attempt}` (a retry gets its own attempt back); check the volume is not being deleted; write an intent with a deadline; re-check the deadline; exclusively create `snaps//` holding a copy of the HEAD root. An unknown outcome keeps the intent; the caller retries with the same request id. - **Fork** (`Catalog.Fork`): claim the parent snapshot, check the source is not being deleted, write the target `VOLUME` (origin fork), then a HEAD at gen 1, epoch 0, no holder, with the parent's `RemoteLSN` and references. No segment or chunk is copied: the fork's references are owner-qualified, so it reads the parent's objects, and its root alone keeps them live after the parent snapshot is deleted. +- **Restore** (`Catalog.Restore`, independent restore): the fork steps with `VOLUME` origin `restore`; the claim is the fork's (live until the target has a HEAD), and from then on the target's owner-qualified refs keep the source's chunks live, so deleting the source snapshot or volume mid-restore is normal. The background walker (`HydrateAll`) makes every chunk local through the shared fill flights, under one host fill permit per flight. Bounded batch cuts then upload the chunks under the target's own keys; when the resolved HEAD holds no ref to another volume, the write-once `RESTORE-INDEPENDENT` entry is created (`MarkIndependent`). Snapshots of the target are refused until then, and a snapshot image that still names another volume's chunks is refused even after it. An aborted first HEAD keeps the parent snapshot as `fork_parent` until the target is deleted. Model: `docs/spec/RestoreIndependence.tla`. - **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; a snapshot with a live fork claim is always kept; deletion uses the same conditional mark as `DeleteSnapshot`. - **GC** (`gc.go` `Collector.run`, operator-driven through `sw-block ops chunk gc`, preview by default; see also `core/frontend/chunkstore/GC.md`): - roots: every HEAD, every named snapshot (including one whose delete is still in progress), every snapshot attempt that is not aborted, live intents, and segment objects; an unreadable segment aborts the mark. A deleted snapshot's attempt stays a root for one grace period after its delete time, then stops counting (`Collector.snapshotAttemptHeads` in `gc_copy.go`); @@ -205,7 +206,7 @@ HEAD states: ```mermaid stateDiagram-v2 - [*] --> active: initial HEAD (gen 1, epoch 0) or fork HEAD + [*] --> active: initial HEAD (gen 1, epoch 0), fork or restore HEAD active --> active: holder's cut CAS (gen+1) active --> detached: Detach final cut detached --> active: takeover CAS (higher epoch, new holder) @@ -235,6 +236,21 @@ stateDiagram-v2 The attempt path is never removed, so a late create can never land after a delete. +Restore (target volume): + +```mermaid +stateDiagram-v2 + [*] --> Claimed: claim parent snapshot, write VOLUME (origin restore) + Claimed --> Restoring: first HEAD (parent's refs, owner-qualified); claim dropped + Claimed --> Aborted: GC tombstones the HEAD (parent kept as fork_parent) + Restoring --> Restoring: walker fills; batch cut replaces foreign refs with own keys + Restoring --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created + Independent --> [*] + Aborted --> [*]: target deleted +``` + +Snapshots of the target are refused in `Claimed` and `Restoring`. + ## 7. Lease, takeover and host moves **Host guard** (`core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard`, enabled with `blockvolume --workspace-lease`; see [workspace lease](../workspace-lease.md)): frontend I/O and cuts are admitted only with a granted, unexpired lease for the exact `{volume, replica, epoch}`. Validity is anchored to the renewal request's start time, and blockmaster's `ValidForNs` already subtracts half the clock-skew bound (`core/host/master/workspace_service.go` `leaseFact`). A late reply cannot extend admission. A fenced guard never reopens. The lease is 30 s (`core/authority/authority.go`, `workspaceTTL`); the skew bound defaults to 20 s (`blockmaster --workspace-max-clock-skew`). diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index aa90753dcb..7c0e2cb485 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -197,6 +197,7 @@ stateDiagram-v2 | Holder | HolderFenced | a conflicting HEAD owner (including a regressed epoch) or a displaced publication is observed; local data and unresolved cut intents remain | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | | Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | +| Holder | (background hydrate) | an independent restore's walker fills every HEAD-named absent chunk through the same shared fill flights (never a second fetch, never over a local write); it yields while any flight has guest waiters, takes one host fill permit per flight (no cut payload, class `BackgroundFill` from the caller) and the permit is released only when that flight's I/O is over, also when the walker returns early on cancel, revocation or close | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill`; `core/storage/chunk_hydration.go` `hydrationFlightLocked` | `INV-RESTORE-HYDRATE-001`, `INV-CUT-READMISS-001` | ### M5 The cut pipeline @@ -266,7 +267,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | +| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork or restore HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork`, `Restore` | `INV-WS-HEAD-CAS-001` | | `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | | `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | @@ -285,6 +286,9 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | +| published | restore | the fork steps with `VOLUME` origin `restore`: the claim is live until the target has a HEAD (the fork's semantics); after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-RESTORE-PARENT-HOLD-001` | +| restore | independent | the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs` | `INV-RESTORE-INDEPENDENT-001` | +| restore (not independent) | name held | refused: `CreateSnapshot` on a restore volume needs the marker, and the supplied image itself must hold no foreign ref; a refused request leaves no name or attempt | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-RESTORE-SNAPSHOT-001` | **Intents and key bindings.** @@ -519,7 +523,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | -| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | +| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. An owner-qualified ref roots the owner's key (load-bearing for forks and restores: a target's HEAD keeps the source's chunks live after the source snapshot and volume are gone). | M6 key: Bound → Tombstoned; M6 snapshot: published → fork \| restore | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`); `TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone` (`core/frontend/chunkstore/restore_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete`; `RestoreIndependence` `NoGap` (simulation) | ACTIVE | | `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | | `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | | `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | @@ -527,6 +531,10 @@ Notes: | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | +| `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` (simulation) | ACTIVE | +| `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`red_snap_during_restore`) | ACTIVE | +| `INV-RESTORE-PARENT-HOLD-001` | A restore target with an aborted first HEAD no longer has a live fork claim (any HEAD ends the claim), but retention still keeps the parent snapshot as `fork_parent` (the fork-record scan treats an aborted HEAD as no HEAD) until the target volume is deleted. | M6 snapshot: published (parent of an aborted restore) | `core/frontend/chunkstore/retention.go` `liveClaims`, `forkParentsNeeded` | `TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `ClaimUntilHead_Inv` (simulation) | ACTIVE | +| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | Notes: diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 0fb0a0bd28..c4381751e8 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -98,6 +98,7 @@ Two kinds of config are **expected to violate**: | `ReplicationFailover.tla` | `cfg/S6_*` | design-level | | `RetentionGCTiming.tla` | `cfg/S9_*` | | | `RetentionGCMulti.tla` | `cfg/S9b_*` | | +| `RestoreIndependence.tla` | `cfg/RestoreIndependence_*` | independent restore; simulation only so far | Each `.cfg` names its spec on its first line. @@ -116,6 +117,7 @@ length of TLC's shortest counterexample. | S5 | `ControlPlane` | Blockmaster authority store: one volume record `{epoch, holder, move journal}`, two retried move requests, durable Puts that succeed, fail, or land with the reply lost, and restarts. | `UniqueEpoch` (issued epochs strictly increase), `Idempotent` (one epoch per request id), `JournalComplete` | `S5_code` pass (298). **RED:** `S5_red_noUncertain` UniqueEpoch violated (5-step: a lost-reply Put, then a reservation from stale memory puts the old assignment back). `S5_red_noReserve` passes (the reservation step is not needed for these invariants). | `core/authority/authority.go:436` applyWithWorkspaceMove (uncertain refusal `:442-444`, Put `:564`, mark uncertain `:568`); `core/authority/workspace.go:309` prepareWorkspaceMoveLocked (expected line `:313`, resume a reserved entry `:324-333`, reserve max+1 `:344-355`), journal replay `:192-219`, persist and mark uncertain `:276-288` | | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | +| S10 | `RestoreIndependence` | Independent restore: claim, two-step fork, hydrate, bounded batch cuts (own keys uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref, claim drop; GC, source snapshot and volume delete, snapshot retention, and crashes with resume from remote facts at any point. `ClaimUntilHead` selects today's fork claim (dropped at the first HEAD); the strict variant keeps the claim until independent. | `NoGap` (the target's chunks are always rooted), `Independent`, `NoForeignList`, `ClaimUntilHead_Inv`, `LifecycleFree`, `StateRemote` | **Simulation only (proves nothing; not exhausted)**, 3 seeds x 60,000 traces, depth 40: `safe` (NIdx 3, Batch 1) no violation in about 812k states; `safe_b2` about 888k; `safe_n4` about 1.22M; `strict_claim_until_independent` about 421k-844k. **RED** (each violated in simulation): `red_drop_claim_at_fork` ClaimUntilHead_Inv; `red_cas_before_upload`, `red_no_intent` NoGap; `red_marker_early`, `red_marker_before_cas`, `red_snap_during_restore` Independent; `red_list_foreign` NoForeignList; `red_resume_local` StateRemote; `red_retention_ignores_marker` LifecycleFree. **Witnesses reached:** `wit_done`, `wit_crash_resume`. An exhaustive run is pending. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `retention.go` `liveClaims`, `forkParentsNeeded`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAll`. Batch cuts and the restore driver are not merged yet. | ## Limits