diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 2ed27285ed..b70e17d002 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -495,17 +495,15 @@ func (c *Catalog) EnsureVolume(ctx context.Context, vol string, g Geometry) (Vol } } if v.Origin == OriginFork { - if h, has, err := c.ReadHead(ctx, vol); err != nil { + // One read of HEAD decides both: absent and aborted never attach. + h, has, err := c.ReadHead(ctx, vol) + switch { + case err != nil: return VolumeInfo{}, err - } else if has && h.State == storage.ChunkHeadAborted { - return VolumeInfo{}, catErr(CodeForkIncomplete, false, nil, "volume %s: its fork was aborted (HEAD is a tombstone); it never attaches", vol) - } - has, err := c.headExists(ctx, root) - if err != nil { - return VolumeInfo{}, remoteErr(err, "read HEAD of %s", vol) - } - if !has { + case !has: return VolumeInfo{}, catErr(CodeForkIncomplete, false, nil, "volume %s is a fork whose HEAD is not written yet", vol) + case h.State == storage.ChunkHeadAborted: + return VolumeInfo{}, catErr(CodeForkIncomplete, false, nil, "volume %s: its fork was aborted (HEAD is a tombstone); it never attaches", vol) } } return v, nil @@ -667,7 +665,7 @@ func (c *Catalog) abortedSnapEntry(vol, name, attempt string) (*filerpb.Entry, e return &filerpb.Entry{ Name: attempt, Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now, Crtime: now, FileMode: 0o644, Mime: "application/json"}, - Extended: map[string][]byte{extKind: []byte(kindChunkSnap), extSnapState: []byte(SnapAborted), extAttempt: []byte(attempt)}, + Extended: map[string][]byte{extKind: []byte(kindChunkSnap), extSnapState: []byte(SnapAborted)}, Content: body, }, nil } @@ -865,9 +863,18 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe switch { case outcome == createdNow: // This request's snapshot is at the attempt path (this create, or - // an earlier attempt's of the same request). + // an earlier attempt's of the same request). Judge it from that + // entry, never by resolving the name again (the name can be freed + // and reused meanwhile). c.dropIntent(ctx, root, id) - return c.readSnap(ctx, vol, req.Name) + info, _, err := decodeSnap(path.Join(dir, attempt), got) + if err != nil { + return SnapshotInfo{}, err + } + if info.State == SnapAborted { + return SnapshotInfo{}, catErr(CodeSnapshotExists, false, nil, "snapshot %s/%s: this request's attempt was aborted; delete the name to reuse it", vol, req.Name) + } + return info, nil case got != nil: // The attempt path holds a sweep's tombstone, which is permanent: // this create can never land. @@ -1223,13 +1230,28 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) pctx, cancel := c.publishCtx(ctx, deadline) outcome, got, cerr := c.createResolved(ctx, pctx, dstRoot, he, id) cancel() + // The HEAD now at the target decides, from that one read: a real HEAD + // completes the fork; an aborted tombstone means a sweep claimed the + // target first, so this fork lost and its create can never land. + if got == nil { + if outcome == createUnsettled { + return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: HEAD create outcome unknown; its intent is kept, retry with the same request id", req.Target) + } + c.dropIntent(ctx, dstRoot, id) // refused for good, but HEAD could not be read + return ForkResult{}, remoteErr(cerr, "fork %s: HEAD exists but could not be read; retry with the same request id", req.Target) + } + h, err := decodeHead(path.Join(dstRoot, headName), got) + if err != nil { + return ForkResult{}, err + } + if h.State == storage.ChunkHeadAborted { + c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands + return ForkResult{}, catErr(CodeTargetExists, false, nil, "fork %s lost to a sweep: its HEAD is an aborted tombstone; fork to a new volume id", req.Target) + } if outcome != createUnsettled { c.dropIntent(ctx, dstRoot, id) // confirmed, or refused for good } - if outcome == createUnsettled && got == nil { - return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: HEAD create outcome unknown; its intent is kept, retry with the same request id", req.Target) - } - return forkResult(existing, outcome != createdNow), nil // refused: the filer says HEAD exists + return forkResult(existing, outcome != createdNow), nil } // AbortFork settles a dead fork for a GC sweep (W5 ruling, 2026-11-15 diff --git a/seaweed-block/core/frontend/chunkstore/catalog_interleave_test.go b/seaweed-block/core/frontend/chunkstore/catalog_interleave_test.go new file mode 100644 index 0000000000..21a18e5169 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/catalog_interleave_test.go @@ -0,0 +1,139 @@ +package chunkstore + +import ( + "context" + "encoding/json" + "path" + "strings" + "testing" + + "google.golang.org/protobuf/proto" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Interleaved sweeps and name reuse (review of #119 r4): every decision is +// taken from ONE read of the entry acted on, and a fork's or snapshot's +// success from re-reading the entry it tried to create. + +func abortedHeadEntry(t *testing.T) *filerpb.Entry { + t.Helper() + he, err := headEntry(storage.ChunkHead{Gen: 1, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadAborted}) + if err != nil { + t.Fatal(err) + } + return he +} + +// A sweep claims the fork's HEAD right after the attach gate's first read: +// the gate must not pass the aborted HEAD. +func TestEnsureVolume_OneHeadReadDecides(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) + } + holdFirst(f, catBase+"/v2/HEAD") + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork with a held HEAD create: %v", err) + } + tomb := abortedHeadEntry(t) + done := false + f.afterLookup = func(p string) { + if p == catBase+"/v2/HEAD" && !done { + done = true + f.entries[p] = tomb // the sweep wins right after the first read + } + } + if _, err := c.EnsureVolume(ctx, "v2", catGeo); CodeOf(err) != CodeForkIncomplete { + t.Fatalf("attach with a sweep between reads: %v; want fork_incomplete", err) + } + f.afterLookup = nil +} + +// A sweep claims the fork's HEAD after the fork wrote its intent and before +// its HEAD create: the fork lost, so it must not report success. +func TestFork_LosesToASweepBeforeItsHeadCreate(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) + } + tomb := abortedHeadEntry(t) + f.beforeCreate = func(p string) { + if path.Dir(p) == catBase+"/v2/intents" { + f.entries[catBase+"/v2/HEAD"] = tomb + } + } + if res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("fork that lost to a sweep: %+v %v; want target_exists", res, err) + } + if in := intentsOf(t, f, "v2"); len(in) != 0 { + t.Fatalf("a fork that lost to a tombstone left %d intents", len(in)) + } + f.beforeCreate = nil +} + +// The name is deleted and reused by another request between a snapshot's +// create and its completion: the caller gets its own attempt, not the name's +// new owner. +func TestCatalog_SnapshotCompletionReadsItsOwnAttempt(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + f.failCreateAfterApply = func(p string) error { + if isSnapPath(p, "v1", "s1") { + return errTransport // applied; the response is lost + } + return nil + } + reused := false + f.afterLookup = func(p string) { + if reused || !isSnapPath(p, "v1", "s1") { + return + } + reused = true + // Meanwhile: the name is deleted and taken by request rB, whose + // snapshot carries other labels. + attB := "1-00000000000000bb" + rec, _ := nameRecordEntry(nameRecord{Format: snapFormat, VolumeID: "v1", Name: "s1", RequestID: "rB", Attempt: attB}) + f.entries[catBase+"/v1/"+snapNamesDir+"/s1"] = rec + other := proto.Clone(f.entries[p]).(*filerpb.Entry) + var doc snapDoc + _ = json.Unmarshal(other.Content, &doc) + doc.RequestID, doc.Labels = "rB", map[string]string{"who": "b"} + other.Content, _ = json.Marshal(doc) + other.Name = attB + other.Extended[extReq] = []byte("rB") + f.entries[path.Join(path.Dir(p), attB)] = other + } + info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "rA", Labels: map[string]string{"who": "a"}}, h) + if err != nil || info.Labels["who"] != "a" { + t.Fatalf("completion after the name was reused: %+v %v; want the caller's own snapshot (labels who=a)", info, err) + } + f.afterLookup, f.failCreateAfterApply = nil, nil +} + +// A sweep's tombstone lands on the attempt path before the create: the +// create is refused for good and reported aborted, never as this attempt's. +func TestCatalog_SnapshotTombstoneIsNeverThisAttempt(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + f.beforeCreate = func(p string) { + if path.Dir(p) != catBase+"/v1/intents" { + return + } + re := f.entries[catBase+"/v1/"+snapNamesDir+"/s1"] + attempt := string(re.Extended[extAttempt]) + tomb, _ := c.abortedSnapEntry("v1", "s1", attempt) + f.entries[catBase+"/v1/snaps/s1/"+attempt] = tomb + } + _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h) + if CodeOf(err) != CodeSnapshotExists || !strings.Contains(err.Error(), "aborted") { + t.Fatalf("create over its own attempt's tombstone: %v; want the aborted refusal", err) + } + if in := intentsOf(t, f, "v1"); len(in) != 0 { + t.Fatalf("an attempt that lost to a tombstone left %d intents", len(in)) + } + f.beforeCreate = nil +} diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go index e402c2147d..9f3ddcfb15 100644 --- a/seaweed-block/core/frontend/chunkstore/fake_test.go +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -48,8 +48,11 @@ type fakeFiler struct { // (exclusive create, evaluated when the server finally runs it). It // runs under the lock and may read or change f.entries (e is the // caller's entry: read it, do not keep it). - deferCreate func(p string, e *filerpb.Entry) bool - stallCreate func(p string) bool + deferCreate func(p string, e *filerpb.Entry) bool + stallCreate func(p string) bool + // afterLookup, if set, runs under the lock after a lookup of p has read + // its result: a change it makes is seen by the next read only. + afterLookup func(p string) deferredCreates []deferredCreate } @@ -58,11 +61,19 @@ func newFakeFiler() *fakeFiler { return &fakeFiler{entries: map[string]*filerpb. func (f *fakeFiler) LookupEntry(_ context.Context, dir, name string) (*filerpb.Entry, error) { f.mu.Lock() defer f.mu.Unlock() - e, ok := f.entries[path.Join(dir, name)] + p := path.Join(dir, name) + e, ok := f.entries[p] + var out *filerpb.Entry + if ok { + out = proto.Clone(e).(*filerpb.Entry) + } + if hook := f.afterLookup; hook != nil { + hook(p) + } if !ok { return nil, ErrNotFound } - return proto.Clone(e).(*filerpb.Entry), nil + return out, nil } func (f *fakeFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {