chunkstore: ShareGuard seam for snapshot and fork (no-op by default)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-20 19:35:08 -08:00
1 parent 4d7cea7d86
commit 29dab5e1d7
5 files changed
+297

No files matched your search

@@ -250,6 +250,11 @@ type SnapshotRequest struct {
// SourceReadAt is when the caller obtained the HEAD it snapshots (the
// cut's return); OpDeadline counts from it. Zero means now.
SourceReadAt time.Time
// ShareToken is the ShareGuard token of a caller that began the share
// before it obtained the HEAD (the owner's seal: Begin, then the cut).
// Empty: CreateSnapshot begins the share itself and refuses a HEAD that
// is no longer current. Unused without a guard; never stored.
ShareToken string
}
// ListOptions pages a snapshot listing.
@@ -295,6 +300,8 @@ type Catalog struct {
// retainHook, when set, runs at the named stages of a Retain pass (a
// test seam for interleavings; see hookPlanned).
retainHook func(stage, name string)
// guard, when set, is told about every share of a volume's chunks.
guard ShareGuard
}
// NewCatalog returns the catalog for the chunk base directory base (the
@@ -859,6 +866,12 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe
if !ok {
return SnapshotInfo{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol)
}
shareToken := req.ShareToken
if shareToken == "" {
if shareToken, err = c.beginShare(ctx, vol, head); err != nil {
return SnapshotInfo{}, err
}
}
// Take the name: this request's record, or an earlier attempt's of it.
attempt, err := c.claimName(ctx, vol, root, req, head.Gen)
@@ -919,6 +932,11 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe
return SnapshotInfo{}, catErr(CodeDeadlineExceeded, true, nil, "snapshot %s/%s: %v since the cut, over the %v deadline; nothing written", vol, req.Name, c.now().Sub(readAt), c.deadline())
}
dir := path.Join(root, snapsDir, req.Name)
if err := c.finishShare(ctx, vol, shareToken, head); err != nil {
// Clean abort: the snapshot entry was never sent.
c.dropIntent(ctx, root, id)
return SnapshotInfo{}, err
}
pctx, cancel := c.publishCtx(ctx, deadline)
outcome, got, cerr := c.createResolved(ctx, pctx, dir, e, attempt)
cancel()
@@ -1223,6 +1241,12 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error)
// write on the parent attempt's entry, which retention's delete mark
// is conditioned against (see retention.go).
readAt := c.now()
var shareToken string
if c.guard != nil { // the shared HEAD is the snapshot's, read below
if shareToken, err = c.guard.Begin(ctx, req.Source); err != nil {
return ForkResult{}, remoteErr(err, "share guard for %s", req.Source)
}
}
snap, err := c.claimForkParent(ctx, req)
if err != nil {
return ForkResult{}, err
@@ -1313,6 +1337,11 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error)
c.dropIntent(ctx, dstRoot, id)
return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: %v since reading the snapshot, over the %v deadline; HEAD not written", req.Target, c.now().Sub(readAt), c.deadline())
}
if err := c.finishShare(ctx, req.Source, shareToken, src); err != nil {
// Clean abort: HEAD was never sent.
c.dropIntent(ctx, dstRoot, id)
return ForkResult{}, err
}
// Under this request's VOLUME only this request's attempts write HEAD
// (attach refuses a fork without HEAD), so a HEAD found there completes
// the fork; if it is another attempt's and this create is unsettled,
@@ -0,0 +1,61 @@
package chunkstore
import (
"context"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// ShareGuard is told about every sharer of a volume's chunks. A snapshot or
// fork calls Begin before it obtains the HEAD it will reference, and Finish,
// with that HEAD, right before it activates its result; an error from either
// aborts the share before anything is activated. A token Begin returned and
// nobody finished is the guard's to expire.
//
// No guard (the default) changes nothing: no call is made and no check is
// added.
type ShareGuard interface {
Begin(ctx context.Context, vol string) (token string, err error)
Finish(ctx context.Context, vol, token string, head storage.ChunkHead) error
}
// SetShareGuard installs g (nil removes it). Set it before the catalog is
// used.
func (c *Catalog) SetShareGuard(g ShareGuard) { c.guard = g }
// ShareGuard returns the installed guard, or nil.
func (c *Catalog) ShareGuard() ShareGuard { return c.guard }
// beginShare starts a share of vol's chunks for a caller that passes the
// HEAD in: with a guard, it begins the share, then refuses unless head is
// still vol's current HEAD (a share that obtained an older HEAD could
// reference chunks superseded meanwhile). token is "" without a guard.
func (c *Catalog) beginShare(ctx context.Context, vol string, head storage.ChunkHead) (token string, err error) {
if c.guard == nil {
return "", nil
}
token, err = c.guard.Begin(ctx, vol)
if err != nil {
return "", remoteErr(err, "share guard for %s", vol)
}
cur, ok, err := c.ReadHead(ctx, vol)
if err != nil {
return "", err
}
if !ok || cur.Gen != head.Gen || cur.Epoch != head.Epoch {
return "", catErr(CodeOutcomeUnknown, true, nil, "volume %s: the HEAD to share (gen %d) is no longer current (gen %d); retry", vol, head.Gen, cur.Gen)
}
return token, nil
}
// finishShare finishes a share before its result is activated; no-op
// without a guard.
func (c *Catalog) finishShare(ctx context.Context, vol, token string, head storage.ChunkHead) error {
if c.guard == nil {
return nil
}
if err := c.guard.Finish(ctx, vol, token, head); err != nil {
return remoteErr(err, "share guard for %s refused the share", vol)
}
return nil
}
@@ -0,0 +1,164 @@
package chunkstore
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// recGuard records Begin and Finish; onFinish runs inside Finish.
type recGuard struct {
mu sync.Mutex
events []string
n int
finishErr error
onFinish func()
}
func (g *recGuard) Begin(_ context.Context, vol string) (string, error) {
g.mu.Lock()
defer g.mu.Unlock()
g.n++
g.events = append(g.events, "begin:"+vol)
return fmt.Sprintf("tok-%d", g.n), nil
}
func (g *recGuard) Finish(_ context.Context, vol, token string, head storage.ChunkHead) error {
if g.onFinish != nil {
g.onFinish()
}
g.mu.Lock()
defer g.mu.Unlock()
g.events = append(g.events, fmt.Sprintf("finish:%s:%s:%d", vol, token, head.Gen))
return g.finishErr
}
func (g *recGuard) list() []string {
g.mu.Lock()
defer g.mu.Unlock()
return append([]string(nil), g.events...)
}
func countUnder(f *fakeFiler, prefix string) int {
f.mu.Lock()
defer f.mu.Unlock()
n := 0
for k := range f.entries {
if strings.HasPrefix(k, prefix) {
n++
}
}
return n
}
// A snapshot of a passed-in HEAD begins the share, checks the HEAD is still
// current, and finishes it before the snapshot entry is written.
func TestShareGuard_SnapshotFinishesBeforeActivation(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
g := &recGuard{}
g.onFinish = func() {
if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 {
t.Errorf("snapshot entry written before Finish (%d entries)", n)
}
}
c.SetShareGuard(g)
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
want := []string{"begin:v1", fmt.Sprintf("finish:v1:tok-1:%d", h.Gen)}
if got := g.list(); len(got) != 2 || got[0] != want[0] || got[1] != want[1] {
t.Fatalf("guard events %v; want %v", got, want)
}
if countUnder(f, catBase+"/v1/snaps/s1/") == 0 {
t.Fatal("snapshot not written after a successful Finish")
}
}
// A refused Finish aborts the snapshot: nothing activated, its intent dropped.
func TestShareGuard_RefusedFinishAbortsTheSnapshot(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
intents := countUnder(f, catBase+"/v1/intents/")
c.SetShareGuard(&recGuard{finishErr: errors.New("token expired")})
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil {
t.Fatal("snapshot activated after a refused Finish")
}
if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 {
t.Fatalf("%d snapshot entries after a refused Finish", n)
}
if n := countUnder(f, catBase+"/v1/intents/"); n != intents {
t.Fatalf("intents %d -> %d; want the snapshot's intent dropped", intents, n)
}
}
// A passed-in HEAD that is no longer current is refused before Finish.
func TestShareGuard_StaleHeadIsRefused(t *testing.T) {
f, b, c, h := catalogFixture(t)
ctx := context.Background()
publishSource(t, f, b, "v1", map[uint64][]byte{5: chunkBytes(0x20)}) // HEAD moves on
g := &recGuard{}
c.SetShareGuard(g)
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil {
t.Fatal("snapshot of a superseded HEAD accepted with a guard")
}
for _, e := range g.list() {
if strings.HasPrefix(e, "finish:") {
t.Fatalf("Finish called for a refused share: %v", g.list())
}
}
if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 {
t.Fatalf("%d snapshot entries for a refused share", n)
}
}
// A caller that began the share itself passes its token: no second Begin.
func TestShareGuard_CallerToken(t *testing.T) {
_, _, c, h := catalogFixture(t)
g := &recGuard{}
c.SetShareGuard(g)
if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r", ShareToken: "owner-tok"}, h); err != nil {
t.Fatal(err)
}
if got := g.list(); len(got) != 1 || got[0] != fmt.Sprintf("finish:v1:owner-tok:%d", h.Gen) {
t.Fatalf("guard events %v; want only Finish with the caller's token", got)
}
}
// A fork begins the share before reading the snapshot and finishes it with
// the snapshot's HEAD before writing the child's HEAD; a refused Finish
// writes no child HEAD.
func TestShareGuard_Fork(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
g := &recGuard{}
g.onFinish = func() {
if countUnder(f, catBase+"/v2/HEAD") != 0 {
t.Error("child HEAD written before Finish")
}
}
c.SetShareGuard(g)
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-1"}); err != nil {
t.Fatal(err)
}
want := []string{"begin:v1", fmt.Sprintf("finish:v1:tok-1:%d", h.Gen)}
if got := g.list(); len(got) != 2 || got[0] != want[0] || got[1] != want[1] {
t.Fatalf("guard events %v; want %v", got, want)
}
c.SetShareGuard(&recGuard{finishErr: errors.New("token expired")})
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "fork-2"}); err == nil {
t.Fatal("fork activated after a refused Finish")
}
if countUnder(f, catBase+"/v3/HEAD") != 0 {
t.Fatal("child HEAD written after a refused Finish")
}
}
@@ -578,6 +578,14 @@ func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkS
if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed {
return info, err
}
// The share begins before the cut that produces the sealed HEAD.
if g := c.cat.ShareGuard(); g != nil {
token, err := g.Begin(ctx, volumeID)
if err != nil {
return chunkstore.SnapshotInfo{}, err
}
sreq.ShareToken = token
}
// A named seal is urgent even without a minimum LSN.
r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0)
if err != nil {
@@ -96,3 +96,38 @@ func TestChunkControl_InvalidLabelRefusedBeforeCutting(t *testing.T) {
t.Fatalf("snapshot with an invalid label: %v (cuts %d); want invalid_label without a cut", err, fp.cuts)
}
}
// ownerGuard records, at Begin, how many cuts the provider had taken.
type ownerGuard struct {
cutsAtBegin []int
finishes []string
fp *fakeChunkProvider
}
func (g *ownerGuard) Begin(context.Context, string) (string, error) {
g.cutsAtBegin = append(g.cutsAtBegin, g.fp.cuts)
return "owner", nil
}
func (g *ownerGuard) Finish(_ context.Context, vol, token string, head storage.ChunkHead) error {
g.finishes = append(g.finishes, vol+":"+token)
return nil
}
// The owner's seal begins the share BEFORE the cut that produces the sealed
// HEAD, and the catalog finishes it with that token (no second Begin).
func TestChunkControl_SnapshotBeginsShareBeforeTheCut(t *testing.T) {
ctx := context.Background()
fp, ctl := adapterFixture(t)
g := &ownerGuard{fp: fp}
ctl.(*chunkControl).cat.SetShareGuard(g)
if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}); err != nil {
t.Fatal(err)
}
if len(g.cutsAtBegin) != 1 || g.cutsAtBegin[0] != 0 || fp.cuts != 1 {
t.Fatalf("Begin saw %v cuts (cuts now %d); want one Begin before the one cut", g.cutsAtBegin, fp.cuts)
}
if len(g.finishes) != 1 || g.finishes[0] != "v1:owner" {
t.Fatalf("finishes %v; want one Finish with the owner's token", g.finishes)
}
}