diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index 9601cbf8ff..6b4d4fc098 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -524,8 +524,11 @@ func (l *LayoutRemote) CommitPendingSnapshot(ctx context.Context) error { } // The image is the one the engine already holds (same root and // position): an own write that leaves the engine's view where it is. + // On a volume never cut it is HEAD's first root (the empty image): seen + // takes it too, so a later write by anyone else that leaves this image + // in place does not move visible under the engine's base. l.session, l.pending, l.lastCommit = "", nil, got - l.ownGen = got.Gen + l.ownGen, l.seen = got.Gen, imageOf(got) return nil } diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote_owngen_census_test.go b/seaweed-block/core/frontend/chunkstore/layout_remote_owngen_census_test.go new file mode 100644 index 0000000000..42f1a09c01 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_remote_owngen_census_test.go @@ -0,0 +1,75 @@ +package chunkstore + +import ( + "go/ast" + "go/parser" + "go/token" + "sort" + "strings" + "testing" +) + +// Every own write of the layout remote records its generation in ownGen. +// One that changes HEAD's image must record the image too (seen), or the +// next write by anyone else that leaves the image in place looks like an +// image change and moves the generation the engine sees (visible) under the +// engine's base. This census lists every assignment to ownGen in +// layout_remote.go with its function and whether the same statement sets +// seen; a new site fails it until it is classified here. +func TestLayoutRemoteOwnWritesCensus(t *testing.T) { + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, "layout_remote.go", nil, 0) + if err != nil { + t.Fatal(err) + } + var got []string + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + as, ok := n.(*ast.AssignStmt) + if !ok { + return true + } + own, seen := false, false + for _, lhs := range as.Lhs { + if sel, ok := lhs.(*ast.SelectorExpr); ok { + switch sel.Sel.Name { + case "ownGen": + own = true + case "seen": + seen = true + } + } + } + if own { + got = append(got, fn.Name.Name+" seen="+map[bool]string{true: "yes", false: "no"}[seen]) + } + return true + }) + } + sort.Strings(got) + want := []string{ + // Own writes that change the image: the cut's commit and the + // snapshot commit of an unchanged (or the first, empty) image. + "CASHead seen=yes", + "CommitPendingSnapshot seen=yes", + // Own writes that change only HEAD's activity, which imageOf + // ignores: begin and end of a cleaning, a session's begin, and the + // abort of a dead session or end of a dead cleaning. + "Clean seen=no", + "Clean seen=no", + "openSessionLocked seen=no", + "rollBackLocked seen=no", + "rollBackLocked seen=no", + // Not an own write: the view following a write by anyone else + // (seen is set in its own statement when the image changed). + "viewLocked seen=no", + } + sort.Strings(want) + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Fatalf("ownGen assignments in layout_remote.go:\n%s\nwant:\n%s\nclassify a new site: does its write change HEAD's image (then set seen with it)?", strings.Join(got, "\n"), strings.Join(want, "\n")) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_layout_busy_operator_known_defect_test.go b/seaweed-block/core/frontend/durable/provider_layout_busy_operator_known_defect_test.go new file mode 100644 index 0000000000..84e77b5dbd --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_busy_operator_known_defect_test.go @@ -0,0 +1,172 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "fmt" + "strconv" + "strings" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// busyOperatorFiler is the holder's filer: while armed, before each HEAD +// write that commits the snapshot named want, an operator deletes one of the +// spare snapshots through its own catalog (a genuine store-direct HEAD write +// that leaves the image in place), so the holder's conditional update loses. +type busyOperatorFiler struct { + chunkstore.Filer + mu sync.Mutex + armed bool + want string + spares []string + deletes int + op func(name string) error + id layout.VolumeID +} + +func (f *busyOperatorFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { + f.mu.Lock() + inject := "" + if f.armed && e.GetName() == layout.HeadName && len(f.spares) > 0 { + gen, _ := strconv.ParseUint(string(expected["swb.layout.gen"]), 10, 64) + if h, err := layout.DecodeHead(e.GetContent(), gen+1, f.id); err == nil { + if _, ok := h.Snapshots[f.want]; ok { + inject, f.spares = f.spares[0], f.spares[1:] + f.deletes++ + } + } + } + f.mu.Unlock() + if inject != "" { + if err := f.op(inject); err != nil { + return fmt.Errorf("operator delete of %s: %w", inject, err) + } + } + return f.Filer.UpdateEntry(ctx, dir, e, expected) +} + +// KNOWN DEFECT (v1, fixed in 1.0.1): a snapshot whose commit loses to a +// genuine concurrent HEAD writer (a busy operator deleting snapshots during +// it, more often than the commit's bounded retry) answers head_conflict; the +// IMMEDIATE retry then commits the requeued data without the name and +// answers "not in HEAD after its commit" (500 internal). The data is +// committed either way; the name only on a later attempt. This test pins +// today's behaviour: when 1.0.1 makes the immediate retry name the snapshot, +// it fails here and is turned around. +func TestKnownDefectSnapshotRetryAfterAGenuineConflictCommitsTheDataUnnamed(t *testing.T) { + ctx := context.Background() + mem := chunkstore.NewMemFiler() + blobs := &layoutProviderBlobs{blobs: map[string][]byte{}} + op, err := chunkstore.NewBCatalog(mem, blobs, "/layout-test") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + v := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err = op.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + busy := &busyOperatorFiler{Filer: mem, want: "b", id: id, op: func(name string) error { _, err := op.DeleteSnapshot(ctx, v, name); return err }} + cat, err := chunkstore.NewBCatalog(busy, blobs, "/layout-test") + if err != nil { + t.Fatal(err) + } + view := newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1})) + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r1", + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return cat.Store(v) }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, v, me) + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ws := s.(*storage.WALStore) + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + head := func() layout.Head { + h, _, err := op.ReadHead(ctx, v) + if err != nil { + t.Fatal(err) + } + return h + } + write := func(lba uint32, tag string) []byte { + b := bytes.Repeat([]byte(fmt.Sprintf("%-16s", tag)), 4096/16) + if _, err := ws.Write(lba, b); err != nil { + t.Fatal(err) + } + if _, err := ws.Sync(); err != nil { + t.Fatal(err) + } + return b + } + write(0, "first") + spares := []string{"x1", "x2", "x3", "x4", "x5", "x6"} + for _, n := range append([]string{"s0"}, spares...) { + if _, err := p.SnapshotVolume(ctx, "v1", n, layout.SnapshotMeta{CreatedNs: 1}); err != nil { + t.Fatalf("setup snapshot %s: %v", n, err) + } + } + data := write(1, "during-the-busy") + before := head() + busy.mu.Lock() + busy.armed, busy.spares = true, spares + busy.mu.Unlock() + + _, err = p.SnapshotVolume(ctx, "v1", "b", layout.SnapshotMeta{CreatedNs: 2}) + busy.mu.Lock() + busy.armed = false + deletes := busy.deletes + busy.mu.Unlock() + if !errors.Is(err, storage.ErrChunkHeadPrecondition) { + t.Fatalf("snapshot b with a busy operator (%d deletes during its commit): %v; want head_conflict (ErrChunkHeadPrecondition)", deletes, err) + } + if h := head(); h.Position != before.Position || h.Current == nil || *h.Current != *before.Current { + t.Fatalf("the lost commit moved HEAD's image: position %d -> %d", before.Position, h.Position) + } else if _, named := h.Snapshots["b"]; named { + t.Fatal("the lost commit named b") + } + + // Today's behaviour (the known defect): the immediate retry commits the + // requeued data, without the name, and answers internal. + _, err = p.SnapshotVolume(ctx, "v1", "b", layout.SnapshotMeta{CreatedNs: 3}) + after := head() + if err == nil || !strings.Contains(err.Error(), `snapshot "b" of v1 is not in HEAD after its commit`) { + t.Fatalf("immediate retry of b: %v; want today's known defect %q (if 1.0.1 fixed it, turn this test around)", err, `snapshot "b" of v1 is not in HEAD after its commit`) + } + if _, named := after.Snapshots["b"]; named || after.Position <= before.Position || *after.Current == *before.Current || after.Activity.Kind != layout.ActIdle { + t.Fatalf("immediate retry of b: named %t, position %d -> %d, activity %s; want the data committed unnamed, HEAD idle", named, before.Position, after.Position, after.Activity.Kind) + } + + // A further attempt names it, at the image that holds the data. + hd, err := p.SnapshotVolume(ctx, "v1", "b", layout.SnapshotMeta{CreatedNs: 4}) + if err != nil { + t.Fatalf("third attempt of b: %v", err) + } + if sn, ok := hd.Snapshots["b"]; !ok || hd.Current == nil || sn.Root != *hd.Current { + t.Fatalf("third attempt of b: %+v", hd.Snapshots["b"]) + } + if got, err := ws.Read(1); err != nil || !bytes.Equal(got, data) { + t.Fatalf("block 1 after the snapshots: %v", err) + } + t.Logf("operator deletes during the lost commit: %d", deletes) +} diff --git a/seaweed-block/core/frontend/durable/provider_layout_empty_snapshot_test.go b/seaweed-block/core/frontend/durable/provider_layout_empty_snapshot_test.go new file mode 100644 index 0000000000..4fe7b5bcf3 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_empty_snapshot_test.go @@ -0,0 +1,112 @@ +package durable_test + +import ( + "bytes" + "context" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// The first snapshot of a volume never written names its empty image with +// a commit of its own, which gives HEAD its first root. A later HEAD write +// by someone else (here the store-direct snapshot delete) must not make the +// holder's next cut lose its commit: the next snapshot, with data, is taken +// on its first attempt, and its data is in the image it names. +func TestLayoutProviderSnapshotAfterAnEmptySnapshotAndAnOutsideWrite(t *testing.T) { + ctx := context.Background() + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &layoutProviderBlobs{blobs: map[string][]byte{}}, "/layout-test") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + v := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err = cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + view := newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1})) + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r1", + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return cat.Store(v) }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, v, me) + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ws := s.(*storage.WALStore) + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + head := func() layout.Head { + h, _, err := cat.ReadHead(ctx, v) + if err != nil { + t.Fatal(err) + } + return h + } + if h := head(); h.Current != nil { + t.Fatalf("setup: a never-written volume's HEAD names an image: %+v", h) + } + if _, err := p.SnapshotVolume(ctx, "v1", "empty", layout.SnapshotMeta{CreatedNs: 1}); err != nil { + t.Fatalf("snapshot of the empty volume: %v", err) + } + if h := head(); h.Current == nil { + t.Fatalf("setup: the empty snapshot's commit gave HEAD no root: %+v", h) + } + if _, err := cat.DeleteSnapshot(ctx, v, "empty"); err != nil { // a HEAD write by someone else + t.Fatalf("store-direct snapshot delete: %v", err) + } + data := bytes.Repeat([]byte("after-the-empty!"), 4096/16) + if _, err = ws.Write(1, data); err != nil { + t.Fatal(err) + } + if _, err = ws.Sync(); err != nil { + t.Fatal(err) + } + hd, err := p.SnapshotVolume(ctx, "v1", "with-data", layout.SnapshotMeta{CreatedNs: 2}) + if err != nil { + t.Fatalf("snapshot with data after the empty snapshot and an outside HEAD write: %v; want it taken on the first attempt", err) + } + sn, ok := hd.Snapshots["with-data"] + if !ok || hd.Current == nil || sn.Root != *hd.Current || sn.Position == 0 { + t.Fatalf("snapshot with-data: %+v (HEAD current %v); want it naming the image with the write", sn, hd.Current) + } + // The snapshot's own root, read from the store (root, segment, chunk; + // not the holder's cache), holds the write at block 1 and zeros at block + // 2, the unwritten block next to it in the same chunk. + st, err := cat.Store(v) + if err != nil { + t.Fatal(err) + } + r, err := layout.NewReader("/layout-test", v.Dir(), st.Fetch) + if err != nil { + t.Fatal(err) + } + img, err := r.Open(ctx, sn.Root) + if err != nil { + t.Fatal(err) + } + c, err := img.Chunk(ctx, 0) // blocks 0-3: ChunkBlocks 4 + if err != nil || c.Zero || len(c.Data) != 4*4096 { + t.Fatalf("chunk 0 of snapshot with-data: zero %t, %d bytes, %v", c.Zero, len(c.Data), err) + } + if !bytes.Equal(c.Data[4096:8192], data) { + t.Fatalf("block 1 in snapshot with-data's stored image is not the write") + } + if !bytes.Equal(c.Data[8192:12288], make([]byte, 4096)) { + t.Fatalf("block 2 in snapshot with-data's stored image is not zero") + } +}