diff --git a/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go new file mode 100644 index 0000000000..e9e52d078c --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go @@ -0,0 +1,60 @@ +package main + +import ( + "context" + "fmt" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type manifestFixtureFiler struct { + chunkstore.Filer + mu sync.Mutex + blobs map[string][]byte +} + +func newManifestFixtureFiler(f chunkstore.Filer) *manifestFixtureFiler { + return &manifestFixtureFiler{Filer: f, blobs: map[string][]byte{}} +} + +func (f *manifestFixtureFiler) Put(_ context.Context, b []byte) (string, error) { + f.mu.Lock() + defer f.mu.Unlock() + id := fmt.Sprintf("fixture-%d", len(f.blobs)) + f.blobs[id] = append([]byte(nil), b...) + return id, nil +} + +func (f *manifestFixtureFiler) Get(_ context.Context, id string) ([]byte, error) { + f.mu.Lock() + defer f.mu.Unlock() + b, ok := f.blobs[id] + if !ok { + return nil, chunkstore.ErrNotFound + } + return append([]byte(nil), b...), nil +} + +func prepareFixtureHead(t *testing.T, f *manifestFixtureFiler, h storage.ChunkHead) storage.ChunkHead { + t.Helper() + ctx := context.Background() + r, err := chunkstore.NewChunkRemote(f, f, defaultChunkPathCLI+"/v1") + if err != nil { + t.Fatal(err) + } + h, intents, err := r.PrepareManifest(ctx, storage.ChunkHead{}, h, 8*4096) + if err != nil { + t.Fatal(err) + } + // These fixtures hand the completed cut directly to the catalog; the + // snapshot/fork operations establish their own reachability intents. + for _, id := range intents { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + return h +} diff --git a/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go b/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go index 705e2ca9d5..b40b03134e 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go +++ b/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go @@ -41,10 +41,11 @@ func (f *failingFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.E func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) { ctx := context.Background() ff := &failingFiler{MemFiler: chunkstore.NewMemFiler()} + fm := newManifestFixtureFiler(ff) prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return ff, func() error { return nil }, nil } + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return fm, func() error { return nil }, nil } t.Cleanup(func() { dialChunkFiler = prev }) - cat, err := chunkstore.NewCatalog(ff, defaultChunkPathCLI) + cat, err := chunkstore.NewCatalog(fm, defaultChunkPathCLI) if err != nil { t.Fatal(err) } @@ -54,6 +55,7 @@ func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) { base := time.Now().Add(-48 * time.Hour) head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + head = prepareFixtureHead(t, fm, head) for i := 0; i < 4; i++ { at := base.Add(time.Duration(i) * time.Minute) cat.SetClock(func() time.Time { return at }) diff --git a/seaweed-block/cmd/sw-block/chunk_retain_test.go b/seaweed-block/cmd/sw-block/chunk_retain_test.go index 3623088e6c..0dd4633cfd 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain_test.go +++ b/seaweed-block/cmd/sw-block/chunk_retain_test.go @@ -44,7 +44,7 @@ func TestOpsChunk_SnapshotPinAndExpires(t *testing.T) { // dry-run, apply, and see the accounting follow. func TestOpsChunk_UsageAndRetain(t *testing.T) { ctx := context.Background() - mem := chunkstore.NewMemFiler() + mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) prev := dialChunkFiler dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } t.Cleanup(func() { dialChunkFiler = prev }) @@ -59,6 +59,7 @@ func TestOpsChunk_UsageAndRetain(t *testing.T) { cat.SetClock(func() time.Time { return old }) head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + head = prepareFixtureHead(t, mem, head) for i := 0; i < 5; i++ { if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: fmt.Sprintf("s%d", i), RequestID: fmt.Sprintf("r%d", i), Class: chunkstore.SnapshotClassSemantic}, head); err != nil { t.Fatal(err) diff --git a/seaweed-block/cmd/sw-block/chunk_show_test.go b/seaweed-block/cmd/sw-block/chunk_show_test.go index 22b3eaa32a..6a36ac02a5 100644 --- a/seaweed-block/cmd/sw-block/chunk_show_test.go +++ b/seaweed-block/cmd/sw-block/chunk_show_test.go @@ -13,7 +13,7 @@ import ( // either is null when it does not exist (B9 W2 appendix). func TestOpsChunk_Show(t *testing.T) { ctx := context.Background() - mem := chunkstore.NewMemFiler() + mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) prev := dialChunkFiler dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } t.Cleanup(func() { dialChunkFiler = prev }) @@ -27,6 +27,7 @@ func TestOpsChunk_Show(t *testing.T) { } head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + head = prepareFixtureHead(t, mem, head) if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil { t.Fatal(err) } diff --git a/seaweed-block/cmd/sw-block/chunk_test.go b/seaweed-block/cmd/sw-block/chunk_test.go index 9b96c7f623..39347d09fa 100644 --- a/seaweed-block/cmd/sw-block/chunk_test.go +++ b/seaweed-block/cmd/sw-block/chunk_test.go @@ -157,6 +157,15 @@ func TestOpsChunk_FilerCommands(t *testing.T) { } head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 42, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + manifestMem := newManifestFixtureFiler(mem) + cat, err = chunkstore.NewCatalog(manifestMem, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return manifestMem, func() error { return nil }, nil + } + head = prepareFixtureHead(t, manifestMem, head) if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/chunkstore/api.go b/seaweed-block/core/frontend/chunkstore/api.go index 469ca3295f..eae7dd0fd8 100644 --- a/seaweed-block/core/frontend/chunkstore/api.go +++ b/seaweed-block/core/frontend/chunkstore/api.go @@ -94,7 +94,7 @@ func NewVolumeShowBody(vol string, v *VolumeInfo, h *storage.ChunkHead) VolumeSh if state == "" { state = storage.ChunkHeadActive } - body.Head = &HeadShow{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: state, ChunkCount: len(h.Chunks)} + body.Head = &HeadShow{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: state, ChunkCount: manifestCount(*h)} if d := h.DetachedBy; d != nil { body.Head.DetachedBy = &DetachedByShow{Holder: d.Holder, Epoch: d.Epoch, Gen: d.Gen} } diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index b24d94f720..eb6fd6f4eb 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -228,8 +228,9 @@ type SnapshotInfo struct { attempt string // the attempt the name resolved to, when read by name - head storage.ChunkHead - geo Geometry + head storage.ChunkHead + geo Geometry + digest string // identity uses the embedded writer version, not today's serializer } // Head returns the HEAD the snapshot copied. @@ -673,6 +674,10 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) { if err != nil { return fail("%v", err) } + digest, err := snapshotHeadDigest(head, doc.Head) + if err != nil { + return fail("HEAD identity: %v", err) + } state := string(e.Extended[extSnapState]) if state != SnapActive && state != SnapDeleting { return fail("state %q", state) @@ -684,7 +689,7 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) { VolumeID: doc.VolumeID, Name: doc.Name, HeadGen: head.Gen, HeadEpoch: head.Epoch, CutLSN: head.RemoteLSN, CreatedNs: doc.CreatedNs, State: state, ChunkCount: manifestCount(head), ManifestBytes: len(e.GetContent()), Consistency: doc.Consistency, Labels: doc.Labels, Parent: doc.Parent, ExpiresAtNs: doc.ExpiresAtNs, - Class: doc.Class, head: head, geo: doc.Geometry, + Class: doc.Class, head: head, geo: doc.Geometry, digest: digest, }, doc.RequestID, nil } @@ -870,6 +875,11 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe return SnapshotInfo{}, refuseDeleted(vol, "it cannot be snapshotted") } + head, upgradeIDs, err := c.prepareLegacyHead(ctx, root, head, head, v.Geometry) + defer c.dropManifestIntents(ctx, root, upgradeIDs) + if err != nil { + return SnapshotInfo{}, err + } headEnt, err := headEntry(head) if err != nil { return SnapshotInfo{}, err @@ -1231,10 +1241,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, fmt.Errorf("chunkstore: snapshot %s/%s has no geometry", req.Source, req.Snapshot) } src := snap.Head() - digest, err := headDigest(src) - if err != nil { - return ForkResult{}, err - } + digest := snap.digest head := storage.ChunkHead{Gen: 1, Epoch: 0, Holder: "", RemoteLSN: src.RemoteLSN, Chunks: make(map[uint64]storage.ChunkRef, len(src.Chunks)), State: storage.ChunkHeadActive} qualified := 0 if src.Segments != nil { @@ -1285,6 +1292,11 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) existing = vol } + head, upgradeIDs, err := c.prepareLegacyHead(ctx, dstRoot, storage.ChunkHead{}, head, snap.geo) + defer c.dropManifestIntents(ctx, dstRoot, upgradeIDs) + if err != nil { + return ForkResult{}, err + } he, err := headEntry(head) if err != nil { return ForkResult{}, err diff --git a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go index 7d7290c26f..44b67dffaa 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go @@ -28,8 +28,7 @@ func intentsOf(t *testing.T, f *fakeFiler, vol string) []storage.ChunkIntent { func sortedKeysOf(h storage.ChunkHead, qualify string) []string { var out []string - for _, ref := range h.Chunks { - k := ref.Key + for _, k := range headKeys(h) { if qualify != "" && !strings.HasPrefix(k, "@") { k = "@" + qualify + "/" + k } @@ -196,11 +195,20 @@ func TestFork_IncompleteRetryBoundToOriginalImage(t *testing.T) { next.Chunks[k] = v } next.Chunks[5] = storage.ChunkRef{Key: "chunks/e1/c5/new", SHA256: sha256Of(chunkBytes(0x55))} + next, ids, err := r1.PrepareManifest(ctx, h, next, h.ChunkBytes) + if err != nil { + t.Fatal(err) + } gen, err := r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: 1}, next) if err != nil { t.Fatal(err) } next.Gen = gen + for _, id := range ids { + if err := r1.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-new"}, next); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/chunkstore/catalog_test.go b/seaweed-block/core/frontend/chunkstore/catalog_test.go index 5e666b46a6..33ade710d3 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_test.go @@ -41,11 +41,20 @@ func publishSource(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string, chunks if err != nil { t.Fatal(err) } + h, intents, err := r.PrepareManifest(ctx, cur, h, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h) if err != nil { t.Fatal(err) } h.Gen = gen + for _, id := range intents { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } return h } @@ -80,7 +89,10 @@ func chunkBytes(fill byte) []byte { func catalogFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) { t.Helper() f, b := newFakeFiler(), newFakeBlobs() - c := newCat(t, f) + c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) + if err != nil { + t.Fatal(err) + } if _, err := c.EnsureVolume(context.Background(), "v1", catGeo); err != nil { t.Fatal(err) } @@ -233,7 +245,7 @@ func TestCatalog_DeleteMarksThenIdempotent(t *testing.T) { } func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) { - f, _, c, h := catalogFixture(t) + f, b, c, h := catalogFixture(t) ctx := context.Background() if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { t.Fatal(err) @@ -259,7 +271,7 @@ func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) { if got, _ := f.ListEntries(ctx, catBase+"/v2/intents", "", "", 0); len(got) != 0 { t.Fatalf("fork left %d intents", len(got)) } - r2, _ := NewChunkRemote(f, newFakeBlobs(), catBase+"/v2") + r2, _ := NewChunkRemote(f, b, catBase+"/v2") head, err := r2.GetHead(ctx) if err != nil { t.Fatal(err) @@ -269,11 +281,11 @@ func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) { } for idx, ref := range head.Chunks { src := h.Chunks[idx] - if ref.Key != "@v1/"+src.Key || ref.SHA256 != src.SHA256 { + if ref.Key != qualifyManifestKey("v1", src.Key) || ref.SHA256 != src.SHA256 { t.Fatalf("chunk %d ref %+v, want @v1/%s with the same hash", idx, ref, src.Key) } } - if res.HeadGen != 1 || res.HeadEpoch != 0 || res.QualifiedRefs != 2 || res.SourceGen != h.Gen || res.RemoteLSN != 42 || res.Replayed { + if res.HeadGen != 1 || res.HeadEpoch != 0 || res.QualifiedRefs != 1 || res.ChunkCount != 2 || res.SourceGen != h.Gen || res.RemoteLSN != 42 || res.Replayed { t.Fatalf("result %+v", res) } v, ok, err := c.ReadVolume(ctx, "v2") @@ -310,7 +322,7 @@ func TestFork_ForkOfForkKeepsOriginalOwner(t *testing.T) { r3, _ := NewChunkRemote(f, b, catBase+"/v3") h3, _ := r3.GetHead(ctx) for idx, ref := range h3.Chunks { - if ref.Key != "@v1/"+h.Chunks[idx].Key { + if ref.Key != qualifyManifestKey("v1", h.Chunks[idx].Key) { t.Fatalf("second-level fork chunk %d names %q, want the original owner @v1/%s", idx, ref.Key, h.Chunks[idx].Key) } if got, err := r3.Get(ctx, ref.Key); err != nil || sha256.Sum256(got) != ref.SHA256 { @@ -648,7 +660,7 @@ func TestCatalog_EnsureVolumeCreatesTheInitialHead(t *testing.T) { if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { t.Fatal(err) } - if kept, _, _ := c.ReadHead(ctx, "v2"); kept.Gen != pub.Gen || len(kept.Chunks) != 1 { + if kept, _, _ := c.ReadHead(ctx, "v2"); kept.Gen != pub.Gen || manifestCount(kept) != 1 || kept.Segments[0] != pub.Segments[0] { t.Fatalf("an existing HEAD was replaced by the initial one: %+v, published %+v", kept, pub) } diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 3fbfde5f9d..aff708783b 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -339,6 +339,7 @@ func decodeIntent(p string, e *filerpb.Entry) (storage.ChunkIntent, error) { } type headDoc struct { + Levels int `json:"levels,omitempty"` Segments map[uint64]storage.ChunkSegment `json:"segments,omitempty"` ChunkBytes uint64 `json:"chunk_bytes,omitempty"` ChunkCount int `json:"chunk_count,omitempty"` @@ -370,6 +371,16 @@ type refDoc struct { // was ever published. An entry that exists but does not decode is an // error, never the zero HEAD. func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + h, err := r.getHeadRoot(ctx) + if err != nil { + return h, err + } + return r.resolveManifest(ctx, h) +} + +// getHeadRoot validates the root and its CAS attributes without reading any +// immutable segment. CASHead only needs authority and lineage from this root. +func (r *ChunkRemote) getHeadRoot(ctx context.Context) (storage.ChunkHead, error) { e, err := r.f.LookupEntry(ctx, r.root, headName) if errors.Is(err, ErrNotFound) { return storage.ChunkHead{}, nil @@ -377,11 +388,7 @@ func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { if err != nil { return storage.ChunkHead{}, err } - h, err := decodeHead(path.Join(r.root, headName), e) - if err != nil { - return h, err - } - return r.resolveManifest(ctx, h) + return decodeHead(path.Join(r.root, headName), e) } // CASHead installs next, at generation expected.Gen+1, only if the stored @@ -397,7 +404,7 @@ func (r *ChunkRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer // Read the LSN under the same generation/epoch guard used by UpdateEntry. // A competing write after this read makes the conditional update fail; // no successful CAS can lower the committed lineage frontier. - current, err := r.GetHead(ctx) + current, err := r.getHeadRoot(ctx) if err != nil { return 0, err } @@ -439,19 +446,17 @@ func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) { doc.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen} } if h.Segments == nil { - doc.Chunks = make(map[uint64]refDoc, len(h.Chunks)) - for idx, ref := range h.Chunks { - if ref.Key == "" { - return nil, fmt.Errorf("chunkstore: HEAD chunk %d has no key", idx) - } - doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} + if len(h.Chunks) != 0 { + return nil, errors.New("chunkstore: data HEAD requires a segmented manifest and geometry") } + doc.Chunks = map[uint64]refDoc{} } if h.Segments != nil { if err := validateRoot(h); err != nil { return nil, err } - doc.Format = 2 + doc.Format = 3 + doc.Levels = 1 doc.Chunks = nil doc.Segments = h.Segments doc.ChunkBytes = h.ChunkBytes @@ -555,11 +560,11 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) { if err != nil || len(sum) != 32 || ref.Key == "" { return fail("chunk %d ref invalid", idx) } - cr := storage.ChunkRef{Key: ref.Key} + cr := storage.ChunkRef{Key: ref.Key, Encoding: "full", BirthLSN: doc.RemoteLSN} copy(cr.SHA256[:], sum) h.Chunks[idx] = cr } - if doc.Format == 2 { + if doc.Format == 2 || doc.Format == 3 { if len(doc.Chunks) != 0 { return fail("segmented root contains flat chunks") } diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go index 7bee5cbf5b..70a1f172ff 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go @@ -55,10 +55,22 @@ func TestChunkRemote_HeadRoundTripAndCAS(t *testing.T) { t.Fatal(err) } want := head(1, "a", 42, map[uint64]storage.ChunkRef{3: ref("chunks/e1/c3/n-1", d)}) + legacy := want.Chunks[3] + legacy.Encoding, legacy.BirthLSN = "full", want.RemoteLSN + want.Chunks[3] = legacy + want, intents, err := r.PrepareManifest(ctx, storage.ChunkHead{}, want, 4096) + if err != nil { + t.Fatal(err) + } gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, want) if err != nil || gen != 1 { t.Fatalf("first CAS = %d, %v; want gen 1", gen, err) } + for _, id := range intents { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } got, err := r.GetHead(ctx) if err != nil { t.Fatal(err) @@ -228,7 +240,8 @@ func TestChunkRemote_UntrustedHeadIsAnError(t *testing.T) { f := newFakeFiler() r := newTestRemote(t, f, newFakeBlobs()) h := head(1, "a", 1, map[uint64]storage.ChunkRef{0: ref("k", []byte("x"))}) - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, h); err != nil { + h.Gen = 1 + if err := f.CreateEntry(ctx, testRoot, legacyHeadFixture(t, h), true); err != nil { t.Fatal(err) } f.mu.Lock() diff --git a/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go b/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go index 5dce4f7ad3..ea28bc0c35 100644 --- a/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go +++ b/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go @@ -21,10 +21,14 @@ func fuzzHeadSeeds(tb testing.TB) [][]byte { {Gen: 3, Epoch: 4, Holder: "r2", RemoteLSN: 9, State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Holder: "r2", Epoch: 4, Gen: 3}, Chunks: map[uint64]storage.ChunkRef{}}, {Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 3, ChunkBytes: 4 << 20, ManifestChunkCount: 2, - Segments: map[uint64]storage.ChunkSegment{0: {Key: "@v1/seg/00", SHA256: sum, Owner: "v1", Count: 2}}}, + Segments: map[uint64]storage.ChunkSegment{0: {Key: "@v1/seg/00", SHA256: sum, Owner: "v1", Count: 2, SegFormat: 2, MaxBirthLSN: 3}}}, } var out [][]byte for _, h := range heads { + if h.Segments == nil && len(h.Chunks) > 0 { + out = append(out, legacyHeadFixture(tb, h).Content) + continue + } e, err := headEntry(h) if err != nil { tb.Fatalf("seed %+v: %v", h, err) @@ -90,6 +94,12 @@ func FuzzDecodeHeadDocument(f *testing.F) { return } e, err := headEntry(h) + if h.Segments == nil && len(h.Chunks) > 0 { + if err == nil { + t.Fatal("read-only legacy data was writable as flat HEAD") + } + return + } if err != nil { if gap := knownHeadEncodeGap(h); gap != "" { return diff --git a/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go b/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go new file mode 100644 index 0000000000..ee4a1779e2 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go @@ -0,0 +1,222 @@ +package chunkstore + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Frozen output of the pre-format-3 CreateSnapshot/Fork producers at 3401cc60. +func preF4ForkFixture(t *testing.T, segmented bool) (*fakeFiler, *Catalog, *ChunkRemote) { + t.Helper() + suffix := "false" + if segmented { + suffix = "true" + } + data, err := os.ReadFile("testdata/pre_f4_fork_" + suffix + ".json") + if err != nil { + t.Fatal(err) + } + var frozen struct { + Entries map[string]*filerpb.Entry + Objects map[string][]byte + } + if err := json.Unmarshal(data, &frozen); err != nil { + t.Fatal(err) + } + f, b := newFakeFiler(), newFakeBlobs() + f.entries = frozen.Entries + c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) + if err != nil { + t.Fatal(err) + } + c.now = func() time.Time { return time.Unix(1000, 0) } + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + if err := r.Put(context.Background(), "legacy-data", bytes.Repeat([]byte{0x41}, 8*4096)); err != nil { + t.Fatal(err) + } + for key, body := range frozen.Objects { + if err := r.Put(context.Background(), key, body); err != nil { + t.Fatal(err) + } + } + return f, c, r +} +func assertLegacyImage(t *testing.T, r *ChunkRemote) { + t.Helper() + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if h.RemoteLSN != 7 || len(h.Chunks) != 1 { + t.Fatalf("legacy image/frontier lost: %+v", h) + } + data, err := r.Get(context.Background(), h.Chunks[0].Key) + if err != nil || !bytes.Equal(data, bytes.Repeat([]byte{0x41}, 8*4096)) { + t.Fatalf("legacy bytes changed: %v", err) + } +} +func TestFormatUpgradeLegacyIncompleteFork(t *testing.T) { + for _, segmented := range []bool{false, true} { + name := "flat" + if segmented { + name = "segmented" + } + t.Run(name, func(t *testing.T) { + f, c, r := preF4ForkFixture(t, segmented) + _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}) + if err != nil { + t.Fatalf("old incomplete fork retry: %v", err) + } + dst, err := NewChunkRemote(f, r.b, path.Join(catBase, "v2")) + if err != nil { + t.Fatal(err) + } + assertLegacyImage(t, dst) + e, err := f.LookupEntry(context.Background(), path.Join(catBase, "v2"), headName) + if err != nil { + t.Fatal(err) + } + var doc struct{ Format int } + if json.Unmarshal(e.Content, &doc) != nil || doc.Format != 3 { + t.Fatal("fork data must be format3") + } + }) + } +} +func TestFormatUpgradeLegacyForkIdentityStillRefusesChangedImage(t *testing.T) { + for _, segmented := range []bool{false, true} { + t.Run(map[bool]string{false: "flat", true: "segmented"}[segmented], func(t *testing.T) { + f, c, _ := preF4ForkFixture(t, segmented) + p := snapPath(t, f, "v1", "s1") + var s snapDoc + if err := json.Unmarshal(f.entries[p].Content, &s); err != nil { + t.Fatal(err) + } + var h map[string]any + if err := json.Unmarshal(s.Head, &h); err != nil { + t.Fatal(err) + } + // Preserve generation/frontier: only immutable content identity changes. + if segmented { + ref := h["segments"].(map[string]any)["0"].(map[string]any) + sum := ref["sha256"].([]any) + sum[0] = float64((int(sum[0].(float64)) + 1) % 256) + } else { + ref := h["chunks"].(map[string]any)["0"].(map[string]any) + ref["sha256"] = strings.Repeat("0", 64) + } + s.Head, _ = json.Marshal(h) + f.entries[p].Content, _ = json.Marshal(s) + if _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("changed image admitted or identity not reached: %v", err) + } + }) + } +} +func TestFormatUpgradeLegacySnapshotAndDelete(t *testing.T) { + t.Run("snapshot", func(t *testing.T) { + f, c, r := preF4ForkFixture(t, false) + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "upgraded", RequestID: "new-snapshot"}, h); err != nil { + t.Fatalf("legacy snapshot: %v", err) + } + e := f.entries[snapPath(t, f, "v1", "upgraded")] + var s snapDoc + if err := json.Unmarshal(e.Content, &s); err != nil { + t.Fatal(err) + } + var doc struct{ Format int } + json.Unmarshal(s.Head, &doc) + if doc.Format != 3 { + t.Fatal("snapshot contains flat data") + } + assertLegacyImage(t, r) + }) + t.Run("delete", func(t *testing.T) { + f, c, r := preF4ForkFixture(t, false) + for p := range f.entries { + if p != path.Join(catBase, "v1", headName) && p != path.Join(catBase, "v1", volumeName) && !bytes.Contains([]byte(p), []byte("/keys/")) { + delete(f.entries, p) + } + } + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + h.Holder = "" + h.Epoch = 0 + f.entries[path.Join(catBase, "v1", headName)] = legacyHeadFixture(t, h) + c.retainHook = func(stage, _ string) { + if stage == hookHeadMarked { + assertLegacyImage(t, r) + e := f.entries[path.Join(catBase, "v1", headName)] + var d struct{ Format int } + json.Unmarshal(e.Content, &d) + if d.Format != 3 { + t.Fatal("delete mark contains flat data") + } + } + } + res, err := c.DeleteVolume(context.Background(), "v1", nil) + if err != nil || !res.Completed { + t.Fatalf("legacy delete: %+v %v", res, err) + } + }) +} + +type legacyUpgradeView struct{} + +func (legacyUpgradeView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, Healthy: true} +} +func TestFormatUpgradeLegacyProviderTakeover(t *testing.T) { + f, _, r := preF4ForkFixture(t, false) + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-new/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, legacyUpgradeView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("legacy provider takeover: %v", err) + } + h, err := r.GetHead(ctx) + if err != nil || h.Holder != "node-new/r1" || h.Epoch != 2 { + t.Fatalf("takeover not installed: %+v %v", h, err) + } + e := f.entries[path.Join(catBase, "v1", headName)] + var d struct{ Format int } + json.Unmarshal(e.Content, &d) + if d.Format != 3 { + t.Fatal("takeover wrote flat data") + } + for i := uint32(0); i < 8; i++ { + got, err := s.Read(i) + if err != nil || !bytes.Equal(got, bytes.Repeat([]byte{0x41}, 4096)) { + t.Fatalf("takeover bytes %d: %v", i, err) + } + } + assertLegacyImage(t, r) +} diff --git a/seaweed-block/core/frontend/chunkstore/format_refusal_test.go b/seaweed-block/core/frontend/chunkstore/format_refusal_test.go new file mode 100644 index 0000000000..1fc6471d0a --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_refusal_test.go @@ -0,0 +1,105 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "encoding/json" + "path" + "testing" +) + +func TestManifestFormatUpgradeRejectsUnsupportedOrInconsistentObjects(t *testing.T) { + type mutation func(map[string]any) + for _, tc := range []struct { + name string + segment bool + change mutation + }{ + {"levels", false, func(v map[string]any) { v["levels"] = 2 }}, + {"missing-levels", false, func(v map[string]any) { delete(v, "levels") }}, + {"head-version", false, func(v map[string]any) { v["format"] = 4 }}, + {"head-unknown", false, func(v map[string]any) { v["future"] = true }}, + {"segment-version-ref", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["seg_format"] = 3 }}, + {"root-max", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["max_birth_lsn"] = 41 }}, + {"root-max-future", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["max_birth_lsn"] = 43 }}, + {"segment-version", true, func(v map[string]any) { v["format"] = 3 }}, + {"segment-unknown", true, func(v map[string]any) { v["future"] = true }}, + {"segment-max", true, func(v map[string]any) { v["max_birth_lsn"] = 41 }}, + {"segment-max-missing", true, func(v map[string]any) { delete(v, "max_birth_lsn") }}, + {"computed-max", true, func(v map[string]any) { + for _, entry := range v["chunks"].(map[string]any) { + entry.(map[string]any)["birth_lsn"] = 41 + } + }}, + {"encoding", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["enc"] = "zstd" }}, + {"birth-future", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["birth_lsn"] = 43 }}, + {"birth-missing", true, func(v map[string]any) { delete(v["chunks"].(map[string]any)["0"].(map[string]any), "birth_lsn") }}, + {"hash-shape", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["sha256"] = "bad" }}, + } { + t.Run(tc.name, func(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + r, h := publishSegmented(t, f, b) + ctx := context.Background() + e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) + if err != nil { + t.Fatal(err) + } + var root map[string]any + if err := json.Unmarshal(e.Content, &root); err != nil { + t.Fatal(err) + } + if tc.segment { + body, err := r.Get(ctx, h.Segments[0].Key) + if err != nil { + t.Fatal(err) + } + var object map[string]any + if err := json.Unmarshal(body, &object); err != nil { + t.Fatal(err) + } + tc.change(object) + body, err = json.Marshal(object) + if err != nil { + t.Fatal(err) + } + if err := r.Put(ctx, "malformed-segment", body); err != nil { + t.Fatal(err) + } + ref := root["segments"].(map[string]any)["0"].(map[string]any) + ref["key"] = qualifyManifestKey("v1", "malformed-segment") + ref["sha256"] = sha256.Sum256(body) + } else { + tc.change(root) + } + e.Content, err = json.Marshal(root) + if err != nil { + t.Fatal(err) + } + if err := f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + if _, err := r.GetHead(ctx); err == nil { + t.Fatal("invalid persisted schema accepted") + } + }) + } +} + +func TestManifestFormatUpgradeReadsLegacyRootGoldens(t *testing.T) { + for _, body := range []string{ + `{"format":1,"gen":1,"epoch":1,"holder":"old","remote_lsn":7,"chunks":{"0":{"key":"old","sha256":"0000000000000000000000000000000000000000000000000000000000000000"}}}`, + `{"format":2,"gen":1,"epoch":1,"holder":"old","remote_lsn":7,"chunk_bytes":4096,"chunk_count":1,"segments":{"0":{"key":"@v1/old","sha256":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"owner":"v1","count":1}}}`, + } { + h, err := DecodeHeadDocument("legacy", []byte(body)) + if err != nil { + t.Fatal(err) + } + if h.Segments == nil { + if h.Chunks[0].Encoding != "full" || h.Chunks[0].BirthLSN != 7 { + t.Fatal("legacy flat frontier not inherited") + } + } else if h.Segments[0].SegFormat != 1 || h.Segments[0].MaxBirthLSN != 7 { + t.Fatal("legacy segment maximum not inherited") + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/format_reuse_test.go b/seaweed-block/core/frontend/chunkstore/format_reuse_test.go new file mode 100644 index 0000000000..7b738b075d --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_reuse_test.go @@ -0,0 +1,185 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "path" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func legacySegmentedFixture(t *testing.T) (*ChunkRemote, *fakeBlobs, storage.ChunkHead) { + t.Helper() + f, b, _, _, _ := gcFixture(t) + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + doc := segmentedHeadDoc{headIdentityDoc: headIdentityDoc{Format: 2, Gen: 1, Epoch: 1, Holder: "old", RemoteLSN: 42}, Segments: map[uint64]legacySegmentRefDoc{}, ChunkBytes: 4096, ChunkCount: 2} + for group := uint64(0); group < 2; group++ { + key := fmt.Sprintf("legacy-data-%d", group) + data := []byte{byte(0x41 + group)} + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + idx := group * (manifestSegmentBytes / 4096) + segment := legacySegmentDoc{Format: 1, Range: group, ChunkBytes: 4096, Owner: "v1", Chunks: map[uint64]legacyChunkRefDoc{idx: {Key: qualifyManifestKey("v1", key), SHA256: sha256.Sum256(data)}}} + body, err := json.Marshal(segment) + if err != nil { + t.Fatal(err) + } + segmentKey := fmt.Sprintf("legacy-segment-%d", group) + if err := r.Put(ctx, segmentKey, body); err != nil { + t.Fatal(err) + } + doc.Segments[group] = legacySegmentRefDoc{Key: qualifyManifestKey("v1", segmentKey), SHA256: sha256.Sum256(body), Owner: "v1", Count: 1} + } + e := legacyHeadFixture(t, storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "old", RemoteLSN: 42}) + e.Content, err = json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + if err := f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + h, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + return r, b.fakeBlobs, h +} + +func TestManifestFormatUpgradeReusesColdSegmentsWithoutUploads(t *testing.T) { + r, b, base := legacySegmentedFixture(t) + ctx := context.Background() + before, _, _ := b.counts() + unchanged, ids, err := r.PrepareManifest(ctx, base, base, base.ChunkBytes) + if err != nil { + t.Fatal(err) + } + after, _, _ := b.counts() + if before != after || len(ids) != 0 || unchanged.Segments[0] != base.Segments[0] || unchanged.Segments[1] != base.Segments[1] { + t.Fatal("zero changed groups uploaded a segment or intent") + } + next := base + next.RemoteLSN = 43 + next.Chunks = map[uint64]storage.ChunkRef{} + for idx, ref := range base.Chunks { + next.Chunks[idx] = ref + } + data := []byte{0x53} + if err := r.Put(ctx, "changed-data", data); err != nil { + t.Fatal(err) + } + idx := manifestSegmentBytes / base.ChunkBytes + next.Chunks[idx] = storage.ChunkRef{Key: qualifyManifestKey("v1", "changed-data"), SHA256: sha256.Sum256(data), Encoding: "full", BirthLSN: 43} + before, _, _ = b.counts() + updated, ids, err := r.PrepareManifest(ctx, base, next, base.ChunkBytes) + if err != nil { + t.Fatal(err) + } + after, _, _ = b.counts() + if after-before != 1 || len(ids) != 1 || updated.Segments[0] != base.Segments[0] || updated.Segments[1].SegFormat != 2 || updated.Segments[1].MaxBirthLSN != 43 { + t.Fatal("one changed group rewrote cold segments or lost the new format") + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, updated); err != nil { + t.Fatal(err) + } + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + h, err := r.GetHead(ctx) + if err != nil || h.Segments[0].SegFormat != 1 || h.Chunks[0].BirthLSN != 42 || h.Chunks[idx].BirthLSN != 43 { + t.Fatalf("mixed legacy/new image did not resolve: %+v %v", h, err) + } + got, err := r.Get(ctx, h.Chunks[idx].Key) + if err != nil || len(got) != 1 || got[0] != 0x53 { + t.Fatal("mixed root changed bytes") + } +} + +func TestManifestFormatUpgradeAllowsInheritedZeroBirth(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + base, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + data := []byte{0x57} + if err := r.Put(ctx, "zero-birth", data); err != nil { + t.Fatal(err) + } + next := storage.ChunkHead{Epoch: 1, Holder: "base", Chunks: map[uint64]storage.ChunkRef{0: {Key: "zero-birth", SHA256: sha256.Sum256(data), Encoding: "full", BirthLSN: 0}}} + next, ids, err := r.PrepareManifest(ctx, base, next, 4096) + if err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, next); err != nil { + t.Fatal(err) + } + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + h, err := r.GetHead(ctx) + if err != nil || h.Chunks[0].BirthLSN != 0 || h.Segments[0].MaxBirthLSN != 0 { + t.Fatalf("fresh base zero birth refused: %+v %v", h, err) + } +} + +func TestManifestFormatUpgradeSnapshotAndForkPreserveMetadata(t *testing.T) { + f, b, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "format3", RequestID: "format3"}, h); err != nil { + t.Fatal(err) + } + snapshotPath := snapPath(t, f, "v1", "format3") + e, err := f.LookupEntry(ctx, path.Dir(snapshotPath), path.Base(snapshotPath)) + if err != nil { + t.Fatal(err) + } + var snapshot struct { + Head struct { + Format int `json:"format"` + Levels int `json:"levels"` + } `json:"head"` + } + if err := json.Unmarshal(e.Content, &snapshot); err != nil || snapshot.Head.Format != 3 || snapshot.Head.Levels != 1 { + t.Fatalf("data snapshot embedded flat HEAD: %s %v", e.Content, err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "format3", Target: "v2", RequestID: "format3-fork"}); err != nil { + t.Fatal(err) + } + r, err := NewChunkRemote(f, b, path.Join(catBase, "v2")) + if err != nil { + t.Fatal(err) + } + fork, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if fork.RemoteLSN != h.RemoteLSN || len(fork.Chunks) != len(h.Chunks) { + t.Fatal("fork lost inherited frontier or chunk count") + } + for idx, ref := range h.Chunks { + if fork.Chunks[idx] != ref { + t.Fatal("fork changed owner, encoding, birth or stored-byte hash") + } + } + for group, ref := range h.Segments { + if fork.Segments[group] != ref { + t.Fatal("fork changed segment version or maximum") + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/format_sustained_test.go b/seaweed-block/core/frontend/chunkstore/format_sustained_test.go new file mode 100644 index 0000000000..3d514e261b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_sustained_test.go @@ -0,0 +1,113 @@ +package chunkstore + +import ( + "bytes" + "context" + "encoding/json" + "path" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestManifestFormatUpgradeSustainedWritesPastWALWithPeriodicFlush(t *testing.T) { + const blocks, blockSize, chunkBlocks = 1024, 4096, 64 + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + f, b := newFakeFiler(), newFakeBlobs() + r, err := NewChunkRemote(f, b, path.Join(catBase, "sustained")) + if err != nil { + t.Fatal(err) + } + s, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "source"), blocks, blockSize, storage.WALStoreOptions{ChunkBlocks: chunkBlocks, WMode: storage.WModeStrict}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { s.Close() }) + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: 1, Holder: "source", FreshFromHead: true, BarrierBound: 2, UploadConcurrency: 2}) + if err != nil { + t.Fatal(err) + } + walBytes := s.WALCapacityBytes() + if walBytes == 0 || walBytes > 128<<20 { + t.Fatalf("smoke WAL capacity outside bounded fixture: %d", walBytes) + } + batchBytes := uint64(blocks * blockSize) + rounds := int(walBytes/batchBytes) + 1 + var payload, last uint64 + var finalByte byte + for round := 0; round < rounds; round++ { + finalByte = byte(round%251 + 1) + data := bytes.Repeat([]byte{finalByte}, blocks*blockSize) + batch := make([][]byte, blocks) + for i := range batch { + batch[i] = data[i*blockSize : (i+1)*blockSize] + } + if _, err := s.WriteBatch(0, batch); err != nil { + t.Fatal(err) + } + last, err = s.Sync() + if err != nil { + t.Fatal(err) + } + payload += batchBytes + // Use the production periodic flusher, not a second checkpoint path. + for s.CheckpointLSN() < last { + select { + case <-ctx.Done(): + t.Fatalf("periodic Flush did not cover batch %d: %v", round, ctx.Err()) + case <-time.After(10 * time.Millisecond): + } + } + if (round+1)%4 == 0 || round+1 == rounds { + if _, err := l.Cut(ctx); err != nil { + t.Fatal(err) + } + } + } + if payload <= walBytes || s.FlushCount() == 0 { + t.Fatal("sustained fixture did not exceed WAL with periodic Flush") + } + h, err := r.GetHead(ctx) + if err != nil || h.RemoteLSN != last { + t.Fatalf("final frontier: %+v %v", h, err) + } + e, err := f.LookupEntry(ctx, path.Join(catBase, "sustained"), headName) + if err != nil { + t.Fatal(err) + } + var shape struct { + Format int `json:"format"` + Levels int `json:"levels"` + } + if err := json.Unmarshal(e.Content, &shape); err != nil || shape.Format != 3 || shape.Levels != 1 { + t.Fatal("sustained cut did not publish format3") + } + fresh, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "fresh"), blocks, blockSize, storage.WALStoreOptions{ChunkBlocks: chunkBlocks, WMode: storage.WModeStrict}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { fresh.Close() }) + if _, err := fresh.Recover(); err != nil { + t.Fatal(err) + } + if err := fresh.SeedChunkFrontier(last); err != nil { + t.Fatal(err) + } + if _, err := storage.AttachChunkLayer(fresh, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: 2, Holder: "fresh", FreshFromHead: true}); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{finalByte}, blockSize) + for lba := uint32(0); lba < blocks; lba++ { + got, err := fresh.Read(lba) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("fresh read block%d: %v", lba, err) + } + } + t.Logf("payload=%d > WAL=%d, checkpoint drains=%d, FlushCount=%d; full fresh lazy read exact", payload, walBytes, rounds, s.FlushCount()) +} diff --git a/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go b/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go new file mode 100644 index 0000000000..f758d1f4d0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go @@ -0,0 +1,125 @@ +package chunkstore + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "path" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestManifestFormatUpgradeFlatWriterNeverStoresData(t *testing.T) { + dataHead := storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{0: {Key: "k"}}} + if _, err := headEntry(dataHead); err == nil { + t.Fatal("flat writer accepted chunk-bearing HEAD without a manifest") + } + f, b, _, _, _ := gcFixture(t) + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + cur, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, dataHead); err == nil { + t.Fatal("direct CAS accepted geometry-free data") + } + after, err := r.GetHead(context.Background()) + if err != nil || after.Gen != cur.Gen { + t.Fatal("refused flat CAS changed HEAD") + } + empty, err := headEntry(storage.ChunkHead{Gen: 1, State: storage.ChunkHeadActive}) + if err != nil { + t.Fatal(err) + } + var shape struct { + Format int `json:"format"` + } + if err := json.Unmarshal(empty.Content, &shape); err != nil || shape.Format != 1 { + t.Fatal("empty flat root must remain writable") + } +} + +func TestManifestFormatUpgradeWritesVersionedStoredByteReferences(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + r, h := publishSegmented(t, f, b) + ctx := context.Background() + entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) + if err != nil { + t.Fatal(err) + } + var root struct { + Format int `json:"format"` + Levels int `json:"levels"` + Segments map[string]struct { + Format int `json:"seg_format"` + Max uint64 `json:"max_birth_lsn"` + } `json:"segments"` + } + if err := json.Unmarshal(entry.Content, &root); err != nil { + t.Fatal(err) + } + if root.Format != 3 || root.Levels != 1 || root.Segments["0"].Format != 2 || root.Segments["0"].Max != h.RemoteLSN { + t.Fatalf("missing format3/levels/segment2 metadata: %s", entry.Content) + } + body, err := r.Get(ctx, h.Segments[0].Key) + if err != nil { + t.Fatal(err) + } + var segment struct { + Format int `json:"format"` + Max uint64 `json:"max_birth_lsn"` + Chunks map[string]struct { + Encoding string `json:"enc"` + Birth uint64 `json:"birth_lsn"` + Hash string `json:"sha256"` + } `json:"chunks"` + } + if err := json.Unmarshal(body, &segment); err != nil { + t.Fatal(err) + } + if segment.Format != 2 || segment.Max != h.RemoteLSN || len(segment.Chunks) != 2 { + t.Fatalf("missing segment format/max: %s", body) + } + for _, ref := range segment.Chunks { + if ref.Encoding != "full" || ref.Birth != h.RemoteLSN || len(ref.Hash) != 64 { + t.Fatalf("invalid inherited chunk reference: %+v", ref) + } + } + resolved, err := r.GetHead(ctx) + if err != nil || len(resolved.Chunks) != 2 { + t.Fatalf("format3 roundtrip: %+v %v", resolved, err) + } +} + +func TestManifestFormatUpgradeRefusesUnknownSegmentField(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + r, h := publishSegmented(t, f, b) + ctx := context.Background() + if _, err := r.GetHead(ctx); err != nil { + t.Fatalf("valid legacy segment refused: %v", err) + } + ref := h.Segments[0] + body, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + // Keep the object hash valid: the refusal must come from the segment schema. + body = append(bytes.TrimSuffix(body, []byte("}")), []byte(",\"future_encoding\":\"unsupported\"}")...) + if err := r.Put(ctx, "format-upgrade-unknown-field", body); err != nil { + t.Fatal(err) + } + ref.Key = qualifyManifestKey(ref.Owner, "format-upgrade-unknown-field") + ref.SHA256 = sha256.Sum256(body) + h.Segments[0] = ref + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, h); err != nil { + t.Fatal(err) + } + if _, err := r.GetHead(ctx); err == nil { + t.Fatal("published segment with unknown field accepted") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 5d524d0c13..7e8bf522f5 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -230,6 +230,15 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e } if in.Segments != nil { h := storage.ChunkHead{Segments: in.Segments, ChunkBytes: in.ChunkBytes} + // Intents protect keys without carrying a published frontier. + // Validate segment maxima against the reference maxima here. + for group, ref := range h.Segments { + if ref.SegFormat == 0 { + ref.SegFormat = 1 + h.Segments[group] = ref + } + h.RemoteLSN = max(h.RemoteLSN, ref.MaxBirthLSN) + } for _, ref := range in.Segments { h.ManifestChunkCount += ref.Count } diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go index 3a296d2d37..00789d6bf4 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go @@ -164,7 +164,7 @@ func TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace(t *testing.T) { t.Fatalf("first unrooted mark: %+v %v", result, e) } *now = now.Add(time.Hour) - if result, e := g.Run(ctx); e != nil || result.Reclaimed != 1 { + if result, e := g.Run(ctx); e != nil || result.Reclaimed != 2 { t.Fatalf("deleted attempt retained chunks forever: %+v %v", result, e) } if _, e := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath)); e != nil { diff --git a/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go b/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go new file mode 100644 index 0000000000..d65183c90e --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go @@ -0,0 +1,62 @@ +package chunkstore + +import ( + "context" + "errors" + "path" + "reflect" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type rootCASFiler struct { + Filer + roots, children int + refuseChildren bool +} + +func (f *rootCASFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if name == headName { + f.roots++ + } else { + f.children++ + if f.refuseChildren { + return nil, errors.New("segment service unavailable") + } + } + return f.Filer.LookupEntry(ctx, dir, name) +} + +// A HEAD CAS validates root authority, not the availability of every immutable +// segment. Ordinary GetHead still resolves and verifies all segment contents. +func TestManifest_CASReadsOnlyRoot(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + _, h := publishSegmented(t, f, b) + tracked := &rootCASFiler{Filer: f, refuseChildren: true} + r, err := NewChunkRemote(tracked, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + next := h + next.RemoteLSN++ + gen, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next) + if err != nil { + t.Fatalf("root-only CAS must not depend on segments: %v", err) + } + if gen != h.Gen+1 || tracked.roots != 1 || tracked.children != 0 { + t.Fatalf("CAS gen=%d root reads=%d child reads=%d", gen, tracked.roots, tracked.children) + } + if _, err := r.GetHead(context.Background()); err == nil { + t.Fatal("GetHead skipped segment resolution") + } + tracked.refuseChildren = false + got, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if got.Gen != gen || got.RemoteLSN != next.RemoteLSN || !reflect.DeepEqual(got.Chunks, h.Chunks) || !reflect.DeepEqual(got.Segments, h.Segments) { + t.Fatalf("CAS changed content or lost frontier: %+v", got) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/head_decode.go b/seaweed-block/core/frontend/chunkstore/head_decode.go index fca0c37eff..699259088b 100644 --- a/seaweed-block/core/frontend/chunkstore/head_decode.go +++ b/seaweed-block/core/frontend/chunkstore/head_decode.go @@ -26,9 +26,30 @@ type flatHeadDoc struct { } type segmentedHeadDoc struct { headIdentityDoc - Segments map[uint64]storage.ChunkSegment `json:"segments"` - ChunkBytes uint64 `json:"chunk_bytes"` - ChunkCount int `json:"chunk_count"` + Segments map[uint64]legacySegmentRefDoc `json:"segments"` + ChunkBytes uint64 `json:"chunk_bytes"` + ChunkCount int `json:"chunk_count"` +} + +type legacySegmentRefDoc struct { + Key string `json:"key"` + SHA256 [32]byte `json:"sha256"` + Owner string `json:"owner"` + Count int `json:"count"` +} + +type segmentRefV3Doc struct { + legacySegmentRefDoc + MaxBirthLSN *uint64 `json:"max_birth_lsn"` + SegFormat int `json:"seg_format"` +} + +type levelHeadDoc struct { + headIdentityDoc + Levels int `json:"levels"` + Segments map[uint64]segmentRefV3Doc `json:"segments"` + ChunkBytes uint64 `json:"chunk_bytes"` + ChunkCount int `json:"chunk_count"` } func (d headIdentityDoc) document() headDoc { @@ -61,7 +82,29 @@ func decodeFormatHead(content []byte) (headDoc, error) { return headDoc{}, err } doc := segmented.headIdentityDoc.document() - doc.Segments, doc.ChunkBytes, doc.ChunkCount = segmented.Segments, segmented.ChunkBytes, segmented.ChunkCount + doc.Segments = make(map[uint64]storage.ChunkSegment, len(segmented.Segments)) + for group, ref := range segmented.Segments { + doc.Segments[group] = storage.ChunkSegment{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count, SegFormat: 1, MaxBirthLSN: doc.RemoteLSN} + } + doc.ChunkBytes, doc.ChunkCount = segmented.ChunkBytes, segmented.ChunkCount + return doc, nil + case 3: + var root levelHeadDoc + if err := decoder.Decode(&root); err != nil { + return headDoc{}, err + } + if root.Levels != 1 { + return headDoc{}, fmt.Errorf("chunkstore: unsupported levels %d", root.Levels) + } + doc := root.headIdentityDoc.document() + doc.Levels, doc.ChunkBytes, doc.ChunkCount = root.Levels, root.ChunkBytes, root.ChunkCount + doc.Segments = make(map[uint64]storage.ChunkSegment, len(root.Segments)) + for group, ref := range root.Segments { + if ref.MaxBirthLSN == nil || (ref.SegFormat != 1 && ref.SegFormat != 2) || *ref.MaxBirthLSN > root.RemoteLSN { + return headDoc{}, fmt.Errorf("chunkstore: invalid segment version/birth maximum") + } + doc.Segments[group] = storage.ChunkSegment{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count, SegFormat: ref.SegFormat, MaxBirthLSN: *ref.MaxBirthLSN} + } return doc, nil default: return headDoc{}, fmt.Errorf("chunkstore: unsupported HEAD format %d", discriminator.Format) diff --git a/seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go b/seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go new file mode 100644 index 0000000000..5df831bae3 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go @@ -0,0 +1,25 @@ +package chunkstore + +import ( + "encoding/hex" + "encoding/json" + "strconv" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Only old-reader fixtures bypass the production format-1 data-write refusal. +func legacyHeadFixture(t testing.TB, h storage.ChunkHead) *filerpb.Entry { + t.Helper() + doc := headDoc{Format: 1, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: h.State, Chunks: map[uint64]refDoc{}} + for idx, ref := range h.Chunks { + doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} + } + body, err := json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + return &filerpb.Entry{Name: headName, Content: body, Extended: map[string][]byte{extKind: []byte(kindChunkHead), extGen: []byte(strconv.FormatUint(h.Gen, 10)), extEpoch: []byte(strconv.FormatUint(h.Epoch, 10)), extHolder: []byte(h.Holder)}} +} diff --git a/seaweed-block/core/frontend/chunkstore/manifest.go b/seaweed-block/core/frontend/chunkstore/manifest.go index 9a4708655d..ee525f2213 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest.go +++ b/seaweed-block/core/frontend/chunkstore/manifest.go @@ -48,6 +48,9 @@ func validateRoot(h storage.ChunkHead) error { } count := 0 for group, ref := range h.Segments { + if (ref.SegFormat != 1 && ref.SegFormat != 2) || ref.MaxBirthLSN > h.RemoteLSN { + return errors.New("chunkstore: invalid segment version/birth maximum") + } if CheckVolumeID(ref.Owner) != nil || storage.ValidChunkKey(ref.Key) != nil || ref.Count <= 0 || uint64(ref.Count) > manifestSegmentBytes/h.ChunkBytes || group > ^uint64(0)/(manifestSegmentBytes/h.ChunkBytes) { return errors.New("chunkstore: invalid segment reference") } @@ -76,6 +79,12 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch groups := map[uint64]map[uint64]storage.ChunkRef{} canonical := make(map[uint64]storage.ChunkRef, len(next.Chunks)) for idx, ref := range next.Chunks { + if ref.Encoding == "" { + ref.Encoding, ref.BirthLSN = "full", next.RemoteLSN + } + if ref.Encoding != "full" || ref.BirthLSN > next.RemoteLSN { + return next, nil, errors.New("chunkstore: invalid chunk encoding/birth") + } ref.Key = qualifyManifestKey(owner, ref.Key) canonical[idx] = ref group := idx / per @@ -94,6 +103,9 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch // segment group. Keep the same qualified-key comparison for segment reuse. baseGroups := map[uint64]map[uint64]storage.ChunkRef{} for idx, ref := range base.Chunks { + if ref.Encoding == "" { + ref.Encoding, ref.BirthLSN = "full", base.RemoteLSN + } group := idx / per if baseGroups[group] == nil { baseGroups[group] = map[uint64]storage.ChunkRef{} @@ -104,10 +116,14 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch for group, chunks := range groups { old := baseGroups[group] if previous, ok := base.Segments[group]; ok && base.ChunkBytes == chunkBytes && reflect.DeepEqual(chunks, old) { + // Legacy groups keep a conservative upper bound until rewritten. + if previous.SegFormat == 0 { + previous.SegFormat, previous.MaxBirthLSN = 1, base.RemoteLSN + } next.Segments[group] = previous continue } - body, err := json.Marshal(segmentDoc{1, group, chunkBytes, owner, chunks}) + body, maxBirth, err := encodeSegmentV2(group, chunkBytes, owner, chunks) if err != nil { return next, nil, err } @@ -119,7 +135,7 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch return next, nil, err } key := fmt.Sprintf("seg/%x", nonce) - next.Segments[group] = storage.ChunkSegment{Key: qualifyManifestKey(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks)} + next.Segments[group] = storage.ChunkSegment{Key: qualifyManifestKey(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks), SegFormat: 2, MaxBirthLSN: maxBirth} uploads = append(uploads, upload{key, body}) } if err := validateRoot(next); err != nil { @@ -161,11 +177,11 @@ func (r *ChunkRemote) resolveManifest(ctx context.Context, h storage.ChunkHead) if len(body) > maxManifestBytes || sha256.Sum256(body) != ref.SHA256 { return h, errors.New("chunkstore: segment hash/size mismatch") } - var doc segmentDoc - if err := decodeManifestJSON(body, &doc); err != nil { + doc, err := decodeSegment(body, ref, h.RemoteLSN) + if err != nil { return h, err } - if doc.Format != 1 || doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count { + if doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count { return h, errors.New("chunkstore: invalid segment contents") } for idx, cr := range doc.Chunks { diff --git a/seaweed-block/core/frontend/chunkstore/manifest_format.go b/seaweed-block/core/frontend/chunkstore/manifest_format.go new file mode 100644 index 0000000000..bd5f852035 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest_format.go @@ -0,0 +1,105 @@ +package chunkstore + +import ( + "bytes" + "encoding/hex" + "encoding/json" + "errors" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type segmentChunkV2Doc struct { + Key string `json:"key"` + // SHA256 covers stored object bytes, before any encoding is decoded. + SHA256 string `json:"sha256"` + Encoding string `json:"enc"` + BirthLSN *uint64 `json:"birth_lsn"` +} + +type segmentV2Doc struct { + Format int `json:"format"` + Range uint64 `json:"range"` + ChunkBytes uint64 `json:"chunk_bytes"` + Owner string `json:"owner"` + MaxBirthLSN *uint64 `json:"max_birth_lsn"` + Chunks map[uint64]segmentChunkV2Doc `json:"chunks"` +} + +type legacyChunkRefDoc struct { + Key string + SHA256 [32]byte +} + +type legacySegmentDoc struct { + Format int `json:"format"` + Range uint64 `json:"range"` + ChunkBytes uint64 `json:"chunk_bytes"` + Owner string `json:"owner"` + Chunks map[uint64]legacyChunkRefDoc `json:"chunks"` +} + +func encodeSegmentV2(group, chunkBytes uint64, owner string, chunks map[uint64]storage.ChunkRef) ([]byte, uint64, error) { + doc := segmentV2Doc{Format: 2, Range: group, ChunkBytes: chunkBytes, Owner: owner, Chunks: map[uint64]segmentChunkV2Doc{}} + var maxBirth uint64 + for idx, ref := range chunks { + birth := ref.BirthLSN + doc.Chunks[idx] = segmentChunkV2Doc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:]), Encoding: ref.Encoding, BirthLSN: &birth} + maxBirth = max(maxBirth, birth) + } + doc.MaxBirthLSN = &maxBirth + body, err := json.Marshal(doc) + return body, maxBirth, err +} + +func decodeSegment(body []byte, ref storage.ChunkSegment, remoteLSN uint64) (segmentDoc, error) { + var discriminator struct { + Format int `json:"format"` + } + if err := decodeManifestJSON(body, &discriminator); err != nil { + return segmentDoc{}, err + } + if discriminator.Format != ref.SegFormat { + return segmentDoc{}, errors.New("chunkstore: segment format/reference mismatch") + } + d := json.NewDecoder(bytes.NewReader(body)) + d.DisallowUnknownFields() + result := segmentDoc{Chunks: map[uint64]storage.ChunkRef{}} + switch discriminator.Format { + case 1: + var doc legacySegmentDoc + if err := d.Decode(&doc); err != nil { + return result, err + } + result.Format, result.Range, result.ChunkBytes, result.Owner = doc.Format, doc.Range, doc.ChunkBytes, doc.Owner + for idx, cr := range doc.Chunks { + result.Chunks[idx] = storage.ChunkRef{Key: cr.Key, SHA256: cr.SHA256, Encoding: "full", BirthLSN: ref.MaxBirthLSN} + } + case 2: + var doc segmentV2Doc + if err := d.Decode(&doc); err != nil { + return result, err + } + if doc.MaxBirthLSN == nil || *doc.MaxBirthLSN != ref.MaxBirthLSN || *doc.MaxBirthLSN > remoteLSN { + return result, errors.New("chunkstore: segment birth maximum mismatch") + } + result.Format, result.Range, result.ChunkBytes, result.Owner = doc.Format, doc.Range, doc.ChunkBytes, doc.Owner + var maxBirth uint64 + for idx, cr := range doc.Chunks { + sum, err := hex.DecodeString(cr.SHA256) + if err != nil || len(sum) != 32 || cr.Encoding != "full" || cr.BirthLSN == nil || *cr.BirthLSN > remoteLSN { + return result, errors.New("chunkstore: invalid segment chunk encoding/hash/birth") + } + v := storage.ChunkRef{Key: cr.Key, Encoding: cr.Encoding, BirthLSN: *cr.BirthLSN} + copy(v.SHA256[:], sum) + result.Chunks[idx] = v + maxBirth = max(maxBirth, v.BirthLSN) + } + if maxBirth != *doc.MaxBirthLSN { + return result, errors.New("chunkstore: incorrect segment birth maximum") + } + default: + return result, errors.New("chunkstore: unsupported segment format") + } + return result, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/manifest_test.go b/seaweed-block/core/frontend/chunkstore/manifest_test.go index eb53976606..fa0309f434 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_test.go @@ -54,7 +54,7 @@ func TestManifest_CapturePublishesSegmentRoot(t *testing.T) { if err = json.Unmarshal(e.Content, &doc); err != nil { t.Fatal(err) } - if doc.Format != 2 || len(doc.Chunks) != 0 || len(doc.Segments) != 1 { + if doc.Format != 3 || len(doc.Chunks) != 0 || len(doc.Segments) != 1 { t.Fatalf("cut did not publish a small segmented root: %s", e.Content) } h, err := r.GetHead(ctx) diff --git a/seaweed-block/core/frontend/chunkstore/manifest_upgrade.go b/seaweed-block/core/frontend/chunkstore/manifest_upgrade.go new file mode 100644 index 0000000000..8a9887873b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest_upgrade.go @@ -0,0 +1,80 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func (c *Catalog) prepareLegacyHead(ctx context.Context, root string, base, next storage.ChunkHead, geo Geometry) (storage.ChunkHead, []string, error) { + if next.Segments != nil || len(next.Chunks) == 0 { + return next, nil, nil + } + if c.blobs == nil { + return next, nil, errors.New("chunkstore: legacy data upgrade needs blob storage") + } + r, err := NewChunkRemote(c.f, c.blobs, root) + if err != nil { + return next, nil, err + } + return r.PrepareManifest(ctx, base, next, uint64(geo.BlockSize)*uint64(geo.ChunkBlocks)) +} +func (c *Catalog) dropManifestIntents(ctx context.Context, root string, ids []string) { + for _, id := range ids { + c.dropIntent(ctx, root, id) + } +} + +// Fork identity is a persisted protocol. Old snapshots keep the pre-format-3 +// canonical encoding even when their next publication upgrades the manifest. +func snapshotHeadDigest(h storage.ChunkHead, embedded json.RawMessage) (string, error) { + var version struct { + Format int `json:"format"` + } + if err := json.Unmarshal(embedded, &version); err != nil { + return "", err + } + if version.Format == 3 { + return headDigest(h) + } + type oldHead struct { + Segments map[uint64]legacySegmentRefDoc `json:"segments,omitempty"` + ChunkBytes uint64 `json:"chunk_bytes,omitempty"` + ChunkCount int `json:"chunk_count,omitempty"` + Format int `json:"format"` + Gen uint64 `json:"gen"` + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + RemoteLSN uint64 `json:"remote_lsn"` + Chunks map[uint64]refDoc `json:"chunks,omitempty"` + State string `json:"state,omitempty"` + DetachedBy *detachedByDoc `json:"detachedBy,omitempty"` + } + d := oldHead{Format: version.Format, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: h.State} + if h.DetachedBy != nil { + d.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen} + } + if version.Format == 2 { + d.Segments = map[uint64]legacySegmentRefDoc{} + d.ChunkBytes = h.ChunkBytes + d.ChunkCount = h.ManifestChunkCount + for idx, ref := range h.Segments { + d.Segments[idx] = legacySegmentRefDoc{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count} + } + } else { + d.Chunks = map[uint64]refDoc{} + for idx, ref := range h.Chunks { + d.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} + } + } + body, err := json.Marshal(d) + if err != nil { + return "", err + } + sum := sha256.Sum256(body) + return hex.EncodeToString(sum[:]), nil +} diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go index 79e8eed28b..10109d3916 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -338,11 +338,20 @@ func publishTagged(t *testing.T, f *fakeFiler, b *fakeBlobs, vol, tag string, ch if err != nil { t.Fatal(err) } + h, ids, err := r.PrepareManifest(ctx, cur, h, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h) if err != nil { t.Fatal(err) } h.Gen = gen + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } return h } @@ -353,6 +362,19 @@ func TestCatalog_UsageFromManifests(t *testing.T) { f, b, c, h := catalogFixture(t) // HEAD: chunks 0 and 3 ctx := context.Background() full := uint64(catGeo.ChunkBlocks) * uint64(catGeo.BlockSize) + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + manifestBytes := func(head storage.ChunkHead) uint64 { + var total uint64 + for _, ref := range head.Segments { + body, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + total += uint64(len(body)) + } + return total + } + expectedManifestBytes := manifestBytes(h) if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { t.Fatal(err) } @@ -363,12 +385,13 @@ func TestCatalog_UsageFromManifests(t *testing.T) { if u.LiveChunks != 2 || u.LiveBytes != 2*full || len(u.Snapshots) != 1 || u.Snapshots[0].ExclusiveBytes != 0 { t.Fatalf("shared chunks: %+v", u) } - if u.StoredBindings != 2 || u.StoredBytes != 2*full || u.StoredUpperBound { + if u.StoredBindings != 3 || u.ManifestBindings != 1 || expectedManifestBytes == 0 || u.ManifestBytes != expectedManifestBytes || u.StoredBytes != 2*full+expectedManifestBytes || u.StoredUpperBound { t.Fatalf("stored: %+v; want 2 bindings, exact", u) } // HEAD moves on: chunk 0 is rewritten, so s1 alone holds the old one. - publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)}) + newHead := publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)}) + expectedManifestBytes += manifestBytes(newHead) u, err = c.Usage(ctx, "v1") if err != nil { t.Fatal(err) @@ -377,7 +400,7 @@ func TestCatalog_UsageFromManifests(t *testing.T) { // both of s1's chunks are now exclusive: the new HEAD uses e2 keys t.Fatalf("after HEAD moved: s1 exclusive %d, want %d", u.Snapshots[0].ExclusiveBytes, 2*full) } - if u.StoredBindings != 4 || u.StoredBytes != 4*full || u.StoredUpperBound { + if u.StoredBindings != 6 || u.ManifestBindings != 2 || u.ManifestBytes != expectedManifestBytes || u.StoredBytes != 4*full+expectedManifestBytes || u.StoredUpperBound { t.Fatalf("stored after HEAD moved: %+v; want 4 bindings, exact", u) } @@ -390,7 +413,7 @@ func TestCatalog_UsageFromManifests(t *testing.T) { if err != nil { t.Fatal(err) } - if len(u.Snapshots) != 0 || u.StoredBindings != 4 || !u.StoredUpperBound { + if len(u.Snapshots) != 0 || u.StoredBindings != 6 || !u.StoredUpperBound { t.Fatalf("after delete: %+v; want no snapshots, 4 bindings, upper bound", u) } } diff --git a/seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go b/seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go new file mode 100644 index 0000000000..a70a44babb --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go @@ -0,0 +1,53 @@ +package chunkstore + +import ( + "crypto/sha256" + "encoding/json" + "reflect" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func FuzzDecodeVersionedSegment(f *testing.F) { + sum := sha256.Sum256([]byte("stored bytes")) + refs := map[uint64]storage.ChunkRef{0: {Key: "@v1/k", SHA256: sum, Encoding: "full", BirthLSN: 7}} + body, _, err := encodeSegmentV2(0, 4096, "v1", refs) + if err != nil { + f.Fatal(err) + } + f.Add(body, uint8(2)) + legacy, err := json.Marshal(legacySegmentDoc{Format: 1, Range: 0, ChunkBytes: 4096, Owner: "v1", Chunks: map[uint64]legacyChunkRefDoc{0: {Key: "@v1/k", SHA256: sum}}}) + if err != nil { + f.Fatal(err) + } + f.Add(legacy, uint8(1)) + f.Add([]byte(`{"format":2,"format":1}`), uint8(2)) + f.Add([]byte(`{"format":3}`), uint8(3)) + f.Fuzz(func(t *testing.T, body []byte, version uint8) { + ref := storage.ChunkSegment{SegFormat: int(version), MaxBirthLSN: 7} + got, err := decodeSegment(body, ref, 7) + if err != nil { + return + } + if got.Format != 1 && got.Format != 2 { + t.Fatalf("accepted format %d", got.Format) + } + for _, cr := range got.Chunks { + if cr.Encoding != "full" || cr.BirthLSN > 7 { + t.Fatalf("accepted unsupported chunk metadata: %+v", cr) + } + } + if got.Format == 2 { + encoded, maxBirth, err := encodeSegmentV2(got.Range, got.ChunkBytes, got.Owner, got.Chunks) + if err != nil { + t.Fatal(err) + } + ref.MaxBirthLSN = maxBirth + again, err := decodeSegment(encoded, ref, 7) + if err != nil || !reflect.DeepEqual(got, again) { + t.Fatalf("round trip: %+v / %+v: %v", got, again, err) + } + } + }) +} diff --git a/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_false.json b/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_false.json new file mode 100644 index 0000000000..a544d45c09 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_false.json @@ -0,0 +1 @@ +{"Entries":{"/swblock/chunks/v1/HEAD":{"name":"HEAD","attributes":{"file_size":190,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.epoch":"MQ==","swb.gen":"Mg==","swb.holder":"b2xk","swb.kind":"Y2h1bmtoZWFk"},"content":"eyJmb3JtYXQiOjEsImdlbiI6MiwiZXBvY2giOjEsImhvbGRlciI6Im9sZCIsInJlbW90ZV9sc24iOjcsImNodW5rcyI6eyIwIjp7ImtleSI6ImxlZ2FjeS1kYXRhIiwic2hhMjU2IjoiNWZmMDc0ZGRhZDg4YjdmY2I0MzM5Y2I3YTNlNjgzNDEwNjE3OTI4NjllNDM2NzNiMmRlODUyNWE3NTQ3NmJkOCJ9fSwic3RhdGUiOiJhY3RpdmUifQ=="},"/swblock/chunks/v1/VOLUME":{"name":"VOLUME","attributes":{"file_size":139,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiY3JlYXRlIiwiY3JlYXRlZF9ucyI6MTAwMDAwMDAwMDAwMCwicGFyZW50IjpudWxsfQ=="},"/swblock/chunks/v1/snapnames/s1":{"name":"s1","attributes":{"file_size":127,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi01NTJjZmRhNGU0YzI3YzA1","swb.kind":"Y2h1bmtzbmFwbmFtZQ==","swb.req":"b2xkLXNuYXBzaG90"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImF0dGVtcHQiOiIyLTU1MmNmZGE0ZTRjMjdjMDUiLCJjcmVhdGVkX25zIjoxMDAwMDAwMDAwMDAwfQ=="},"/swblock/chunks/v1/snaps/s1/2-552cfda4e4c27c05":{"name":"2-552cfda4e4c27c05","attributes":{"file_size":442,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi01NTJjZmRhNGU0YzI3YzA1","swb.kind":"Y2h1bmtzbmFw","swb.req":"b2xkLXNuYXBzaG90","swb.snap.claims":"WyJ2Mi9vbGQtZm9yayJd","swb.snap.epoch":"MQ==","swb.snap.gen":"Mg==","swb.snap.lsn":"Nw==","swb.snap.state":"YWN0aXZl"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsImNyZWF0ZWRfYnkiOiIiLCJjb25zaXN0ZW5jeSI6ImNyYXNoIiwiaGVhZCI6eyJmb3JtYXQiOjEsImdlbiI6MiwiZXBvY2giOjEsImhvbGRlciI6Im9sZCIsInJlbW90ZV9sc24iOjcsImNodW5rcyI6eyIwIjp7ImtleSI6ImxlZ2FjeS1kYXRhIiwic2hhMjU2IjoiNWZmMDc0ZGRhZDg4YjdmY2I0MzM5Y2I3YTNlNjgzNDEwNjE3OTI4NjllNDM2NzNiMmRlODUyNWE3NTQ3NmJkOCJ9fSwic3RhdGUiOiJhY3RpdmUifSwiZ2VvbWV0cnkiOnsibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OH0sInBhcmVudCI6bnVsbCwibGFiZWxzIjpudWxsLCJleHBpcmVzX2F0X25zIjowfQ=="},"/swblock/chunks/v2/VOLUME":{"name":"VOLUME","attributes":{"file_size":384,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU=","swb.req":"b2xkLWZvcms="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYyIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiZm9yayIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsInBhcmVudCI6eyJ2b2x1bWVfaWQiOiJ2MSIsInNuYXBzaG90IjoiczEiLCJnZW4iOjJ9LCJmb3JrIjp7InJlcXVlc3RfaWQiOiJvbGQtZm9yayIsInNvdXJjZSI6InYxIiwic25hcHNob3QiOiJzMSIsInNvdXJjZV9nZW4iOjIsImhlYWRfc2hhMjU2IjoiNGZlZGEwZWY2ZTA1OGRjNzNmYmFlMWUyZWEwOGU3ZTdlMGVjZWE0OTk2NjY0Y2ViYTFjYTNmODA5ZGFiYTk3MiIsInJlbW90ZV9sc24iOjcsImNodW5rX2NvdW50IjoxLCJxdWFsaWZpZWRfcmVmcyI6MX19"}},"Objects":{}} diff --git a/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_true.json b/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_true.json new file mode 100644 index 0000000000..43bcb01966 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_true.json @@ -0,0 +1 @@ +{"Entries":{"/swblock/chunks/v1/HEAD":{"name":"HEAD","attributes":{"file_size":331,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.epoch":"MQ==","swb.gen":"Mg==","swb.holder":"b2xk","swb.kind":"Y2h1bmtoZWFk"},"content":"eyJzZWdtZW50cyI6eyIwIjp7ImtleSI6IkB2MS9zZWcvZTdiM2VkZGUwNTYwYTM3MjQxZTkxMDJkNjA3ZWJjMTQiLCJzaGEyNTYiOls3NSwyMTgsMTMyLDExMywxNTgsMTcxLDQ1LDIxNCwyMjUsMjE5LDEwNywxNzYsMTczLDQ4LDI0MiwxNTMsMTIsMjMwLDExOCwyMjcsOTAsMTQxLDI0Nyw0LDExMSw1Nyw0OSwyMzcsOTQsMTg0LDg0LDk0XSwib3duZXIiOiJ2MSIsImNvdW50IjoxfX0sImNodW5rX2J5dGVzIjozMjc2OCwiY2h1bmtfY291bnQiOjEsImZvcm1hdCI6MiwiZ2VuIjoyLCJlcG9jaCI6MSwiaG9sZGVyIjoib2xkIiwicmVtb3RlX2xzbiI6Nywic3RhdGUiOiJhY3RpdmUifQ=="},"/swblock/chunks/v1/VOLUME":{"name":"VOLUME","attributes":{"file_size":139,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiY3JlYXRlIiwiY3JlYXRlZF9ucyI6MTAwMDAwMDAwMDAwMCwicGFyZW50IjpudWxsfQ=="},"/swblock/chunks/v1/snapnames/s1":{"name":"s1","attributes":{"file_size":127,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi03ZDc0ZTg5MWU0MTZhMmI5","swb.kind":"Y2h1bmtzbmFwbmFtZQ==","swb.req":"b2xkLXNuYXBzaG90"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImF0dGVtcHQiOiIyLTdkNzRlODkxZTQxNmEyYjkiLCJjcmVhdGVkX25zIjoxMDAwMDAwMDAwMDAwfQ=="},"/swblock/chunks/v1/snaps/s1/2-7d74e891e416a2b9":{"name":"2-7d74e891e416a2b9","attributes":{"file_size":583,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi03ZDc0ZTg5MWU0MTZhMmI5","swb.kind":"Y2h1bmtzbmFw","swb.req":"b2xkLXNuYXBzaG90","swb.snap.claims":"WyJ2Mi9vbGQtZm9yayJd","swb.snap.epoch":"MQ==","swb.snap.gen":"Mg==","swb.snap.lsn":"Nw==","swb.snap.state":"YWN0aXZl"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsImNyZWF0ZWRfYnkiOiIiLCJjb25zaXN0ZW5jeSI6ImNyYXNoIiwiaGVhZCI6eyJzZWdtZW50cyI6eyIwIjp7ImtleSI6IkB2MS9zZWcvZTdiM2VkZGUwNTYwYTM3MjQxZTkxMDJkNjA3ZWJjMTQiLCJzaGEyNTYiOls3NSwyMTgsMTMyLDExMywxNTgsMTcxLDQ1LDIxNCwyMjUsMjE5LDEwNywxNzYsMTczLDQ4LDI0MiwxNTMsMTIsMjMwLDExOCwyMjcsOTAsMTQxLDI0Nyw0LDExMSw1Nyw0OSwyMzcsOTQsMTg0LDg0LDk0XSwib3duZXIiOiJ2MSIsImNvdW50IjoxfX0sImNodW5rX2J5dGVzIjozMjc2OCwiY2h1bmtfY291bnQiOjEsImZvcm1hdCI6MiwiZ2VuIjoyLCJlcG9jaCI6MSwiaG9sZGVyIjoib2xkIiwicmVtb3RlX2xzbiI6Nywic3RhdGUiOiJhY3RpdmUifSwiZ2VvbWV0cnkiOnsibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OH0sInBhcmVudCI6bnVsbCwibGFiZWxzIjpudWxsLCJleHBpcmVzX2F0X25zIjowfQ=="},"/swblock/chunks/v2/VOLUME":{"name":"VOLUME","attributes":{"file_size":384,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU=","swb.req":"b2xkLWZvcms="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYyIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiZm9yayIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsInBhcmVudCI6eyJ2b2x1bWVfaWQiOiJ2MSIsInNuYXBzaG90IjoiczEiLCJnZW4iOjJ9LCJmb3JrIjp7InJlcXVlc3RfaWQiOiJvbGQtZm9yayIsInNvdXJjZSI6InYxIiwic25hcHNob3QiOiJzMSIsInNvdXJjZV9nZW4iOjIsImhlYWRfc2hhMjU2IjoiY2U3OTJiODQ3NWQ2OGY3OTcwNzNlMTA0Nzc1NTFlYmUzYzBlMTQ2NzdmNTNmYjIxMzZkYmM2MDQ4YmVlODU1MSIsInJlbW90ZV9sc24iOjcsImNodW5rX2NvdW50IjoxLCJxdWFsaWZpZWRfcmVmcyI6MX19"}},"Objects":{"seg/e7b3edde0560a37241e9102d607ebc14":"eyJmb3JtYXQiOjEsInJhbmdlIjowLCJjaHVua19ieXRlcyI6MzI3NjgsIm93bmVyIjoidjEiLCJjaHVua3MiOnsiMCI6eyJLZXkiOiJAdjEvbGVnYWN5LWRhdGEiLCJTSEEyNTYiOls5NSwyNDAsMTE2LDIyMSwxNzMsMTM2LDE4MywyNTIsMTgwLDUxLDE1NiwxODMsMTYzLDIzMCwxMzEsNjUsNiwyMywxNDYsMTM0LDE1OCw2NywxMDMsNTksNDUsMjMyLDgyLDkwLDExNyw3MSwxMDcsMjE2XX19fQ=="}} diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete.go b/seaweed-block/core/frontend/chunkstore/volume_delete.go index 0526990ae7..bfa4b8d787 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete.go @@ -244,17 +244,38 @@ func headDeletingOrDeleted(h storage.ChunkHead) bool { // refuses to anyone else. func (c *Catalog) writeHead(ctx context.Context, root string, cur, next storage.ChunkHead) error { next.Gen = cur.Gen + 1 + var ids []string + if next.Segments == nil && len(next.Chunks) != 0 { + v, ok, err := c.ReadVolume(ctx, path.Base(root)) + if err != nil { + return err + } + if !ok { + return errors.New("chunkstore: legacy delete needs VOLUME geometry") + } + next, ids, err = c.prepareLegacyHead(ctx, root, cur, next, v.Geometry) + if err != nil { + c.dropManifestIntents(ctx, root, ids) + return err + } + } e, err := headEntry(next) if err != nil { + c.dropManifestIntents(ctx, root, ids) return err } if cur.Gen == 0 { - return c.f.CreateEntry(ctx, root, e, true) + err = c.f.CreateEntry(ctx, root, e, true) + } else { + err = c.f.UpdateEntry(ctx, root, e, map[string][]byte{ + extGen: []byte(strconv.FormatUint(cur.Gen, 10)), extEpoch: []byte(strconv.FormatUint(cur.Epoch, 10)), + }) } - return c.f.UpdateEntry(ctx, root, e, map[string][]byte{ - extGen: []byte(strconv.FormatUint(cur.Gen, 10)), - extEpoch: []byte(strconv.FormatUint(cur.Epoch, 10)), - }) + // Unknown publication retains protection; a later sweep can settle it. + if err == nil || lostCondition(err) { + c.dropManifestIntents(ctx, root, ids) + } + return err } func lostCondition(err error) bool { diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2fee16c71f..dc5a1cca97 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -365,6 +365,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h } cfg := storage.ChunkLayerConfig{ ChunkBlocks: p.cfg.ChunkBlocks, + RestoreChunkBytes: uint64(ws.BlockSize()) * uint64(p.cfg.ChunkBlocks), Epoch: lin.epoch, Holder: holder, FreshFromHead: h.fresh, diff --git a/seaweed-block/core/host/volume/chunk_control_adapter_test.go b/seaweed-block/core/host/volume/chunk_control_adapter_test.go index cac46d325a..c84cfb7877 100644 --- a/seaweed-block/core/host/volume/chunk_control_adapter_test.go +++ b/seaweed-block/core/host/volume/chunk_control_adapter_test.go @@ -3,7 +3,9 @@ package volume import ( "context" "encoding/json" + "fmt" "reflect" + "sync" "testing" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" @@ -19,6 +21,30 @@ type fakeChunkProvider struct { lastMin uint64 } +type adapterManifestFiler struct { + chunkstore.Filer + mu sync.Mutex + blobs map[string][]byte +} + +func (f *adapterManifestFiler) Put(_ context.Context, b []byte) (string, error) { + f.mu.Lock() + defer f.mu.Unlock() + id := fmt.Sprintf("fixture-%d", len(f.blobs)) + f.blobs[id] = append([]byte(nil), b...) + return id, nil +} + +func (f *adapterManifestFiler) Get(_ context.Context, id string) ([]byte, error) { + f.mu.Lock() + defer f.mu.Unlock() + b, ok := f.blobs[id] + if !ok { + return nil, chunkstore.ErrNotFound + } + return append([]byte(nil), b...), nil +} + func (f *fakeChunkProvider) CutVolume(_ context.Context, _ string, minLSN uint64) (storage.ChunkCutResult, error) { f.cuts++ f.lastMin = minLSN @@ -36,8 +62,17 @@ func adapterFixture(t *testing.T) (*fakeChunkProvider, ChunkControl) { t.Helper() head := storage.ChunkHead{Gen: 3, Epoch: 2, Holder: "r1", RemoteLSN: 9, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e2/c0/k1"}, 5: {Key: "chunks/e2/c5/k2"}}} + f := &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}} + r, err := chunkstore.NewChunkRemote(f, f, "/swblock/chunks/v1") + if err != nil { + t.Fatal(err) + } + head, _, err = r.PrepareManifest(context.Background(), storage.ChunkHead{}, head, 8*4096) + if err != nil { + t.Fatal(err) + } fp := &fakeChunkProvider{cut: storage.ChunkCutResult{H: 9, Head: head}} - cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), "/swblock/chunks") + cat, err := chunkstore.NewCatalog(f, "/swblock/chunks") if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/base_install_v3.go b/seaweed-block/core/storage/base_install_v3.go index f0297ae6ff..dba6fb0aaa 100644 --- a/seaweed-block/core/storage/base_install_v3.go +++ b/seaweed-block/core/storage/base_install_v3.go @@ -634,7 +634,15 @@ func (s *WALStore) markMapUnknownV3(lba uint64) { if v.ownedMap == nil { return } - v.mapEntries[lba/v.ownedMap.chunkBlocks].Unknown = true + e := &v.mapEntries[lba/v.ownedMap.chunkBlocks] + e.Unknown = true + // A BASE byte has no WAL record: inherit its image frontier, not an + // unrelated later write. Keep UNKNOWN conservative as before. + birth := s.nextLSN - 1 + if d := v.pub.current(); d.BaseState == BaseInstalling { + birth = d.BaseLSN + } + e.LSN = max(e.LSN, birth) } // InstalledBaseLSN reports a completed local BASE obligation, not a normal diff --git a/seaweed-block/core/storage/chunk_birth.go b/seaweed-block/core/storage/chunk_birth.go new file mode 100644 index 0000000000..c6862223a8 --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth.go @@ -0,0 +1,19 @@ +package storage + +// The caller holds captureMu exclusive, with no layer state lock held. +// An owned-map max is conservative: recovery can drop an unacked suffix +// while retaining its maximum. Bound it by the same-barrier cut frontier; +// the captured image has no later writes. Preserve lower inherited births. +func (l *chunkLayerImpl) captureBirths(candidates map[uint64]bool, frontier uint64) map[uint64]uint64 { + out := make(map[uint64]uint64, len(candidates)) + l.s.mu.RLock() + defer l.s.mu.RUnlock() + for idx := range candidates { + birth := frontier + if l.usesOwnedMapV3() { + birth = min(l.s.v3.mapEntries[idx].LSN, frontier) + } + out[idx] = birth + } + return out +} diff --git a/seaweed-block/core/storage/chunk_birth_budget_test.go b/seaweed-block/core/storage/chunk_birth_budget_test.go new file mode 100644 index 0000000000..5535c69edf --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_budget_test.go @@ -0,0 +1,65 @@ +package storage + +import ( + "testing" + "time" +) + +// Metadata-only maximum-volume/default-chunk shape; no volume-sized image or +// device is allocated. This measures the added sampler, not a complete cut. +func BenchmarkCaptureBirthsMaxVolumeDefaultChunk(b *testing.B) { + const count = 1 << 22 // ceil((16 TiB - 4 KiB) / 4 MiB) + candidates := make(map[uint64]bool, count) + s := &WALStore{v3: &walStoreV3State{mapEntries: make([]chunkLSNEntryV3, count), mapProof: newMapProofEpochV3()}} + for i := uint64(0); i < count; i++ { + candidates[i] = true + s.v3.mapEntries[i].LSN = i + 1 + } + l := &chunkLayerImpl{s: s} + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.captureMu.Lock() + out := l.captureBirths(candidates, count) + s.captureMu.Unlock() + if len(out) != count || out[0] != 1 || out[count-1] != count { + b.Fatal("worst-shape birth mismatch") + } + } +} +func TestCaptureBirthsIncludesStoreLockWait(t *testing.T) { + s := &WALStore{} + l := &chunkLayerImpl{s: s} + candidates := map[uint64]bool{0: true} + s.mu.Lock() + locked := true + done := make(chan map[uint64]uint64, 1) + t.Cleanup(func() { + if locked { + s.mu.Unlock() + } + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("sampler did not join") + } + }) + go func() { s.captureMu.Lock(); out := l.captureBirths(candidates, 7); s.captureMu.Unlock(); done <- out }() + select { + case out := <-done: + done <- out + t.Fatal("sampler bypassed store lock") + case <-time.After(25 * time.Millisecond): + } + s.mu.Unlock() + locked = false + select { + case out := <-done: + done <- out + if out[0] != 7 { + t.Fatal("legacy frontier changed") + } + case <-time.After(5 * time.Second): + t.Fatal("sampler did not finish after lock release") + } +} diff --git a/seaweed-block/core/storage/chunk_birth_export_test.go b/seaweed-block/core/storage/chunk_birth_export_test.go new file mode 100644 index 0000000000..08795edc5e --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_export_test.go @@ -0,0 +1,82 @@ +package storage + +import ( + "bytes" + "testing" +) + +// DroppedSuffixBirthStoreForTest exposes only the recovery fixture to the +// external-package regression, which uses chunkstore's real manifest builder. +func DroppedSuffixBirthStoreForTest(t *testing.T, remote ChunkRemote) *WALStore { + t.Helper() + s, path := newMappedCheckpointStoreV3(t) + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(1, blk(0xA1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, blk(0xA2)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, blk(0xA3)); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + if e := prepared.candidate.entries[0]; e.LSN != 3 || d.CheckpointLSN != 1 || d.W != 1 { + t.Fatalf("setup entry%+v cp%d W%d", e, d.CheckpointLSN, d.W) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatal(err) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + damageRecord(t, path, 2) + reopen := func() *WALStore { + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + return r + } + r := reopen() + if r.NextLSN() != 2 || r.v3.mapEntries[0].LSN != 3 { + t.Fatal("missing conservative maximum after dropped suffix") + } + if n, err := r.Write(1, blk(0xB2)); err != nil || n != 2 { + t.Fatalf("reused LSN %d: %v", n, err) + } + if _, err := r.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, r) + r.mu.Lock() + r.closed = true + r.mu.Unlock() + r2 := reopen() + if e := r2.v3.mapEntries[0]; e.LSN != 3 || !e.Unknown || r2.NextLSN() != 3 || !bytes.Equal(readV3(t, r2, 1), blk(0xB2)) { + t.Fatalf("recovered reused image: entry%+v next%d", e, r2.NextLSN()) + } + return r2 +} diff --git a/seaweed-block/core/storage/chunk_birth_manifest_test.go b/seaweed-block/core/storage/chunk_birth_manifest_test.go new file mode 100644 index 0000000000..062f36e959 --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_manifest_test.go @@ -0,0 +1,156 @@ +package storage_test + +import ( + "bytes" + "context" + "fmt" + "path" + "sort" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/protobuf/proto" +) + +// Only the metadata/blob transports are in memory; capture, recovery, +// PrepareManifest, segment encoding, CAS and resolved reads are production. +type birthFiler struct { + mu sync.Mutex + entries map[string]*filerpb.Entry +} + +func (f *birthFiler) LookupEntry(_ context.Context, d, n string) (*filerpb.Entry, error) { + f.mu.Lock() + defer f.mu.Unlock() + e := f.entries[path.Join(d, n)] + if e == nil { + return nil, chunkstore.ErrNotFound + } + return proto.Clone(e).(*filerpb.Entry), nil +} +func (f *birthFiler) CreateEntry(_ context.Context, d string, e *filerpb.Entry, excl bool) error { + f.mu.Lock() + defer f.mu.Unlock() + k := path.Join(d, e.Name) + if excl && f.entries[k] != nil { + return chunkstore.ErrExists + } + f.entries[k] = proto.Clone(e).(*filerpb.Entry) + return nil +} +func (f *birthFiler) UpdateEntry(_ context.Context, d string, e *filerpb.Entry, expected map[string][]byte) error { + f.mu.Lock() + defer f.mu.Unlock() + k := path.Join(d, e.Name) + old := f.entries[k] + if old == nil { + return chunkstore.ErrNotFound + } + for k, v := range expected { + if !bytes.Equal(old.Extended[k], v) { + return chunkstore.ErrPrecondition + } + } + f.entries[k] = proto.Clone(e).(*filerpb.Entry) + return nil +} +func (f *birthFiler) DeleteEntry(_ context.Context, d, n string, expected map[string][]byte) error { + f.mu.Lock() + defer f.mu.Unlock() + k := path.Join(d, n) + for key, v := range expected { + if f.entries[k] == nil || !bytes.Equal(f.entries[k].Extended[key], v) { + return chunkstore.ErrPrecondition + } + } + delete(f.entries, k) + return nil +} +func (f *birthFiler) ListEntries(_ context.Context, d, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + f.mu.Lock() + defer f.mu.Unlock() + var out []*filerpb.Entry + for k, e := range f.entries { + if path.Dir(k) == d && strings.HasPrefix(e.Name, prefix) && e.Name > after { + out = append(out, proto.Clone(e).(*filerpb.Entry)) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + if limit > 0 && len(out) > int(limit) { + out = out[:limit] + } + return out, nil +} + +type birthBlobs struct { + mu sync.Mutex + data map[string][]byte +} + +func (b *birthBlobs) Put(_ context.Context, d []byte) (string, error) { + b.mu.Lock() + defer b.mu.Unlock() + id := fmt.Sprint(len(b.data) + 1) + b.data[id] = bytes.Clone(d) + return id, nil +} +func (b *birthBlobs) Get(_ context.Context, id string) ([]byte, error) { + b.mu.Lock() + defer b.mu.Unlock() + d, ok := b.data[id] + if !ok { + return nil, chunkstore.ErrNotFound + } + return bytes.Clone(d), nil +} + +func TestChunkBirthDroppedSuffixPublishesWithRealManifest(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + f := &birthFiler{entries: map[string]*filerpb.Entry{}} + b := &birthBlobs{data: map[string][]byte{}} + remote, err := chunkstore.NewChunkRemote(f, b, "/birth/v1") + if err != nil { + t.Fatal(err) + } + s := storage.DroppedSuffixBirthStoreForTest(t, remote) + layer, err := storage.AttachChunkLayer(s, remote, storage.ChunkLayerConfig{ChunkBlocks: 4, Epoch: 2, Holder: "host-a"}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = layer.Close() }) + cut, err := layer.Cut(ctx) + if err != nil { + t.Fatalf("reused-LSN cut must publish without another write: %v", err) + } + h, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if cut.Head.RemoteLSN != 2 || h.RemoteLSN != 2 || h.Chunks[0].BirthLSN != 2 || h.Segments[0].MaxBirthLSN != 2 { + t.Fatalf("cut-image frontier/birth: %+v", h) + } + data, err := remote.Get(ctx, h.Chunks[0].Key) + if err != nil { + t.Fatal(err) + } + want := make([]byte, 4*4096) + copy(want[4096:], bytes.Repeat([]byte{0xB2}, 4096)) + if !bytes.Equal(data, want) { + t.Fatal("published cut differs from recovered B2 image") + } + // The real builder's future-birth guard must still reject corrupt proposals. + invalid := h + invalid.Chunks = map[uint64]storage.ChunkRef{0: h.Chunks[0]} + ref := invalid.Chunks[0] + ref.BirthLSN = 3 + invalid.Chunks[0] = ref + if _, _, err := remote.PrepareManifest(ctx, h, invalid, 4*4096); err == nil { + t.Fatal("future birth was accepted") + } +} diff --git a/seaweed-block/core/storage/chunk_birth_migration_test.go b/seaweed-block/core/storage/chunk_birth_migration_test.go new file mode 100644 index 0000000000..987c7bab07 --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_migration_test.go @@ -0,0 +1,99 @@ +package storage + +import ( + "bytes" + "os" + "testing" +) + +func TestChunkBirthMigrationCarriesImageFrontier(t *testing.T) { + s, path := newChunkTestStore(t) + d := s.v3.pub.current() + mapPath := s.v3.ownedMap.fd.Name() + if err := s.Close(); err != nil { + t.Fatal(err) + } + src := MigrationSourceV3{UUID: d.UUID, VolumeSize: d.VolumeSize, ExtentSize: d.ExtentSize, BlockSize: d.BlockSize, OldWALOffset: 4096, OldWALSize: d.WALSize + 4096, CreatedAt: d.CreatedAt, CheckpointLSN: 7, ChunkBlocks: ctChunkBlocks} + plan, err := PrepareMigrationV3(mapPath, src) + if err != nil { + t.Fatal(err) + } + fd, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { fd.Close() }) + // Actual offline migration's map and slot encoder, on a small flushed + // image. No legacy engine or fabricated in-memory owned-map entries. + for _, part := range []struct { + offset int64 + data []byte + }{{MigrationSlotBOffset, plan.PreparedB}, {MigrationSlotAOffset, plan.CommittedA}, {MigrationSlotBOffset, plan.RolloverB}} { + if _, err := fd.WriteAt(part.data, part.offset); err != nil { + t.Fatal(err) + } + if err := fd.Sync(); err != nil { + t.Fatal(err) + } + } + want := makeBlock(ctBlockSize, 0x57) + if _, err := fd.WriteAt(want, int64(d.WALOffset+d.WALSize)); err != nil { + t.Fatal(err) + } + if err := fd.Sync(); err != nil { + t.Fatal(err) + } + if err := fd.Close(); err != nil { + t.Fatal(err) + } + r, err := OpenWALStoreWithOptions(path, WALStoreOptions{ChunkBlocks: ctChunkBlocks}) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { closeBounded(t, r) }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + l := mustAttach(t, r, f, ctConfig(1)) + newest, err := r.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x41)) + if err != nil { + t.Fatal(err) + } + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if cut.Head.Chunks[0].BirthLSN != 7 || cut.Head.Chunks[1].BirthLSN != newest { + t.Fatalf("migrated image birth lost: %+v", cut.Head) + } + if !bytes.Equal(f.imageOf(t, cut.Head)[:ctBlockSize], want) { + t.Fatal("migration cut changed inherited bytes") + } +} + +func TestChunkBirthSeededFrontierPreservesInheritedImage(t *testing.T) { + s, _ := newChunkTestStore(t) + if err := s.SeedChunkFrontier(7); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, 0x57)) + f.seedHead(t, image, 7, 1) + cfg := ctConfig(2) + cfg.FreshFromHead = true + l := mustAttach(t, s, f, cfg) + newest, err := s.Write(0, makeBlock(ctBlockSize, 0x41)) + if err != nil { + t.Fatal(err) + } + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if cut.Head.Chunks[1].BirthLSN != 7 || cut.Head.Chunks[0].BirthLSN != newest { + t.Fatalf("seeded image birth lost: %+v", cut.Head) + } +} diff --git a/seaweed-block/core/storage/chunk_birth_test.go b/seaweed-block/core/storage/chunk_birth_test.go new file mode 100644 index 0000000000..c442156f43 --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_test.go @@ -0,0 +1,177 @@ +package storage + +import ( + "bytes" + "context" + "sync" + "testing" + "time" +) + +func TestChunkBirthLegacyEngineUsesCutFrontierUpperBound(t *testing.T) { + s, _ := newLegacyChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + l := mustAttach(t, s, f, cfg) + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil { + t.Fatal(err) + } + last, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)) + if err != nil { + t.Fatal(err) + } + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + for _, idx := range []uint64{0, 1} { + if cr := cut.Head.Chunks[idx]; cr.Encoding != "full" || cr.BirthLSN != last { + t.Fatalf("legacy chunk %d metadata %+v, want frontier %d", idx, cr, last) + } + } + want := make([]byte, ctNumBlocks*ctBlockSize) + copy(want, makeBlock(ctBlockSize, 0x41)) + copy(want[ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, 0x42)) + assertImage(t, "legacy inherited image", f.imageOf(t, cut.Head), want) +} + +func TestChunkBirthBASEUsesInheritedFrontierIncludingZero(t *testing.T) { + for _, frontier := range []uint64{0, 7} { + t.Run(string(rune('0'+frontier)), func(t *testing.T) { + s, _, l := mappedBASELayerV3(t) + h, err := s.BeginBaseInstall(frontier, idA) + if err != nil { + t.Fatal(err) + } + if err := h.WriteBase(5, blk(0x55)); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + newest, err := s.Write(0, blk(0x41)) + if err != nil { + t.Fatal(err) + } + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if cut.Head.Chunks[1].BirthLSN != frontier || cut.Head.Chunks[0].BirthLSN != newest { + t.Fatalf("BASE birth drifted with unrelated WAL writes: %+v, inherited %d", cut.Head, frontier) + } + }) + } +} + +func TestChunkBirthCOWDoesNotObservePostBarrierWrite(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.FreshFromHead = true + cfg.BarrierBound = 0 + cfg.UploadConcurrency = 1 + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil { + t.Fatal(err) + } + before, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)) + if err != nil { + t.Fatal(err) + } + entered, release := make(chan struct{}), make(chan struct{}) + var once, releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + l.testCOWRead = func(idx uint64, _ bool) { + if idx == 0 { + once.Do(func() { close(entered) }) + <-release + } + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + done := make(chan error, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + cancel() + unblock() + select { + case <-joined: + case <-time.After(ctLocalBound): + t.Error("birth COW worker not joined") + } + }) + go func() { defer close(joined); _, err := l.Cut(ctx); done <- err }() + cowWaitSignal(t, entered, "copy after the birth barrier") + after, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x43)) + if err != nil { + t.Fatal(err) + } + unblock() + if err := waitErr(t, done, "birth COW cut"); err != nil { + t.Fatal(err) + } + cowWaitSignal(t, joined, "birth COW join") + first := f.installedHeads()[0] + if first.Chunks[1].BirthLSN != before || !bytes.Equal(f.imageOf(t, first)[ctChunkBlocks*ctBlockSize:(ctChunkBlocks+1)*ctBlockSize], makeBlock(ctBlockSize, 0x42)) { + t.Fatal("post-barrier write changed the saved image or its birth") + } + l.testCOWRead = nil + second, err := l.Cut(ctTimeout(t)) + if err != nil || second.Head.Chunks[1].BirthLSN != after { + t.Fatalf("next version lost post-barrier birth: %+v %v", second, err) + } +} + +func TestChunkBirthTracksNewestLocalWriteAtCut(t *testing.T) { + for _, bound := range []int{0, 1} { + t.Run(string(rune('0'+bound)), func(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.FreshFromHead = true + cfg.BarrierBound = bound + l := mustAttach(t, s, f, cfg) + x, err := s.Write(0, makeBlock(ctBlockSize, 0x41)) + if err != nil { + t.Fatal(err) + } + if _, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)); err != nil { + t.Fatal(err) + } + y, err := s.Write(ctChunkBlocks+1, makeBlock(ctBlockSize, 0x43)) + if err != nil { + t.Fatal(err) + } + first, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if first.Head.Chunks[0].BirthLSN != x || first.Head.Chunks[1].BirthLSN != y || first.Head.Chunks[0].Encoding != "full" || first.Head.RemoteLSN != y { + t.Fatalf("births did not preserve distinct local write frontiers: %+v, want %d/%d", first.Head, x, y) + } + z, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x44)) + if err != nil { + t.Fatal(err) + } + second, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if second.Head.Chunks[0] != first.Head.Chunks[0] || second.Head.Chunks[1].BirthLSN != z { + t.Fatal("rewrite changed a cold chunk birth or failed to advance the changed version") + } + for _, lba := range []uint32{ctChunkBlocks, ctChunkBlocks + 1} { + if _, err := s.Write(lba, makeBlock(ctBlockSize, 0)); err != nil { + t.Fatal(err) + } + } + third, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if _, exists := third.Head.Chunks[1]; exists || third.Head.Chunks[0] != first.Head.Chunks[0] { + t.Fatal("zero-chunk deletion retained a reference or changed the cold birth") + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index f3eef79172..ea6d6da91f 100644 --- a/seaweed-block/core/storage/chunk_fake_remote_test.go +++ b/seaweed-block/core/storage/chunk_fake_remote_test.go @@ -386,7 +386,7 @@ func (f *fakeChunkRemote) seedHead(t *testing.T, image []byte, remoteLSN, epoch key := fmt.Sprintf("seed/%d", idx) f.objs[key] = append([]byte(nil), c...) f.everStored[key] = true - head.Chunks[uint64(idx)] = chunkRef{Key: key, SHA256: sha256.Sum256(c)} + head.Chunks[uint64(idx)] = chunkRef{Key: key, SHA256: sha256.Sum256(c), Encoding: "full", BirthLSN: remoteLSN} } f.installLocked(head) } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 38be4fdc0e..8736b52936 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -780,11 +780,12 @@ func (l *chunkLayerImpl) MakeRemoteDurable(ctx context.Context, t uint64) error } type capturedChunk struct { - idx uint64 - data []byte - sum [32]byte - zero bool - key string // staged: already uploaded under this key (data is nil) + idx uint64 + data []byte + sum [32]byte + zero bool + key string // staged: already uploaded under this key (data is nil) + birth uint64 } // stagedChunk is a chunk pre-copied outside the barrier at chunk version @@ -907,6 +908,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.cutLSN = h baseHead := copyHead(l.head) l.stMu.Unlock() + // Candidates, mutation versions and births belong to the same barrier. + // Do not sample the owned map after COW writers are admitted again. + births := l.captureBirths(candidates, h) st.CandidateChunks = len(candidates) var copyErr error @@ -974,6 +978,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } var uploads []upload for _, c := range captured { + c.birth = births[c.idx] ref, had := baseHead.Chunks[c.idx] switch { case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum: @@ -986,7 +991,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch continue } if c.key != "" { // staged: uploaded before the barrier - next.Chunks[c.idx] = chunkRef{Key: c.key, SHA256: c.sum} + next.Chunks[c.idx] = chunkRef{Key: c.key, SHA256: c.sum, Encoding: "full", BirthLSN: c.birth} newKeys[c.idx] = c.key changed = append(changed, c.idx) st.StagedChunksUsed++ @@ -1019,7 +1024,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w: %w", errChunkRemoteUnavailable, err) } for _, u := range uploads { - next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum} + next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum, Encoding: "full", BirthLSN: u.c.birth} newKeys[u.c.idx] = u.key changed = append(changed, u.c.idx) st.UploadedChunks++ diff --git a/seaweed-block/core/storage/chunk_manifest.go b/seaweed-block/core/storage/chunk_manifest.go index 2125321931..c460c0fe99 100644 --- a/seaweed-block/core/storage/chunk_manifest.go +++ b/seaweed-block/core/storage/chunk_manifest.go @@ -5,14 +5,16 @@ import "context" // ChunkSegment names an immutable range manifest. Owner is the namespace in // which that manifest was encoded; forks preserve it without rewriting data. type ChunkSegment struct { - Key string `json:"key"` - SHA256 [32]byte `json:"sha256"` - Owner string `json:"owner"` - Count int `json:"count"` + Key string `json:"key"` + SHA256 [32]byte `json:"sha256"` + Owner string `json:"owner"` + Count int `json:"count"` + MaxBirthLSN uint64 `json:"max_birth_lsn"` + SegFormat int `json:"seg_format"` } // ChunkManifestBuilder prepares immutable segments before the existing root -// CAS. Returned intents belong to the cut and follow its settlement rules. +// CAS. Returned intents belong to the publishing caller and follow its settlement rules. type ChunkManifestBuilder interface { PrepareManifest(context.Context, ChunkHead, ChunkHead, uint64) (ChunkHead, []string, error) } diff --git a/seaweed-block/core/storage/chunk_restore.go b/seaweed-block/core/storage/chunk_restore.go index c95f8a9d1f..e34a11251b 100644 --- a/seaweed-block/core/storage/chunk_restore.go +++ b/seaweed-block/core/storage/chunk_restore.go @@ -57,11 +57,31 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi // A new holder's takeover starts serving the same image as active. The // previous holder's final-cut proof belongs only to its detached HEAD. next.State, next.DetachedBy = chunkHeadActive, nil + var intents []string + settled := true // no root RPC sent yet + defer func() { + if settled { + for _, id := range intents { + _ = remote.DeleteIntent(ctx, id) + } + } + }() + if builder, ok := remote.(ChunkManifestBuilder); ok && next.Segments == nil && len(next.Chunks) != 0 { + if cfg.RestoreChunkBytes == 0 { + return ChunkHead{}, errors.New("storage: legacy HEAD claim needs validated chunk geometry") + } + next, intents, err = builder.PrepareManifest(ctx, head, next, cfg.RestoreChunkBytes) + if err != nil { + return ChunkHead{}, err + } + } if err := allowed(); err != nil { return ChunkHead{}, err } + settled = false // an ambiguous CAS keeps its segment intents gen, casErr := remote.CASHead(ctx, ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, next) if casErr == nil { + settled = true next.Gen = gen return next, allowed() } @@ -71,6 +91,7 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi if readErr != nil { return ChunkHead{}, fmt.Errorf("storage: HEAD claim unresolved: %w", errors.Join(casErr, readErr)) } + settled = errors.Is(casErr, ErrChunkHeadPrecondition) || current.Gen > head.Gen if current.Gen > head.Gen && sameProposal(current, next) { return current, allowed() } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index a578fefcec..617a88ad7d 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -151,10 +151,12 @@ type chunkBitmapStore interface { } // chunkRef names one published chunk: its immutable key and the SHA-256 of -// its ChunkBlocks*BlockSize bytes. +// its stored object bytes, verified before any encoding is decoded. type chunkRef struct { - Key string - SHA256 [32]byte + Key string + SHA256 [32]byte + Encoding string + BirthLSN uint64 } // chunkHeadVersion is the CAS guard of HEAD. @@ -331,6 +333,9 @@ type chunkLayerConfig struct { // while its frontend is gated. An error leaves remote ownership unchanged. // No store/layer/remote lock is held across the callback. PrepareRestore func(head chunkHead) error + // RestoreChunkBytes is the local, validated geometry for upgrading a flat + // legacy image during an ownership claim; it is never inferred from data. + RestoreChunkBytes uint64 // CaptureAllowed is supplied by the store owner. It is an admission // check, made when a capture starts and again right before its HEAD CAS: // it refuses a cut during a BASE install or rebuild, or when this node is diff --git a/seaweed-block/core/storage/migrate_v3.go b/seaweed-block/core/storage/migrate_v3.go index 16ebb3964d..89c12c0e6b 100644 --- a/seaweed-block/core/storage/migrate_v3.go +++ b/seaweed-block/core/storage/migrate_v3.go @@ -107,7 +107,8 @@ func ValidateMigrationV3(src MigrationSourceV3) error { // PrepareMigrationV3 runs DESIGN 10.1 step 3 and builds the slot images of // steps 4 to 6. It (re)creates the initial map sidecar at mapPath durably: -// generation 1, every chunk UNKNOWN with maxWriteLSN 0, coveredCheckpoint = +// generation 1, every chunk UNKNOWN with its inherited checkpoint frontier, +// coveredCheckpoint = // the v2 checkpoint (a fully flushed WAL is not remote-clean). The slots // carry a fresh random nonce and the map fields of that root. It writes // nothing to the store file. @@ -141,6 +142,7 @@ func PrepareMigrationV3(mapPath string, src MigrationSourceV3) (MigrationPlanV3, entries := make([]chunkLSNEntryV3, int(shape.chunks)) for i := range entries { entries[i].Unknown = true + entries[i].LSN = src.CheckpointLSN } c, err := m.Prepare(1, src.CheckpointLSN, entries, nil) if err = errors.Join(err, m.Close()); err != nil { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e34a286148..35a961d925 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -439,6 +439,7 @@ Notes: | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | | `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | | `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE |