From c974574f8a8908570f7e7cb97dd6955a21febb0b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 22:14:22 -0800 Subject: [PATCH 01/11] test: the rejoin failure reports both replicas' log tails The primary's peer answer alone cannot tell a replica that never caught up from one that never answered; the failure now carries r2's and r3's logs. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/fence_heal_integration_test.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/fence_heal_integration_test.go b/seaweed-block/cmd/blockvolume/fence_heal_integration_test.go index c285e9bc05..cbbe480621 100644 --- a/seaweed-block/cmd/blockvolume/fence_heal_integration_test.go +++ b/seaweed-block/cmd/blockvolume/fence_heal_integration_test.go @@ -191,7 +191,9 @@ func fencingRoundHeal(t *testing.T, rejoin bool) { // not ready, and the gate then fences once more and continues r1 at the // next epoch, which is the designed answer to a primary that is not // ready, not a failure of the rejoin. - epoch := waitRejoinConverged(t, r1.status, 2, "r2", "r3") + epoch := waitRejoinConverged(t, r1.status, 2, func() string { + return "r2 log tail:\n" + r2.d.tail(40) + "\nr3 log tail:\n" + r3.d.tail(40) + }, "r2", "r3") if epoch > 2 { t.Logf("a further fencing round continued r1 at epoch %d after the pause", epoch) } @@ -210,7 +212,10 @@ func fencingRoundHeal(t *testing.T, rejoin bool) { // peer at that same e, all read in one pass; it returns e. Reading the epoch // once and then waiting for that exact epoch would fail if a further round // moved it in between. -func waitRejoinConverged(t *testing.T, statusAddr string, minEpoch uint64, rids ...string) uint64 { +// On failure it reports the last answer and dump(), the replicas' own logs: +// the primary's answer alone cannot tell a replica that never caught up from +// one that never answered. +func waitRejoinConverged(t *testing.T, statusAddr string, minEpoch uint64, dump func() string, rids ...string) uint64 { t.Helper() c := &http.Client{Timeout: 5 * time.Second} get := func(path string) []byte { @@ -256,7 +261,7 @@ func waitRejoinConverged(t *testing.T, statusAddr string, minEpoch uint64, rids return st.Epoch } } - t.Fatalf("the primary and %v never converged on one epoch >= %d; last answer: %s", rids, minEpoch, last) + t.Fatalf("the primary and %v never converged on one epoch >= %d; last answer: %s\n%s", rids, minEpoch, last, dump()) return 0 } From ffe16608dd9b08e83b52a0a3a2d21e58fd5c2817 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 23:06:30 -0800 Subject: [PATCH 02/11] fix: redraw pending volume identity after directory collision --- .../frontend/chunkstore/delete_sites_test.go | 1 + .../core/frontend/chunkstore/layout/create.go | 5 + .../volume_writer_repository_guard_test.go | 4 +- .../chunkstore/layout_collision_test.go | 47 ++++ .../core/frontend/chunkstore/layout_create.go | 14 ++ .../core/host/master/collision_safety_test.go | 202 ++++++++++++++++++ .../core/host/master/layout_collision_test.go | 85 ++++++++ seaweed-block/core/host/master/services.go | 11 +- .../lifecycle/layout_identity_guard_test.go | 2 + .../core/lifecycle/layout_redraw_test.go | 105 +++++++++ seaweed-block/core/lifecycle/store.go | 50 +++++ seaweed-block/docs/design/invariants.md | 4 +- .../design/volume-directory-collisions.md | 31 +++ 13 files changed, 558 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout_collision_test.go create mode 100644 seaweed-block/core/host/master/collision_safety_test.go create mode 100644 seaweed-block/core/host/master/layout_collision_test.go create mode 100644 seaweed-block/core/lifecycle/layout_redraw_test.go create mode 100644 seaweed-block/docs/design/volume-directory-collisions.md diff --git a/seaweed-block/core/frontend/chunkstore/delete_sites_test.go b/seaweed-block/core/frontend/chunkstore/delete_sites_test.go index 36fe22da5f..25b297e267 100644 --- a/seaweed-block/core/frontend/chunkstore/delete_sites_test.go +++ b/seaweed-block/core/frontend/chunkstore/delete_sites_test.go @@ -19,6 +19,7 @@ import ( // master's volume record, never from a name given plus an id read from // that same directory. A new site fails until it is classified here. var deleteSites = map[string]string{ + "core/frontend/chunkstore/layout_create.go LayoutStore.CreateVolumeRecord -> VolumeDir": "validation only after a rejected exclusive create: a valid full foreign VOLUME must name the already selected name/id8 directory; TestCreateVolumeExclusiveCollisionRedraws; no directory selection or removal", "core/frontend/chunkstore/startup_head_probe.go BCatalog.cleanStartupProbes -> DeleteEntry": "only exact reserved 32-hex probe directories observed before the full active-probe grace; nonrecursive HEAD and empty directory deletes, no volume directory (TestConditionalHeadNextStartCleansCrashLeftovers)", "core/frontend/chunkstore/startup_head_probe.go BCatalog.checkConditionalHead -> DeleteEntry": "only the disposable HEAD and empty random probe directory after successful exclusive create; no volume directory is used (TestCatalogStartupRequiresWrongGenerationHeadRefusal)", "cmd/sw-block/chunk_verify.go chunkVerify -> VolumeDir": "master-resolved full id and requested name; offline form accepts an explicit directory without discovering an identity", diff --git a/seaweed-block/core/frontend/chunkstore/layout/create.go b/seaweed-block/core/frontend/chunkstore/layout/create.go index ee41452b7e..2fcc9dfad0 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/create.go +++ b/seaweed-block/core/frontend/chunkstore/layout/create.go @@ -16,6 +16,11 @@ type NewVolumeStore interface { CreateVolumeRecord(ctx context.Context, v Volume) error } +// ErrDirectoryCollision means an exclusive VOLUME create found a valid, +// different full identity in the same name/id8 directory. Only a pending +// ordinary create may redraw its identity; readers still refuse the mismatch. +var ErrDirectoryCollision = fmt.Errorf("%w: volume directory collision", ErrIdentity) + // Unclaimed is the first HEAD of a volume: its id, epoch 0, no holder, no // claim id, idle, live, position 0, and current (nil for a new volume, the // copied root for a restore target). The first Start claims it from a diff --git a/seaweed-block/core/frontend/chunkstore/layout/volume_writer_repository_guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/volume_writer_repository_guard_test.go index 30eb2b8f84..cd6e8a0e31 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/volume_writer_repository_guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/volume_writer_repository_guard_test.go @@ -86,7 +86,9 @@ func TestVolumeWriterRepositorySites(t *testing.T) { "core/frontend/chunkstore/layout/read.go VolumeID VolumeName": 1, "core/frontend/chunkstore/layout/verify.go volumeID VolumeName": 1, "core/frontend/chunkstore/layout_create.go ReadVolumeRecord VolumeName": 1, - "core/frontend/chunkstore/layout_create.go CreateVolumeRecord VolumeName": 1, + // One exclusive create plus one read-only collision classification; + // TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal pins the latter. + "core/frontend/chunkstore/layout_create.go CreateVolumeRecord VolumeName": 2, } got := map[string]int{} root := filepath.Clean("../../../..") diff --git a/seaweed-block/core/frontend/chunkstore/layout_collision_test.go b/seaweed-block/core/frontend/chunkstore/layout_collision_test.go new file mode 100644 index 0000000000..2c79f9a1aa --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_collision_test.go @@ -0,0 +1,47 @@ +package chunkstore + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "testing" +) + +func TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal(t *testing.T) { + ctx := context.Background() + f := NewMemFiler() + cat, _ := NewBCatalog(f, newFakeBlobs(), "/blocks") + v := VolumeRef{Name: "v", ID: layout.VolumeID{1}} + foreign := v + foreign.ID[15] = 2 + g := layout.Geometry{SizeBytes: 1 << 20, BlockSize: 4096, ChunkBytes: 4 << 20} + if _, e := cat.CreateVolume(ctx, foreign, g); e != nil { + t.Fatal(e) + } + st, _ := cat.Store(v) + if _, _, e := st.ReadVolumeRecord(ctx); !errors.Is(e, layout.ErrIdentity) || errors.Is(e, layout.ErrDirectoryCollision) { + t.Fatalf("read allowed redraw: %v", e) + } + if _, e := cat.CreateVolume(ctx, v, g); !errors.Is(e, layout.ErrDirectoryCollision) || !errors.Is(e, layout.ErrIdentity) { + t.Fatalf("collision not classified: %v", e) + } + // A wrong full identity that does not belong in the selected id8 path is + // corruption, not evidence that a new random directory would heal it. + wrong := foreign + wrong.ID[0] = 3 + raw, e := (layout.Volume{ID: wrong.ID, Name: wrong.Name, Format: layout.VolumeFormat, Geometry: g}).Encode() + if e != nil { + t.Fatal(e) + } + entry, e := f.LookupEntry(ctx, "/blocks/"+v.Dir(), layout.VolumeName) + if e != nil { + t.Fatal(e) + } + entry.Content = raw + if e = f.UpdateEntry(ctx, "/blocks/"+v.Dir(), entry, nil); e != nil { + t.Fatal(e) + } + if _, e = cat.CreateVolume(ctx, v, g); !errors.Is(e, layout.ErrIdentity) || errors.Is(e, layout.ErrDirectoryCollision) { + t.Fatalf("corruption allowed redraw: %v", e) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_create.go b/seaweed-block/core/frontend/chunkstore/layout_create.go index b65f32e4f0..57858c0f52 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_create.go +++ b/seaweed-block/core/frontend/chunkstore/layout_create.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "path" "strconv" "time" @@ -94,6 +95,19 @@ func (s *LayoutStore) CreateVolumeRecord(ctx context.Context, v layout.Volume) e e.Extended = map[string][]byte{layoutKind: []byte("volume"), layoutVolume: []byte(s.id.String())} err = s.f.CreateEntry(ctx, s.root, e, true) if errors.Is(err, ErrExists) { + // Classify only the rejected exclusive VOLUME create, before any + // HEAD write. An ordinary read keeps the full-identity refusal. + existing, readErr := s.f.LookupEntry(ctx, s.root, layout.VolumeName) + if readErr != nil { + return readErr + } + got, decodeErr := layout.DecodeVolume(existing.Content) + if decodeErr != nil { + return fmt.Errorf("%w: VOLUME: %v", layout.ErrCorrupt, decodeErr) + } + if got.ID != v.ID && got.Name == v.Name && layout.VolumeDir(got.Name, got.ID) == path.Base(s.root) { + return layout.ErrDirectoryCollision + } return layout.ErrExists } return err diff --git a/seaweed-block/core/host/master/collision_safety_test.go b/seaweed-block/core/host/master/collision_safety_test.go new file mode 100644 index 0000000000..ffd012e329 --- /dev/null +++ b/seaweed-block/core/host/master/collision_safety_test.go @@ -0,0 +1,202 @@ +package master + +import ( + "bytes" + "context" + "crypto/sha256" + "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/protobuf/proto" + "path/filepath" + "sort" + "testing" + "time" +) + +type safetyFiler struct { + *chunkstore.MemFiler + entries map[string][]byte + writes int +} + +func (f *safetyFiler) CreateEntry(c context.Context, d string, e *filerpb.Entry, x bool) error { + err := f.MemFiler.CreateEntry(c, d, e, x) + if err == nil { + b, _ := proto.MarshalOptions{Deterministic: true}.Marshal(e) + f.entries[d+"/"+e.Name] = b + f.writes++ + } + return err +} +func (f *safetyFiler) UpdateEntry(c context.Context, d string, e *filerpb.Entry, x map[string][]byte) error { + err := f.MemFiler.UpdateEntry(c, d, e, x) + if err == nil { + b, _ := proto.MarshalOptions{Deterministic: true}.Marshal(e) + f.entries[d+"/"+e.Name] = b + f.writes++ + } + return err +} +func (f *safetyFiler) DeleteEntry(c context.Context, d, n string, x map[string][]byte) error { + err := f.MemFiler.DeleteEntry(c, d, n, x) + if err == nil { + delete(f.entries, d+"/"+n) + f.writes++ + } + return err +} + +type safetyBlobs struct { + data map[string][]byte + puts int +} + +func (b *safetyBlobs) Put(_ context.Context, d []byte) (string, error) { + b.puts++ + id := fmt.Sprint(b.puts) + b.data[id] = append([]byte(nil), d...) + return id, nil +} +func (b *safetyBlobs) Get(_ context.Context, id string) ([]byte, error) { + d, ok := b.data[id] + if !ok { + return nil, fmt.Errorf("missing %s", id) + } + return append([]byte(nil), d...), nil +} + +type safetyLease struct{} + +func (safetyLease) OldLeaseEnded(context.Context, uint64) error { return nil } +func safetyDigest(m map[string][]byte) string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + h := sha256.New() + for _, k := range keys { + fmt.Fprintf(h, "%d:%s:%d:", len(k), k, len(m[k])) + h.Write(m[k]) + } + return fmt.Sprintf("%x", h.Sum(nil)) +} + +func TestCollisionExistingVolumeSafety(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + h.cfg.WorkspaceRPC = true + f := &safetyFiler{MemFiler: chunkstore.NewMemFiler(), entries: map[string][]byte{}} + b := &safetyBlobs{data: map[string][]byte{}} + cat, err := chunkstore.NewBCatalog(f, b, "/collision") + if err != nil { + t.Fatal(err) + } + var foreign chunkstore.VolumeRef + var g layout.Geometry + var beforeMeta, beforeData string + var beforeWrites, beforePuts int + me := layout.HolderID{Epoch: 1, Holder: "existing-holder", ClaimID: "existing-claim"} + attach := func(name string) (*storage.WALStore, storage.ChunkLayer) { + t.Helper() + s, e := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), name), uint32(g.SizeBytes/uint64(g.BlockSize)), int(g.BlockSize), storage.WALStoreOptions{ChunkBlocks: uint32(g.ChunkBytes / uint64(g.BlockSize))}) + if e != nil { + t.Fatal(e) + } + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + r, e := chunkstore.NewLayoutRemote(cat, foreign, me) + if e != nil { + t.Fatal(e) + } + l, e := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: uint32(g.ChunkBytes / uint64(g.BlockSize)), Epoch: me.Epoch, Holder: me.Holder, FreshFromHead: true}) + if e != nil { + t.Fatal(e) + } + return s, l + } + want := bytes.Repeat([]byte{0xa7}, 4096) + attempts := 0 + h.cfg.LayoutCreateVolume = func(c context.Context, spec lifecycle.VolumeSpec) error { + id, e := layout.ParseVolumeID(spec.LayoutID) + if e != nil { + return e + } + ref := chunkstore.VolumeRef{Name: spec.VolumeID, ID: id} + attempts++ + if attempts == 1 { + foreign = ref + foreign.ID[15] ^= 1 + g = layout.Geometry{SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes} + if _, e = cat.CreateVolume(c, foreign, g); e != nil { + return e + } + st, _ := cat.Store(foreign) + if _, e = layout.Start(c, st, safetyLease{}, layout.HolderID{Epoch: 1, Holder: me.Holder}, layout.LocalRoot{Geometry: g, ClaimID: me.ClaimID, Fresh: true, CanStartFrom: func(layout.Head) error { return nil }}); e != nil { + return e + } + s, l := attach("seed") + if _, e = s.Write(0, want); e != nil { + t.Fatal(e) + } + if _, e = s.Sync(); e != nil { + t.Fatal(e) + } + if _, e = l.Capture(ctx); e != nil { + t.Fatal(e) + } + if e = s.Close(); e != nil { + t.Fatal(e) + } + beforeMeta = safetyDigest(f.entries) + beforeData = safetyDigest(b.data) + beforeWrites = f.writes + beforePuts = b.puts + } + _, e = cat.CreateVolume(c, ref, g) + return e + } + req := &control.CreateVolumeRequest{VolumeId: "v", SizeBytes: 1 << 20, ReplicationFactor: 1} + for i := 0; i < 1; i++ { + if _, e := newServices(h).CreateVolume(ctx, req); e == nil { + t.Fatal("collision unexpectedly healed; reassess witness") + } + } + if safetyDigest(f.entries) != beforeMeta || safetyDigest(b.data) != beforeData || f.writes != beforeWrites || b.puts != beforePuts { + t.Fatalf("SAFETY FAILURE metadata/data changed: writes %d->%d puts %d->%d", beforeWrites, f.writes, beforePuts, b.puts) + } + head, found, e := cat.ReadHead(ctx, foreign) + if e != nil || !found || head.Activity.Kind != layout.ActIdle { + t.Fatalf("HEAD lock/activity left: %+v %v", head, e) + } + t.Logf("BYTE_IDENTICAL metadata_sha256=%s blobs_sha256=%s successful_mutations=0 puts=0 directory=%s activity=idle", beforeMeta, beforeData, foreign.Dir()) + s, l := attach("after-collision") + defer s.Close() + got, e := s.Read(0) + if e != nil || !bytes.Equal(got, want) { + t.Fatalf("reattach/read old data failed: %v", e) + } + next := bytes.Repeat([]byte{0x3c}, 4096) + if _, e = s.Write(1, next); e != nil { + t.Fatal(e) + } + if _, e = s.Sync(); e != nil { + t.Fatal(e) + } + if _, e = l.Capture(ctx); e != nil { + t.Fatal(e) + } + got, e = s.Read(1) + if e != nil || !bytes.Equal(got, next) { + t.Fatalf("serve new write/read failed: %v", e) + } + t.Log("ATTACH_AND_SERVE_PASS old nonzero data read; new write synced, cut committed, read back; no lock left") +} diff --git a/seaweed-block/core/host/master/layout_collision_test.go b/seaweed-block/core/host/master/layout_collision_test.go new file mode 100644 index 0000000000..eb8c5bc751 --- /dev/null +++ b/seaweed-block/core/host/master/layout_collision_test.go @@ -0,0 +1,85 @@ +package master + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +type collisionBlobs struct{} + +func (collisionBlobs) Put(context.Context, []byte) (string, error) { + return "", errors.New("unexpected payload upload") +} +func (collisionBlobs) Get(context.Context, string) ([]byte, error) { + return nil, errors.New("unexpected payload read") +} + +// A full-id mismatch in an exclusively-created VOLUME is a directory collision, +// not a replay. The next create attempt must use a newly minted directory. +func TestCreateVolumeExclusiveCollisionRedraws(t *testing.T) { + ctx := context.Background() + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + h.cfg.WorkspaceRPC = true + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), collisionBlobs{}, "/collision") + if err != nil { + t.Fatal(err) + } + var first, foreign chunkstore.VolumeRef + var old layout.Volume + attempts := 0 + h.cfg.LayoutCreateVolume = func(ctx context.Context, spec lifecycle.VolumeSpec) error { + id, err := layout.ParseVolumeID(spec.LayoutID) + if err != nil { + return err + } + ref := chunkstore.VolumeRef{Name: spec.VolumeID, ID: id} + g := layout.Geometry{SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes} + attempts++ + if attempts == 1 { + first = ref + foreign = ref + foreign.ID[15] ^= 1 + if _, err := cat.CreateVolume(ctx, foreign, g); err != nil { + return err + } + old, err = cat.ReadVolume(ctx, foreign) + if err != nil { + return err + } + } + _, err = cat.CreateVolume(ctx, ref, g) + return err + } + req := &control.CreateVolumeRequest{VolumeId: "v", SizeBytes: 1 << 20, ReplicationFactor: 1} + // A retry is allowed, but it must heal the collision rather than stay stuck. + resp, err := newServices(h).CreateVolume(ctx, req) + if err != nil { + resp, err = newServices(h).CreateVolume(ctx, req) + } + if err != nil { + t.Fatalf("exclusive-create collision did not redraw: attempts=%d first=%s err=%v", attempts, first.ID, err) + } + id, err := layout.ParseVolumeID(resp.GetLayoutId()) + if err != nil { + t.Fatal(err) + } + next := chunkstore.VolumeRef{Name: "v", ID: id} + if !resp.GetStoreReady() || id == first.ID || next.Dir() == first.Dir() { + t.Fatalf("collision reused identity/directory: first=%s next=%s ready=%v", first.ID, id, resp.GetStoreReady()) + } + got, err := cat.ReadVolume(ctx, foreign) + if err != nil || got != old { + t.Fatalf("redraw altered the colliding volume: %v %v", got, err) + } + replay, err := newServices(h).CreateVolume(ctx, req) + if err != nil || replay.GetLayoutId() != id.String() { + t.Fatalf("settled identity changed on replay: %v %v", replay, err) + } +} diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index f42f816c41..d94e7b3e3a 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -12,10 +12,10 @@ import ( "github.com/seaweedfs/seaweed-block/core/auth" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" - "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" "github.com/seaweedfs/seaweed-block/core/lifecycle" "github.com/seaweedfs/seaweed-block/core/ops" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" "github.com/seaweedfs/seaweed-block/core/storeident" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -241,6 +241,15 @@ func (h *Host) createLifecycleVolume(ctx context.Context, spec lifecycle.VolumeS } } else { createErr = h.cfg.LayoutCreateVolume(ctx, rec.Spec) + if errors.Is(createErr, layout.ErrDirectoryCollision) { + // The rejected exclusive create wrote nothing to the colliding + // volume. Persist a fresh directory before the next RPC retries; + // ordinary store errors keep their original identity for replay. + if _, err := h.lifecycle.Volumes.RedrawPendingLayoutID(rec.Spec.VolumeID, rec.Spec.LayoutID); err != nil { + return lifecycle.VolumeRecord{}, fmt.Errorf("%w: directory collision; replacement not settled: %w", errLayoutStoreNotReady, err) + } + return lifecycle.VolumeRecord{}, fmt.Errorf("%w: directory collision; a fresh identity is recorded; retry", errLayoutStoreNotReady) + } } if createErr != nil { return lifecycle.VolumeRecord{}, fmt.Errorf("%w: %w", errLayoutStoreNotReady, createErr) diff --git a/seaweed-block/core/lifecycle/layout_identity_guard_test.go b/seaweed-block/core/lifecycle/layout_identity_guard_test.go index c47e805073..48e354f82f 100644 --- a/seaweed-block/core/lifecycle/layout_identity_guard_test.go +++ b/seaweed-block/core/lifecycle/layout_identity_guard_test.go @@ -16,6 +16,7 @@ func TestLayoutIdentityWriterAndReaders(t *testing.T) { // or a lifecycle record; its RPC containment is tested at catalog startup. mintSites := map[string]string{ "core/lifecycle/store.go CreateVolume": "durable lifecycle volume identity", + "core/lifecycle/store.go RedrawPendingLayoutID": "only a rejected unplaced ordinary create; TestRedrawPendingLayoutID and TestCreateVolumeExclusiveCollisionRedraws", "core/frontend/chunkstore/startup_head_probe.go checkConditionalHead": "disposable HEAD only, exclusive create in its random probe namespace; TestCatalogStartupRequiresWrongGenerationHeadRefusal", } seenMints := map[string]bool{} @@ -24,6 +25,7 @@ func TestLayoutIdentityWriterAndReaders(t *testing.T) { "core/lifecycle/store.go volumeSpecsCompatible": true, "core/lifecycle/store.go validateSpec": true, "core/lifecycle/store.go MarkStoreReady": true, + "core/lifecycle/store.go RedrawPendingLayoutID": true, "core/lifecycle/workload_plan.go PlanBlockVolumeWorkloads": true, "core/host/master/services.go lifecycleVolumeResponse": true, "core/host/master/services.go CreateVolume": true, diff --git a/seaweed-block/core/lifecycle/layout_redraw_test.go b/seaweed-block/core/lifecycle/layout_redraw_test.go new file mode 100644 index 0000000000..13536f4c26 --- /dev/null +++ b/seaweed-block/core/lifecycle/layout_redraw_test.go @@ -0,0 +1,105 @@ +package lifecycle + +import ( + "encoding/json" + "errors" + "os" + "os/exec" + "runtime" + "testing" +) + +func TestRedrawPendingLayoutID(t *testing.T) { + if os.Getenv("SWB_REDRAW_CHILD") != "1" { + cmd := exec.Command(os.Args[0], "-test.run=^TestRedrawPendingLayoutID$", "-test.v") + cmd.Env = append(os.Environ(), "SWB_REDRAW_CHILD=1") + if out, e := cmd.CombinedOutput(); e != nil { + t.Fatalf("child: %v\n%s", e, out) + } + return + } + hooks := &durableRecordHooks{} + if runtime.GOOS == "windows" { + hooks.dirSync = func(string) error { return nil } + } + durableRecordHooksForTest.Store(hooks) + defer durableRecordHooksForTest.Store(nil) + s, e := OpenFileStore(t.TempDir()) + if e != nil { + t.Fatal(e) + } + spec := VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1} + old, e := s.CreateVolume(spec) + if e != nil { + t.Fatal(e) + } + if _, e = s.RedrawPendingLayoutID("v", "00000000000000000000000000000001"); !errors.Is(e, ErrVolumeConflict) { + t.Fatalf("stale ID accepted: %v", e) + } + // A lost directory-sync reply after rename must settle the replacement + // from disk, even though the in-memory record still has the rejected ID. + fail := true + hooks.dirSync = func(string) error { + if fail { + return errors.New("lost directory sync") + } + return nil + } + if _, e = s.RedrawPendingLayoutID("v", old.Spec.LayoutID); e == nil { + t.Fatal("sync failure hidden") + } + cur, _ := s.GetVolume("v") + if cur != old { + t.Fatal("uncertain replacement published") + } + raw, e := os.ReadFile(s.path("v")) + if e != nil { + t.Fatal(e) + } + var disk VolumeRecord + if e = json.Unmarshal(raw, &disk); e != nil { + t.Fatal(e) + } + fail = false + got, e := s.RedrawPendingLayoutID("v", old.Spec.LayoutID) + if e != nil || got != disk || got.Spec.LayoutID[:8] == old.Spec.LayoutID[:8] { + t.Fatalf("replacement not settled: %+v %v", got, e) + } + reopened, e := OpenFileStore(s.dir) + if e != nil { + t.Fatal(e) + } + again, e := reopened.CreateVolume(spec) + if e != nil || again != got { + t.Fatalf("restart reminted: %+v %v", again, e) + } + if _, e = s.MarkStoreReady("v", got.Spec.LayoutID); e != nil { + t.Fatal(e) + } + if _, e = s.RedrawPendingLayoutID("v", got.Spec.LayoutID); !errors.Is(e, ErrVolumeConflict) { + t.Fatalf("ready identity redrawn: %v", e) + } + spec.VolumeID = "attached" + attached, e := s.CreateVolume(spec) + if e != nil { + t.Fatal(e) + } + if _, e = s.AttachVolume("attached", "host"); e != nil { + t.Fatal(e) + } + if _, e = s.RedrawPendingLayoutID("attached", attached.Spec.LayoutID); !errors.Is(e, ErrVolumeConflict) { + t.Fatalf("attached identity redrawn: %v", e) + } + spec.VolumeID = "restore" + spec.SourceVolume = "source" + spec.SourceLayoutID = got.Spec.LayoutID + spec.SourceSnapshot = "snap" + spec.CreateRequestID = "request" + restore, e := s.CreateVolume(spec) + if e != nil { + t.Fatal(e) + } + if _, e = s.RedrawPendingLayoutID("restore", restore.Spec.LayoutID); !errors.Is(e, ErrVolumeConflict) { + t.Fatalf("restore identity redrawn: %v", e) + } +} diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index d8b20c3644..fe8193f3e3 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -205,6 +205,56 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { return rec, nil } +// RedrawPendingLayoutID replaces only an unplaced ordinary create's rejected +// identity. The caller must have proved an exclusive VOLUME directory collision. +// A replacement whose directory-sync reply was lost is settled, never reminted. +func (s *FileStore) RedrawPendingLayoutID(volumeID, rejectedID string) (VolumeRecord, error) { + s.mu.Lock() + defer s.mu.Unlock() + rec, ok := s.records[volumeID] + if !ok { + return VolumeRecord{}, ErrVolumeNotFound + } + if rec.Spec.LayoutID != rejectedID || rec.StoreReady || rec.AttachedTo != "" || rec.Spec.SourceVolume != "" { + return VolumeRecord{}, ErrVolumeConflict + } + raw, err := os.ReadFile(s.path(volumeID)) + if err != nil { + return VolumeRecord{}, err + } + var disk VolumeRecord + if err := json.Unmarshal(raw, &disk); err != nil { + return VolumeRecord{}, err + } + // Apart from its identity, an uncertain replacement must be the exact + // same pending request. Never turn another record into this request. + oldID := disk.Spec.LayoutID + disk.Spec.LayoutID = rejectedID + if disk != rec { + return VolumeRecord{}, ErrVolumeConflict + } + disk.Spec.LayoutID = oldID + if _, err := layout.ParseVolumeID(oldID); err != nil { + return VolumeRecord{}, err + } + if oldID == rejectedID { + id, err := layout.NewVolumeID() + if err != nil { + return VolumeRecord{}, err + } + if id.String()[:8] == rejectedID[:8] { + return VolumeRecord{}, fmt.Errorf("lifecycle: replacement repeats the rejected directory; retry") + } + disk.Spec.LayoutID = id.String() + } + if err := s.putLocked(disk); err != nil { + return VolumeRecord{}, err + } + s.records[volumeID] = disk + s.publishLocked() + return disk, nil +} + // MarkStoreReady publishes the durable placement hint after the filer has // accepted both exclusive creates. A retry of the same create may repeat it; // another layout identity may not mark this record ready. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index bdf33b23eb..2a0e32f6fc 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -567,6 +567,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | no lifecycle record | named volume with immutable layout id | master lifecycle create mints the id once; a lost directory-sync reply settles the same record on retry. Lookup resolves the durable name/id without creating one; workload launch carries both and selects a local directory keyed by id | `core/lifecycle/store.go` `CreateVolume`; master `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient` `ResolveVolume`; launcher `blockVolumeArgs`; blockvolume `parseFlags` | `INV-SNAPK-VOLUME-DIR-001` | +| pending ordinary create with a proved id8 collision | pending create with a fresh durable layout id | rejected exclusive VOLUME create, valid foreign full identity belongs to the selected name/id8 directory; not ready, not attached, not a restore; persist replacement before retry, settle unknown rename on replay; never modify the colliding volume | `LayoutStore.CreateVolumeRecord`; `FileStore.RedrawPendingLayoutID`; master `createLifecycleVolume` | `INV-CREATE-DIR-COLLISION-001` | | idle | snap(s) | caller is the holder at HEAD's epoch (epoch, server and claim id); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` | | snap(s) | idle | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); over idle it succeeds without a write and means only that no activity remains; before resuming a failed stop, abort its still-open session and re-read HEAD: only matching live/idle resumes, detached goes Down, absent/unknown stays stopped | head.go `Head.Abort`; durable/provider_layout.go `settleLayoutStop` | `INV-SNAPK-ABORT-001` | | snap(s) | idle, current = root | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); the previous manifest builds to HEAD's current root; the new own chunks, every segment and the root are present; a new snapshot name records bounded retention facts once, while replay preserves them | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-COMMIT-REACH-001`, `INV-SNAPK-TXN-INTERRUPT-001`, `INV-SNAPK-SNAPSHOT-META-001` | @@ -785,6 +786,7 @@ Notes: | `INV-AUTH-ONE-REPLICATED-FACTOR-001` | CreateVolume admits a replicated volume only if the master can decide it: its replication factor equals the master's one slot count (--expected-slots-per-volume) and the lifecycle product loop runs (only that loop binds, mints and promotes it). | M2 none → Bound (a created replicated volume's first line) | `core/host/master/services.go` `CreateVolume`; `core/host/master/host.go` `Config.LifecycleProductLoop`; `core/authority/controller.go` `ExpectedSlotsPerVolume`, `validateVolumeTopology` | `TestAnRF2CreateOnAnRF3MasterIsRefusedAndFailoverContinues`, `TestAReplicatedCreateWithTheProductLoopOffIsRefused` (`core/host/master/create_rf_mismatch_test.go`) | — (an admission check). Limits: single-replica volumes are admitted at any slot count (they never reach the check); a static --topology file with a mismatched volume is not checked at start (a cluster spec is: `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001`) | ACTIVE | | `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001` | blockmaster refuses to start when its cluster spec holds a replicated volume it could never decide: one whose replication factor differs from --expected-slots-per-volume, or any while the lifecycle product loop is off (only that loop binds, mints and promotes it). | M2 none → Bound (a replicated cluster-spec volume's first line) | `cmd/blockmaster/product_loop_guard.go` `requireProductLoop`; `cmd/blockmaster/main.go` `run` | `TestReplicatedClusterSpecWithTheProductLoopOffIsRefused`, `TestTheProductLoopGuardPassesWhatItShould`, `TestAClusterSpecVolumeOfAnotherReplicationFactorIsRefused`, `TestAPlacementOnlyClusterSpecVolumeIsChecked` (`cmd/blockmaster/product_loop_guard_test.go`) | — (a startup configuration check). Limits: static `--topology` is not refused (its observation controller mints), and has no automatic failover in v1 | ACTIVE | | `INV-CREATE-ONE-IDENTITY-001` | One name, one layout identity; no directory but the record's holds a live HEAD (not none, not deleted). A served volume's deleted name is never created again. | M2 none → created (CreateVolume, restore target creation) | `core/host/master/services.go` `CreateVolume`, `createLifecycleVolume`; `core/frontend/chunkstore/layout/start.go` `Start` | `TestARefusedRestoreLeavesNoTargetRecord` (`core/host/master/restore_refusal_test.go`), `TestARealCatalogRestoreOfARestoreTargetLeavesNothing`, `TestAServedThenDeletedNameIsStillRefused` (`core/host/master/restore_refusal_catalog_test.go`), `TestCreateVolume` (`core/frontend/chunkstore/layout/create_test.go`), `TestDecodeHead_RefusesAnotherVolumesHead` (`core/frontend/chunkstore/layout/head_test.go`) | VolumeCreate OneIdentity (its second clause: a directory with a live HEAD is the record's). Scope: only a refused restore's record, which never left the creation phase (never assigned, never served), is removed, with no filer write. Limits: a served volume's deleted name stays refused until 1.1 | ACTIVE | +| `INV-CREATE-DIR-COLLISION-001` | Only a rejected exclusive VOLUME create proving a valid foreign full identity in the same name/id8 directory permits a pending ordinary create to replace its id. Ready, attached and restore records refuse replacement. No foreign metadata or payload is modified; a lost replacement sync reply settles its existing disk identity. | M2 pending create collision → pending create with fresh id | `core/frontend/chunkstore/layout_create.go` `CreateVolumeRecord`; `core/lifecycle/store.go` `RedrawPendingLayoutID`; `core/host/master/services.go` `createLifecycleVolume` | `TestCreateVolumeExclusiveCollisionRedraws`, `TestCollisionExistingVolumeSafety`, `TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal`, `TestRedrawPendingLayoutID` | VolumeCreate collision-redraw extension: model review pending; no change to HEAD ownership/lease rules | STUB | | `INV-CLI-TYPED-REFUSAL-001` | The chunk CLI reports a restore the master refused for a foreign source as `restore_source_not_own` (from the master's typed reason, never its text) and a volume the master does not know as `volume_not_found`. | M2 none → created (restore refusal); CLI volume resolve | `core/host/master/services.go` `CreateVolume`; `core/rpc/lifecycleclient/reason.go` `WithReason`, `Reason`; `cmd/sw-block/chunk_b.go` `chunkRestore`, `run` | `TestOpsChunkTypedRefusalCodes` (`cmd/sw-block/chunk_typed_codes_test.go`), `TestReasonRoundTrip` (`core/rpc/lifecycleclient/reason_test.go`), `TestARealCatalogRestoreOfARestoreTargetLeavesNothing` (`core/host/master/restore_refusal_catalog_test.go`) | — (reporting only; the refusal is `INV-CREATE-ONE-IDENTITY-001`'s). Limits: other FailedPrecondition refusals stay the generic `not_admitted` | ACTIVE | | `INV-CLI-RESTORE-VERB-001` | `volume restore --abort` changes nothing unless the master records this command's source, snapshot and request id for the target and this host's settings name exactly it (volume, master, `--layout-id` alone in the extra arguments); a re-run counts only this replica's published line as placed. | client (no state machine): the CLI side of M2 restore create, placement and delete | `cmd/sw-block/volume_backup.go` `volumeRestoreAbort`, `volumeRestore`, `restorePlaced`; `core/host/master/services.go` `lifecycleVolumeResponse` | `TestVolumeRestoreAbortRefusesAForeignTarget`, `TestVolumeRestoreAbortRefusesAnotherLocalInstallation`, `TestVolumeRestoreAbortInterruptedAtEveryStepCompletes`, `TestVolumeRestoreCrashTableBothWays`, `TestVolumeRestorePublicationDuringThePlacement`, `TestVolumeRestorePlacementOfAnotherLineRefuses`, `TestVolumeRestoreCreatesPlacesAndStarts`, `TestVolumeBackupTakesOneSnapshotAndRerunReplays`, `TestVolumeBackupRefusals`, `TestVolumeBackupIncompleteAnswerIsUnknown` (`cmd/sw-block/volume_backup_test.go`), `TestGetVolumeAnswersTheRecordedRestoreTuple` (`core/host/master/volume_restore_tuple_test.go`) | — (the command's model is checked outside the repository; its trace is on the pull request) | ACTIVE | | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`); also in `core/authority/layout_granted_epoch_guard_test.go` | `ControlPlane` `UniqueEpoch` | ACTIVE | @@ -1207,7 +1209,7 @@ Notes: | `INV-WS-DELETE-WITHOUT-ACK-001` | A delete without the holder's acknowledgement is admitted only while the master's record still awaits a replica store (stage 1), marked durably first; the mark freezes the wait, so the primary never serves. Past stage 1 the live-lease refusal stays. | M2 any authority line, stores still awaited → DeleteReserved without the holder's acknowledgement | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited` | `TestANeverCreatedVolumeIsDeletedWithoutItsHolder`, `TestAnEstablishedVolumeIsNotDeletedUnderALiveLease` (`core/host/master/workspace_delete_never_created_test.go`); `TestAStage2VolumeKeepsTheLiveLeaseRefusal`, `TestTheDeleteMarkFreezesTheStoreWait`, `TestAStage2VolumeIsNotMarkedForADeleteWithoutAck` (`core/host/master/workspace_delete_proof_test.go`); `TestDeleteMarkWriterCensus`, `TestDeleteMarkWriterCensusControls` (`core/host/master/store_attestation_census_test.go`) | CreateEvid2 model rows `mut_delete_on_flag_only`, `mut_no_horizon` | ACTIVE | | `INV-CLI-DELETE-PROGRESS-001` | Volume deletion bounds each sweep, continues across transient filer failures while objects are removed, and returns a retryable unavailable answer with progress after a no-progress window. | M9 deleting → deleted | `cmd/sw-block/chunk_volume_delete.go` `deleteVolumeWithProgress` | `TestVolumeDeleteContinuesAcrossTransientObjectFailures` | Existing ordered delete; no new persisted state. | ACTIVE | | `INV-SNAPK-DELETE-GUARD-001` | A source scan requires DeleteVolume to run no-holder check, deleting, release, object deletes and deleted in that order, and allows it as the only remover besides RemoveUnreachable. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-VOLUME-DIR-001` | A volume's master-minted layout identity is immutable; its directory is -, created exclusively and never reused. A foreign chunk's owning directory is checked against its full VOLUME id. | Content-named layout and lifecycle create/lookup/launch | `core/frontend/chunkstore/layout` `VolumeDir`; `core/lifecycle/store.go` `CreateVolume`; `core/host/master/services.go` `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient`; `core/launcher/k8s_renderer.go`; `cmd/blockvolume/main.go` `parseFlags`; `core/host/volume/chunk_control.go` `catalogVolume`, `ListSnapshots`, `DeleteSnapshot`, `Usage`; `cmd/blockvolume/chunk_remote.go` `chunkAttachCheck`; `core/frontend/chunkstore/layout/read.go` `Image.Chunk`; `core/rpc/lifecycleclient/identity.go` `ResolveVolume` | `TestRead_ForeignChunkFromSourcePool`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`; `TestLifecycleLayoutIdentity`, `TestLayoutIdentityWriterAndReaders`; `TestGetLifecycleVolumeResolvesOnlyTheDurableIdentity`; `TestResolveVolumeNeverInventsAnIdentity`; `TestLauncherCarriesTheMasterLayoutIdentity`; `TestBlockvolumeLayoutIdentitySelectsTheLocalRoot`; `TestChunkControlUsesTheBoundLayoutIdentity`, `TestChunkControlCatalogLookupErrorIsNotAbsence`, `TestChunkAttachCheckAppliesVolumeRules`; `TestHeadReaders_Enumeration`, `TestDeleteAndDirectorySites_Enumeration` | Lifecycle ids are durable record fields, not assignment epochs. Old records without the field are refused by the new-layout lookup; host metadata is bound to the full name/id and does not fall back to a previous incarnation. Data-path, scheduled snapshot and cleaning callers plus Linux crash qualification remain cutover work. | ACTIVE | +| `INV-SNAPK-VOLUME-DIR-001` | After store-ready, a volume's master-minted layout identity is immutable; a pending ordinary create may redraw only a proved directory collision (INV-CREATE-DIR-COLLISION-001); its directory is -, created exclusively and never reused. A foreign chunk's owning directory is checked against its full VOLUME id. | Content-named layout and lifecycle create/lookup/launch | `core/frontend/chunkstore/layout` `VolumeDir`; `core/lifecycle/store.go` `CreateVolume`; `core/host/master/services.go` `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient`; `core/launcher/k8s_renderer.go`; `cmd/blockvolume/main.go` `parseFlags`; `core/host/volume/chunk_control.go` `catalogVolume`, `ListSnapshots`, `DeleteSnapshot`, `Usage`; `cmd/blockvolume/chunk_remote.go` `chunkAttachCheck`; `core/frontend/chunkstore/layout/read.go` `Image.Chunk`; `core/rpc/lifecycleclient/identity.go` `ResolveVolume` | `TestRead_ForeignChunkFromSourcePool`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`; `TestLifecycleLayoutIdentity`, `TestLayoutIdentityWriterAndReaders`; `TestGetLifecycleVolumeResolvesOnlyTheDurableIdentity`; `TestResolveVolumeNeverInventsAnIdentity`; `TestLauncherCarriesTheMasterLayoutIdentity`; `TestBlockvolumeLayoutIdentitySelectsTheLocalRoot`; `TestChunkControlUsesTheBoundLayoutIdentity`, `TestChunkControlCatalogLookupErrorIsNotAbsence`, `TestChunkAttachCheckAppliesVolumeRules`; `TestHeadReaders_Enumeration`, `TestDeleteAndDirectorySites_Enumeration` | Lifecycle ids are durable record fields, not assignment epochs. Old records without the field are refused by the new-layout lookup; host metadata is bound to the full name/id and does not fall back to a previous incarnation. Data-path, scheduled snapshot and cleaning callers plus Linux crash qualification remain cutover work. | ACTIVE | | `INV-SNAPK-TOMBSTONE-001` | For a restore target without HEAD (never created, or a restore died between its two creates) the operator writes a deleted HEAD exclusively in its directory before releasing, so the restore cannot create it later. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent`, `TargetStore.CreateDeletedHead` | `TestOperatorReleaseDependent`, `TestOperatorReleaseDependent_TombstoneLosesToTheRestore`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-KEEP-HEAD-001` | Nothing removes a HEAD, a VOLUME or a volume directory: a volume delete removes only pool, segment and root objects; a source scan lists every delete and every directory-naming site in core/ and cmd/. | M9 deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`; (source scan) | `TestDeleteVolume_RemovesOnlyObjects`, `TestDeleteAndDirectorySites_Enumeration` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-CREATE-001` | A new volume or restore target gets VOLUME then an unclaimed HEAD (epoch 0, no holder, no claim id, idle), each created exclusively; only createVolume and the operator's tombstone create a HEAD; the first Start claims it from a fresh root. | M9 absent → idle | `core/frontend/chunkstore/layout` `create.go` `CreateVolume`, `CreateTarget` | `TestCreateVolume`, `TestCreateVolume_InterruptAtEveryStep`, `TestUnclaimedHead_Shape`, `TestStart_ClaimsAnUnclaimedHeadFromAFreshRoot`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | diff --git a/seaweed-block/docs/design/volume-directory-collisions.md b/seaweed-block/docs/design/volume-directory-collisions.md new file mode 100644 index 0000000000..d1f4aa39ad --- /dev/null +++ b/seaweed-block/docs/design/volume-directory-collisions.md @@ -0,0 +1,31 @@ +# Volume directory collisions + +A directory uses the volume name and the first eight hexadecimal digits of +its full layout identity. Two different full identities can select the same +directory. The exclusive VOLUME create refuses that collision without writing +VOLUME, HEAD, objects or payloads in the existing volume. + +```mermaid +stateDiagram-v2 + pending --> pending: ordinary storage error; retry same identity + pending --> replacementPending: exclusive create proves a valid foreign id8 collision + replacementPending --> pending: persist fresh full identity, retry in fresh directory + pending --> ready: matching VOLUME and HEAD created + ready --> ready: identical create replay +``` + +Only an ordinary, not-ready, unattached lifecycle record can redraw. A restore +keeps its source/request binding and is not handled by this transition. A corrupt +VOLUME, an unrelated identity mismatch, or an unknown store outcome never proves +a collision. Ordinary reads and attach still reject every full-ID mismatch. + +One RPC performs at most one redraw. It returns a retry response after recording +the replacement; the next RPC creates the new directory. A replacement first +lands through the lifecycle store's file-sync, rename and directory-sync path. +If its synchronization result is unknown, a retry settles that on-disk identity +before publishing it, rather than generating another. No ready identity changes. + +The master serializes create and placement under workspaceMu. This is a change +to pending creation only, not an assignment, lease, epoch or serving decision. +The create model's collision transition and its invariant are pending model +review; the implementation remains a draft until that review and Linux tests. From 5c5c57055d020d101d09289b91a621047f2bbb63 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 23:15:44 -0800 Subject: [PATCH 03/11] fix: settle pending identity before create metadata enrichment --- .../lifecycle/layout_identity_guard_test.go | 14 ++-- .../core/lifecycle/layout_redraw_test.go | 19 ++++- seaweed-block/core/lifecycle/store.go | 74 ++++++++++++++----- 3 files changed, 82 insertions(+), 25 deletions(-) diff --git a/seaweed-block/core/lifecycle/layout_identity_guard_test.go b/seaweed-block/core/lifecycle/layout_identity_guard_test.go index 48e354f82f..1a4884159a 100644 --- a/seaweed-block/core/lifecycle/layout_identity_guard_test.go +++ b/seaweed-block/core/lifecycle/layout_identity_guard_test.go @@ -26,6 +26,7 @@ func TestLayoutIdentityWriterAndReaders(t *testing.T) { "core/lifecycle/store.go validateSpec": true, "core/lifecycle/store.go MarkStoreReady": true, "core/lifecycle/store.go RedrawPendingLayoutID": true, + "core/lifecycle/store.go settlePendingLayoutIDLocked": true, "core/lifecycle/workload_plan.go PlanBlockVolumeWorkloads": true, "core/host/master/services.go lifecycleVolumeResponse": true, "core/host/master/services.go CreateVolume": true, @@ -129,11 +130,14 @@ func TestLayoutIdentityWriterAndReaders(t *testing.T) { // Adding a new reader or writer requires a binding probe at that site. func TestRestoreSourceIdentitySites(t *testing.T) { want := map[string]bool{ - "core/lifecycle/store.go CreateVolume": true, - "core/lifecycle/store.go volumeSpecsCompatible": true, - "core/lifecycle/store.go validateSpec": true, - "core/host/master/services.go CreateVolume": true, - "core/host/master/services.go createLifecycleVolume": true, + // Restore records are excluded; TestRedrawPendingLayoutID probes both paths. + "core/lifecycle/store.go RedrawPendingLayoutID": true, + "core/lifecycle/store.go settlePendingLayoutIDLocked": true, + "core/lifecycle/store.go CreateVolume": true, + "core/lifecycle/store.go volumeSpecsCompatible": true, + "core/lifecycle/store.go validateSpec": true, + "core/host/master/services.go CreateVolume": true, + "core/host/master/services.go createLifecycleVolume": true, } seen := map[string]bool{} root := filepath.Join("..", "..") diff --git a/seaweed-block/core/lifecycle/layout_redraw_test.go b/seaweed-block/core/lifecycle/layout_redraw_test.go index 13536f4c26..96b67b022b 100644 --- a/seaweed-block/core/lifecycle/layout_redraw_test.go +++ b/seaweed-block/core/lifecycle/layout_redraw_test.go @@ -61,9 +61,22 @@ func TestRedrawPendingLayoutID(t *testing.T) { t.Fatal(e) } fail = false - got, e := s.RedrawPendingLayoutID("v", old.Spec.LayoutID) - if e != nil || got != disk || got.Spec.LayoutID[:8] == old.Spec.LayoutID[:8] { - t.Fatalf("replacement not settled: %+v %v", got, e) + // Exercise the public retry path, including metadata enrichment. It + // must settle disk B before a metadata put could overwrite it with A. + retry := spec + retry.PVCName, retry.PVName = "claim", "pv" + public, retryErr := s.CreateVolume(retry) + if retryErr != nil || public.Spec.LayoutID != disk.Spec.LayoutID || public.Spec.PVCName != "claim" || public.Spec.PVName != "pv" { + t.Fatalf("public retry lost disk replacement: disk=%s public=%+v err=%v", disk.Spec.LayoutID, public, retryErr) + } + // Re-enter the direct method with its current ID for a separate + // replacement; the stale original ID must no longer be admitted. + if _, e = s.RedrawPendingLayoutID("v", old.Spec.LayoutID); !errors.Is(e, ErrVolumeConflict) { + t.Fatalf("settled replacement accepted stale rejected ID: %v", e) + } + got := public + if got.Spec.LayoutID[:8] == old.Spec.LayoutID[:8] { + t.Fatal("replacement reused directory") } reopened, e := OpenFileStore(s.dir) if e != nil { diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index fe8193f3e3..7ea6a7c77f 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -147,6 +147,16 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { if !volumeSpecsCompatible(existing.Spec, spec) { return VolumeRecord{}, ErrVolumeConflict } + // A previous collision redraw may have reached disk but lost its + // directory-sync reply. Settle it before enriching cached metadata. + var err error + existing, err = s.settlePendingLayoutIDLocked(existing) + if err != nil { + return VolumeRecord{}, err + } + if !volumeSpecsCompatible(existing.Spec, spec) { + return VolumeRecord{}, ErrVolumeConflict + } merged := existing merged.Spec = mergeVolumeSpecMetadata(existing.Spec, spec) if merged.Spec != existing.Spec { @@ -215,29 +225,18 @@ func (s *FileStore) RedrawPendingLayoutID(volumeID, rejectedID string) (VolumeRe if !ok { return VolumeRecord{}, ErrVolumeNotFound } - if rec.Spec.LayoutID != rejectedID || rec.StoreReady || rec.AttachedTo != "" || rec.Spec.SourceVolume != "" { + if rec.Spec.LayoutID != rejectedID || rec.StoreReady || rec.AttachedTo != "" || rec.Spec.SourceVolume != "" || rec.Spec.SourceLayoutID != "" || rec.Spec.SourceSnapshot != "" || rec.Spec.CreateRequestID != "" { return VolumeRecord{}, ErrVolumeConflict } - raw, err := os.ReadFile(s.path(volumeID)) + settled, err := s.settlePendingLayoutIDLocked(rec) if err != nil { return VolumeRecord{}, err } - var disk VolumeRecord - if err := json.Unmarshal(raw, &disk); err != nil { - return VolumeRecord{}, err + if settled.Spec.LayoutID != rejectedID { + return settled, nil } - // Apart from its identity, an uncertain replacement must be the exact - // same pending request. Never turn another record into this request. - oldID := disk.Spec.LayoutID - disk.Spec.LayoutID = rejectedID - if disk != rec { - return VolumeRecord{}, ErrVolumeConflict - } - disk.Spec.LayoutID = oldID - if _, err := layout.ParseVolumeID(oldID); err != nil { - return VolumeRecord{}, err - } - if oldID == rejectedID { + disk := settled + if disk.Spec.LayoutID == rejectedID { id, err := layout.NewVolumeID() if err != nil { return VolumeRecord{}, err @@ -255,6 +254,47 @@ func (s *FileStore) RedrawPendingLayoutID(volumeID, rejectedID string) (VolumeRe return disk, nil } +// settlePendingLayoutIDLocked reconciles only an uncertain pending identity +// replacement, before either a redraw or public metadata enrichment can write. +func (s *FileStore) settlePendingLayoutIDLocked(rec VolumeRecord) (VolumeRecord, error) { + if rec.StoreReady || rec.AttachedTo != "" || rec.Spec.SourceVolume != "" || rec.Spec.SourceLayoutID != "" || rec.Spec.SourceSnapshot != "" || rec.Spec.CreateRequestID != "" { + return rec, nil + } + raw, err := os.ReadFile(s.path(rec.Spec.VolumeID)) + if err != nil { + return VolumeRecord{}, err + } + var disk VolumeRecord + if err := json.Unmarshal(raw, &disk); err != nil { + return VolumeRecord{}, err + } + if disk.Spec.LayoutID == rec.Spec.LayoutID { + return rec, nil + } + id, err := layout.ParseVolumeID(disk.Spec.LayoutID) + if err != nil { + return VolumeRecord{}, err + } + // Nothing except the identity may differ in an uncertain redraw. + disk.Spec.LayoutID = rec.Spec.LayoutID + if disk != rec { + return VolumeRecord{}, ErrVolumeConflict + } + if _, err := layout.ParseVolumeID(rec.Spec.LayoutID); err != nil { + return VolumeRecord{}, err + } + if id.String()[:8] == rec.Spec.LayoutID[:8] { + return VolumeRecord{}, ErrVolumeConflict + } + disk.Spec.LayoutID = id.String() + if err := s.putLocked(disk); err != nil { + return VolumeRecord{}, err + } + s.records[rec.Spec.VolumeID] = disk + s.publishLocked() + return disk, nil +} + // MarkStoreReady publishes the durable placement hint after the filer has // accepted both exclusive creates. A retry of the same create may repeat it; // another layout identity may not mark this record ready. From 3616d4294688ed1b6e60dd30fba9b77900db63e2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 23:29:24 -0800 Subject: [PATCH 04/11] docs: record checked collision redraw automaton --- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/design/volume-directory-collisions.md | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 2a0e32f6fc..98405de8b0 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -786,7 +786,7 @@ Notes: | `INV-AUTH-ONE-REPLICATED-FACTOR-001` | CreateVolume admits a replicated volume only if the master can decide it: its replication factor equals the master's one slot count (--expected-slots-per-volume) and the lifecycle product loop runs (only that loop binds, mints and promotes it). | M2 none → Bound (a created replicated volume's first line) | `core/host/master/services.go` `CreateVolume`; `core/host/master/host.go` `Config.LifecycleProductLoop`; `core/authority/controller.go` `ExpectedSlotsPerVolume`, `validateVolumeTopology` | `TestAnRF2CreateOnAnRF3MasterIsRefusedAndFailoverContinues`, `TestAReplicatedCreateWithTheProductLoopOffIsRefused` (`core/host/master/create_rf_mismatch_test.go`) | — (an admission check). Limits: single-replica volumes are admitted at any slot count (they never reach the check); a static --topology file with a mismatched volume is not checked at start (a cluster spec is: `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001`) | ACTIVE | | `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001` | blockmaster refuses to start when its cluster spec holds a replicated volume it could never decide: one whose replication factor differs from --expected-slots-per-volume, or any while the lifecycle product loop is off (only that loop binds, mints and promotes it). | M2 none → Bound (a replicated cluster-spec volume's first line) | `cmd/blockmaster/product_loop_guard.go` `requireProductLoop`; `cmd/blockmaster/main.go` `run` | `TestReplicatedClusterSpecWithTheProductLoopOffIsRefused`, `TestTheProductLoopGuardPassesWhatItShould`, `TestAClusterSpecVolumeOfAnotherReplicationFactorIsRefused`, `TestAPlacementOnlyClusterSpecVolumeIsChecked` (`cmd/blockmaster/product_loop_guard_test.go`) | — (a startup configuration check). Limits: static `--topology` is not refused (its observation controller mints), and has no automatic failover in v1 | ACTIVE | | `INV-CREATE-ONE-IDENTITY-001` | One name, one layout identity; no directory but the record's holds a live HEAD (not none, not deleted). A served volume's deleted name is never created again. | M2 none → created (CreateVolume, restore target creation) | `core/host/master/services.go` `CreateVolume`, `createLifecycleVolume`; `core/frontend/chunkstore/layout/start.go` `Start` | `TestARefusedRestoreLeavesNoTargetRecord` (`core/host/master/restore_refusal_test.go`), `TestARealCatalogRestoreOfARestoreTargetLeavesNothing`, `TestAServedThenDeletedNameIsStillRefused` (`core/host/master/restore_refusal_catalog_test.go`), `TestCreateVolume` (`core/frontend/chunkstore/layout/create_test.go`), `TestDecodeHead_RefusesAnotherVolumesHead` (`core/frontend/chunkstore/layout/head_test.go`) | VolumeCreate OneIdentity (its second clause: a directory with a live HEAD is the record's). Scope: only a refused restore's record, which never left the creation phase (never assigned, never served), is removed, with no filer write. Limits: a served volume's deleted name stays refused until 1.1 | ACTIVE | -| `INV-CREATE-DIR-COLLISION-001` | Only a rejected exclusive VOLUME create proving a valid foreign full identity in the same name/id8 directory permits a pending ordinary create to replace its id. Ready, attached and restore records refuse replacement. No foreign metadata or payload is modified; a lost replacement sync reply settles its existing disk identity. | M2 pending create collision → pending create with fresh id | `core/frontend/chunkstore/layout_create.go` `CreateVolumeRecord`; `core/lifecycle/store.go` `RedrawPendingLayoutID`; `core/host/master/services.go` `createLifecycleVolume` | `TestCreateVolumeExclusiveCollisionRedraws`, `TestCollisionExistingVolumeSafety`, `TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal`, `TestRedrawPendingLayoutID` | VolumeCreate collision-redraw extension: model review pending; no change to HEAD ownership/lease rules | STUB | +| `INV-CREATE-DIR-COLLISION-001` | Only a rejected exclusive VOLUME create proving a valid foreign full identity in the same name/id8 directory permits a pending ordinary create to replace its id. Ready, attached and restore records refuse replacement. No foreign metadata or payload is modified; a lost replacement sync reply settles its existing disk identity. | M2 pending create collision → pending create with fresh id | `core/frontend/chunkstore/layout_create.go` `CreateVolumeRecord`; `core/lifecycle/store.go` `RedrawPendingLayoutID`; `core/host/master/services.go` `createLifecycleVolume` | `TestCreateVolumeExclusiveCollisionRedraws`, `TestCollisionExistingVolumeSafety`, `TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal`, `TestRedrawPendingLayoutID` | MasterCreate3 MUST-VIOLATE rows 220-224; no-proof redraw, use-before-persist and remint-on-replay mutants violate OneIdentity; no change to HEAD ownership/lease rules | ACTIVE | | `INV-CLI-TYPED-REFUSAL-001` | The chunk CLI reports a restore the master refused for a foreign source as `restore_source_not_own` (from the master's typed reason, never its text) and a volume the master does not know as `volume_not_found`. | M2 none → created (restore refusal); CLI volume resolve | `core/host/master/services.go` `CreateVolume`; `core/rpc/lifecycleclient/reason.go` `WithReason`, `Reason`; `cmd/sw-block/chunk_b.go` `chunkRestore`, `run` | `TestOpsChunkTypedRefusalCodes` (`cmd/sw-block/chunk_typed_codes_test.go`), `TestReasonRoundTrip` (`core/rpc/lifecycleclient/reason_test.go`), `TestARealCatalogRestoreOfARestoreTargetLeavesNothing` (`core/host/master/restore_refusal_catalog_test.go`) | — (reporting only; the refusal is `INV-CREATE-ONE-IDENTITY-001`'s). Limits: other FailedPrecondition refusals stay the generic `not_admitted` | ACTIVE | | `INV-CLI-RESTORE-VERB-001` | `volume restore --abort` changes nothing unless the master records this command's source, snapshot and request id for the target and this host's settings name exactly it (volume, master, `--layout-id` alone in the extra arguments); a re-run counts only this replica's published line as placed. | client (no state machine): the CLI side of M2 restore create, placement and delete | `cmd/sw-block/volume_backup.go` `volumeRestoreAbort`, `volumeRestore`, `restorePlaced`; `core/host/master/services.go` `lifecycleVolumeResponse` | `TestVolumeRestoreAbortRefusesAForeignTarget`, `TestVolumeRestoreAbortRefusesAnotherLocalInstallation`, `TestVolumeRestoreAbortInterruptedAtEveryStepCompletes`, `TestVolumeRestoreCrashTableBothWays`, `TestVolumeRestorePublicationDuringThePlacement`, `TestVolumeRestorePlacementOfAnotherLineRefuses`, `TestVolumeRestoreCreatesPlacesAndStarts`, `TestVolumeBackupTakesOneSnapshotAndRerunReplays`, `TestVolumeBackupRefusals`, `TestVolumeBackupIncompleteAnswerIsUnknown` (`cmd/sw-block/volume_backup_test.go`), `TestGetVolumeAnswersTheRecordedRestoreTuple` (`core/host/master/volume_restore_tuple_test.go`) | — (the command's model is checked outside the repository; its trace is on the pull request) | ACTIVE | | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`); also in `core/authority/layout_granted_epoch_guard_test.go` | `ControlPlane` `UniqueEpoch` | ACTIVE | diff --git a/seaweed-block/docs/design/volume-directory-collisions.md b/seaweed-block/docs/design/volume-directory-collisions.md index d1f4aa39ad..534659f1e0 100644 --- a/seaweed-block/docs/design/volume-directory-collisions.md +++ b/seaweed-block/docs/design/volume-directory-collisions.md @@ -27,5 +27,7 @@ before publishing it, rather than generating another. No ready identity changes. The master serializes create and placement under workspaceMu. This is a change to pending creation only, not an assignment, lease, epoch or serving decision. -The create model's collision transition and its invariant are pending model -review; the implementation remains a draft until that review and Linux tests. +MasterCreate3 checks the collision transition and OneIdentity (MUST-VIOLATE +rows 220-224): redraw without proof, use before persistence and remint on +replay each violate the invariant. Linux focused regression controls pass; +the full master package's qualification remains open. From ac85a9dc2bcfcd21324c87119f96a60d720d7c47 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 22:40:44 -0800 Subject: [PATCH 05/11] layout: HEAD format version 1 with a verbatim ext; manifest sizes as v1.1 fields - version first (absent: v1.0, strict as before); every known version is strict at the top level, later fields live in ext, kept raw and written back verbatim, so the canonical-bytes check holds - a HEAD of a newer version is refused as ErrHeadNewerVersion, not ErrMalformed; a v1.0 HEAD carrying v1.1 fields is malformed - CurrentBytes (Current's manifest size) and a snapshot's ManifestBytes, written by the commit that knows the size (which makes HEAD v1.1); a snapshot's size is written once - the HEAD write census gains version, current_bytes and ext Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/commit.go | 26 +++- .../chunkstore/layout/head-write-census.json | 25 +++- .../core/frontend/chunkstore/layout/head.go | 90 +++++++++++-- .../layout/head_census_export_test.go | 8 +- .../chunkstore/layout/head_version_test.go | 119 ++++++++++++++++++ 5 files changed, 249 insertions(+), 19 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/head_version_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit.go b/seaweed-block/core/frontend/chunkstore/layout/commit.go index a0436a5211..2a7a898873 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit.go @@ -58,6 +58,10 @@ type CommitRequest struct { // Delta, when set, is the commit by change: Prev and Next are unused, // and the plan builds and checks only the changed shards and the root. Delta *CommitDelta + // ManifestBytes, when set, is the size of the committed root's manifest + // (the root and every segment it names): HEAD's CurrentBytes after the + // commit, and the named snapshot's size. nil writes neither (unknown). + ManifestBytes *uint64 } // CommitDelta is a commit by change (cost table K3): HEAD's current root, @@ -447,7 +451,27 @@ func commitChecked(ctx context.Context, h Head, os ObjectStore, vol string, me H return Head{}, false, err } } - return h.Commit(me, req.Session, plan.root, req.Position, req.Snapshot, req.Meta, req.State) + next, changed, err := h.Commit(me, req.Session, plan.root, req.Position, req.Snapshot, req.Meta, req.State) + if err == nil && changed { + next = next.withManifestBytes(req.Snapshot, req.ManifestBytes) + } + return next, changed, err +} + +// withManifestBytes records the committed root's manifest size: HEAD's +// CurrentBytes (nil: unknown, also when an earlier commit knew it), and the +// size of the snapshot this commit named, written once. +func (h Head) withManifestBytes(snapshot string, size *uint64) Head { + h = h.clone() // the snapshot map is shared with the HEAD it came from + if size != nil && h.Version < HeadVersion1 { + h.Version = HeadVersion1 // the sizes are v1.1 fields + } + h.CurrentBytes = cloneSize(size) + if s, ok := h.Snapshots[snapshot]; snapshot != "" && ok && s.ManifestBytes == nil { + s.ManifestBytes = cloneSize(size) + h.Snapshots[snapshot] = s + } + return h } // commitVerifyParallel bounds the object lookups one commit runs at once. diff --git a/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json b/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json index 906c8fdafb..afc85ccf56 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json +++ b/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json @@ -15,8 +15,11 @@ "current": "Head.Current (including nil)", "position": "Head.Position", "state": "Head.State", - "snapshots": "Snapshot name membership and each entry Root, Position, Meta; excludes Dependents of retained entries", - "snapshots[].Dependents": "Dependents of retained snapshot entries, including target name, target id and root; excludes snapshot membership and other snapshot fields" + "snapshots": "Snapshot name membership and each entry Root, Position, Meta, ManifestBytes (written once, when the entry is named); excludes Dependents of retained entries", + "snapshots[].Dependents": "Dependents of retained snapshot entries, including target name, target id and root; excludes snapshot membership and other snapshot fields", + "version": "Head.Version (0 absent: the v1.0 format; 1: v1.1)", + "current_bytes": "Head.CurrentBytes, the manifest size of Current (including nil: unknown)", + "ext": "Head.Ext, the v1.1 extension object, written back verbatim by every writer that does not own an entry in it" }, "notes": [ "snapshots removal includes removal of its empty dependent list; snapshots with dependents cannot be removed.", @@ -40,7 +43,10 @@ "position", "state", "snapshots", - "snapshots[].Dependents" + "snapshots[].Dependents", + "version", + "current_bytes", + "ext" ] }, { @@ -90,7 +96,9 @@ "position", "activity", "state", - "snapshots" + "snapshots", + "version", + "current_bytes" ] }, { @@ -99,7 +107,9 @@ "may_change": [ "current", "activity", - "snapshots" + "snapshots", + "version", + "current_bytes" ] }, { @@ -178,7 +188,10 @@ "position", "state", "snapshots", - "snapshots[].Dependents" + "snapshots[].Dependents", + "version", + "current_bytes", + "ext" ] } ] diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index 9d5dd5e707..555aea058b 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -49,6 +49,11 @@ type Snapshot struct { Position uint64 Meta SnapshotMeta Dependents []Dependent + // ManifestBytes is the size of the snapshot's manifest (its root and + // every segment the root names), written once by the commit that named + // it. nil: unknown (a snapshot named before the field, or by a commit + // that did not know the size); never reported as 0. + ManifestBytes *uint64 } // The retention classes of a snapshot. @@ -151,9 +156,35 @@ type Head struct { Position uint64 Snapshots map[string]Snapshot State string // StateLive, StateDetached, StateDeleting or StateDeleted + // CurrentBytes is the manifest size of Current (its root and every + // segment it names), kept by each commit (nil: unknown). A commit by + // change updates it from the objects it replaces, with no lookups. + CurrentBytes *uint64 + // Version is HEAD's format version: 0 (absent in the bytes) is the v1.0 + // format, decoded strictly; HeadVersion1 is v1.1, whose own fields are + // CurrentBytes and snapshots' ManifestBytes, and whose Ext carries every + // later field. A writer keeps the version and Ext it read. + Version int + // Ext is a v1.1 HEAD's extension object, kept as raw bytes and written + // back verbatim (the ext contract: only additive facts that a writer + // keeping them verbatim while it changes the known fields cannot make + // wrong; anything an older writer could break bumps Version instead). + Ext json.RawMessage } +// HeadVersion1 is the v1.1 HEAD format; MaxHeadVersion the newest this +// binary reads. +const ( + HeadVersion1 = 1 + MaxHeadVersion = HeadVersion1 +) + +// ErrHeadNewerVersion refuses a HEAD written by a newer format version: +// not damage, a binary too old to read it. +var ErrHeadNewerVersion = errors.New("layout: HEAD written by a newer version") + type headDoc struct { + Version int `json:"version,omitempty"` VolumeID string `json:"volume_id"` Epoch uint64 `json:"epoch"` Holder string `json:"holder"` @@ -161,8 +192,10 @@ type headDoc struct { Activity Activity `json:"activity"` Current string `json:"current,omitempty"` Position uint64 `json:"position"` - Snapshots map[string]snapDoc `json:"snapshots,omitempty"` - State string `json:"state,omitempty"` + Snapshots map[string]snapDoc `json:"snapshots,omitempty"` + State string `json:"state,omitempty"` + CurrentBytes *uint64 `json:"current_bytes,omitempty"` + Ext json.RawMessage `json:"ext,omitempty"` } type snapDoc struct { @@ -172,7 +205,8 @@ type snapDoc struct { Class string `json:"class,omitempty"` ExpiresNs int64 `json:"expires_ns,omitempty"` Labels map[string]string `json:"labels,omitempty"` - Dependents []depDoc `json:"dependents,omitempty"` + Dependents []depDoc `json:"dependents,omitempty"` + ManifestBytes *uint64 `json:"manifest_bytes,omitempty"` } type depDoc struct { @@ -294,14 +328,14 @@ func (h Head) Encode() ([]byte, error) { if err := h.check(); err != nil { return nil, err } - d := headDoc{VolumeID: h.VolumeID.String(), Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID, Activity: h.Activity, Position: h.Position, State: h.State} + d := headDoc{Version: h.Version, VolumeID: h.VolumeID.String(), Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID, Activity: h.Activity, Position: h.Position, State: h.State, CurrentBytes: h.CurrentBytes, Ext: h.Ext} if h.Current != nil { d.Current = h.Current.String() } if len(h.Snapshots) > 0 { d.Snapshots = map[string]snapDoc{} for n, s := range h.Snapshots { - sd := snapDoc{Root: s.Root.String(), Position: s.Position, CreatedNs: s.Meta.CreatedNs, Class: s.Meta.Class, ExpiresNs: s.Meta.ExpiresNs} + sd := snapDoc{Root: s.Root.String(), Position: s.Position, CreatedNs: s.Meta.CreatedNs, Class: s.Meta.Class, ExpiresNs: s.Meta.ExpiresNs, ManifestBytes: s.ManifestBytes} if len(s.Meta.Labels) > 0 { sd.Labels = s.Meta.Labels } @@ -327,17 +361,36 @@ func DecodeHead(b []byte, gen uint64, volume VolumeID) (Head, error) { if volume.IsZero() { return Head{}, errors.New("layout: DecodeHead needs the volume's id from its VOLUME") } + // The version first, read leniently: a newer version is refused as + // newer, never as malformed. Every known version is then decoded + // strictly (unknown top-level fields refused; v1.1's later fields live + // in ext, kept raw). + var probe struct { + Version int `json:"version"` + } + if err := json.Unmarshal(b, &probe); err != nil { + return Head{}, fmt.Errorf("%w: HEAD: %v", ErrMalformed, err) + } + if probe.Version > MaxHeadVersion { + return Head{}, fmt.Errorf("%w: version %d, this binary reads up to %d", ErrHeadNewerVersion, probe.Version, MaxHeadVersion) + } + if probe.Version < 0 { + return Head{}, fmt.Errorf("%w: HEAD version %d", ErrMalformed, probe.Version) + } var d headDoc dec := json.NewDecoder(bytes.NewReader(b)) dec.DisallowUnknownFields() if err := dec.Decode(&d); err != nil { return Head{}, fmt.Errorf("%w: HEAD: %v", ErrMalformed, err) } + if d.Version == 0 && (d.CurrentBytes != nil || d.Ext != nil || snapshotsSized(d.Snapshots)) { + return Head{}, fmt.Errorf("%w: HEAD of the v1.0 format carries v1.1 fields", ErrMalformed) + } vid, err := ParseVolumeID(d.VolumeID) if err != nil { return Head{}, err } - h := Head{Gen: gen, VolumeID: vid, Epoch: d.Epoch, Holder: d.Holder, ClaimID: d.ClaimID, Activity: d.Activity, Position: d.Position, State: d.State} + h := Head{Gen: gen, VolumeID: vid, Epoch: d.Epoch, Holder: d.Holder, ClaimID: d.ClaimID, Activity: d.Activity, Position: d.Position, State: d.State, CurrentBytes: d.CurrentBytes, Version: d.Version, Ext: d.Ext} if d.Current != "" { rn, err := ParseRootName(d.Current) if err != nil { @@ -352,7 +405,7 @@ func DecodeHead(b []byte, gen uint64, volume VolumeID) (Head, error) { if err != nil { return Head{}, err } - snap := Snapshot{Root: rn, Position: s.Position, Meta: SnapshotMeta{CreatedNs: s.CreatedNs, Class: s.Class, ExpiresNs: s.ExpiresNs, Labels: s.Labels}} + snap := Snapshot{Root: rn, Position: s.Position, Meta: SnapshotMeta{CreatedNs: s.CreatedNs, Class: s.Class, ExpiresNs: s.ExpiresNs, Labels: s.Labels}, ManifestBytes: s.ManifestBytes} for _, dep := range s.Dependents { tid, err := ParseVolumeID(dep.TargetID) if err != nil { @@ -453,15 +506,36 @@ func (h Head) clone() Head { rn := *h.Current c.Current = &rn } + c.CurrentBytes = cloneSize(h.CurrentBytes) + if h.Ext != nil { + c.Ext = append(json.RawMessage(nil), h.Ext...) + } if h.Snapshots != nil { c.Snapshots = make(map[string]Snapshot, len(h.Snapshots)) for n, s := range h.Snapshots { - c.Snapshots[n] = Snapshot{Root: s.Root, Position: s.Position, Meta: s.Meta.clone(), Dependents: append([]Dependent(nil), s.Dependents...)} + c.Snapshots[n] = Snapshot{Root: s.Root, Position: s.Position, Meta: s.Meta.clone(), Dependents: append([]Dependent(nil), s.Dependents...), ManifestBytes: cloneSize(s.ManifestBytes)} } } return c } +func snapshotsSized(snaps map[string]snapDoc) bool { + for _, s := range snaps { + if s.ManifestBytes != nil { + return true + } + } + return false +} + +func cloneSize(p *uint64) *uint64 { + if p == nil { + return nil + } + v := *p + return &v +} + // ErrPrecondition is returned by HeadStore.Update when HEAD is not at the // expected generation. var ErrPrecondition = errors.New("layout: HEAD generation moved") diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_census_export_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_census_export_test.go index d4005e775e..73b96419c6 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_census_export_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_census_export_test.go @@ -31,13 +31,13 @@ func TestMachineReadableHeadCensusNamesExactlyTheTypedCauses(t *testing.T) { if census.SchemaVersion != 1 { t.Fatalf("schema=%d", census.SchemaVersion) } - observable := map[string]bool{"volume_id": true, "epoch": true, "holder": true, "claim_id": true, "activity": true, "current": true, "position": true, "state": true, "snapshots": true, "snapshots[].Dependents": true} + observable := map[string]bool{"volume_id": true, "epoch": true, "holder": true, "claim_id": true, "activity": true, "current": true, "position": true, "state": true, "snapshots": true, "snapshots[].Dependents": true, "version": true, "current_bytes": true, "ext": true} for field := range census.FieldGroups { if !observable[field] { t.Fatalf("unobservable census field %s", field) } } - headFields := map[string]bool{"Gen": true, "VolumeID": true, "Epoch": true, "Holder": true, "ClaimID": true, "Activity": true, "Current": true, "Position": true, "Snapshots": true, "State": true} + headFields := map[string]bool{"Gen": true, "VolumeID": true, "Epoch": true, "Holder": true, "ClaimID": true, "Activity": true, "Current": true, "Position": true, "Snapshots": true, "State": true, "Version": true, "CurrentBytes": true, "Ext": true} typ := reflect.TypeOf(Head{}) for n := 0; n < typ.NumField(); n++ { if !headFields[typ.Field(n).Name] { @@ -83,8 +83,8 @@ func TestMachineReadableHeadCensusNamesExactlyTheTypedCauses(t *testing.T) { func changedCensusGroups(before, after Head) []string { var out []string a, b := reflect.ValueOf(before), reflect.ValueOf(after) - jsonKeys := map[string]string{"VolumeID": "volume_id", "Epoch": "epoch", "Holder": "holder", "ClaimID": "claim_id", "Activity": "activity", "Current": "current", "Position": "position", "State": "state"} - for _, name := range []string{"VolumeID", "Epoch", "Holder", "ClaimID", "Activity", "Current", "Position", "State"} { + jsonKeys := map[string]string{"VolumeID": "volume_id", "Epoch": "epoch", "Holder": "holder", "ClaimID": "claim_id", "Activity": "activity", "Current": "current", "Position": "position", "State": "state", "Version": "version", "CurrentBytes": "current_bytes", "Ext": "ext"} + for _, name := range []string{"VolumeID", "Epoch", "Holder", "ClaimID", "Activity", "Current", "Position", "State", "Version", "CurrentBytes", "Ext"} { if !reflect.DeepEqual(a.FieldByName(name).Interface(), b.FieldByName(name).Interface()) { out = append(out, jsonKeys[name]) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go new file mode 100644 index 0000000000..201c6de239 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go @@ -0,0 +1,119 @@ +package layout + +import ( + "bytes" + "encoding/json" + "errors" + "strings" + "testing" +) + +func u64(v uint64) *uint64 { return &v } + +// A v1.1 HEAD (version 1) carries its sizes and an ext object kept as raw +// bytes: it decodes, and encodes back to the same bytes (the canonical +// check holds with ext re-emitted verbatim). A v1.0 HEAD's bytes are +// unchanged: no version field is written when the version is 0. +func TestHeadVersion1RoundTripsWithItsExtVerbatim(t *testing.T) { + root := RootName{Hash: Sum([]byte("image"))} + h := idleHead() + h.Current, h.Position = &root, 9 + h.Version, h.CurrentBytes = HeadVersion1, u64(4096) + h.Ext = json.RawMessage(`{"later":{"a":1}}`) + h.Snapshots = map[string]Snapshot{"s1": {Root: root, Position: 9, ManifestBytes: u64(4096)}} + b, err := h.Encode() + if err != nil { + t.Fatal(err) + } + if !bytes.HasPrefix(b, []byte(`{"version":1,`)) { + t.Fatalf("a v1.1 HEAD does not start with its version: %s", b) + } + back, err := DecodeHead(b, h.Gen, h.VolumeID) + if err != nil { + t.Fatal(err) + } + if back.Version != HeadVersion1 || back.CurrentBytes == nil || *back.CurrentBytes != 4096 || string(back.Ext) != string(h.Ext) { + t.Fatalf("decoded %+v", back) + } + if s := back.Snapshots["s1"]; s.ManifestBytes == nil || *s.ManifestBytes != 4096 { + t.Fatalf("snapshot size lost: %+v", s) + } + again, err := back.Encode() + if err != nil || !bytes.Equal(again, b) { + t.Fatalf("v1.1 HEAD not canonical after a round trip: %s / %s (%v)", again, b, err) + } + + v0 := idleHead() + b0, err := v0.Encode() + if err != nil { + t.Fatal(err) + } + if bytes.Contains(b0, []byte(`"version"`)) || bytes.Contains(b0, []byte(`"ext"`)) || bytes.Contains(b0, []byte(`bytes"`)) { + t.Fatalf("a v1.0 HEAD's bytes changed: %s", b0) + } +} + +// Decoding by version: a HEAD of a newer version is refused as newer +// (ErrHeadNewerVersion), never as damage; a v1.0 HEAD (no version) that +// carries a v1.1 field is malformed; a known version still refuses an +// unknown top-level field (later fields go in ext). +func TestHeadDecodeByVersion(t *testing.T) { + root := RootName{Hash: Sum([]byte("image"))} + h := idleHead() + h.Current, h.Position = &root, 9 + h.Version, h.CurrentBytes = HeadVersion1, u64(10) + b, err := h.Encode() + if err != nil { + t.Fatal(err) + } + newer := bytes.Replace(b, []byte(`{"version":1,`), []byte(`{"version":2,`), 1) + if _, err := DecodeHead(newer, 1, h.VolumeID); !errors.Is(err, ErrHeadNewerVersion) || errors.Is(err, ErrMalformed) { + t.Fatalf("a newer HEAD: %v; want ErrHeadNewerVersion, not ErrMalformed", err) + } + v0WithSize := bytes.Replace(b, []byte(`{"version":1,`), []byte(`{`), 1) + if _, err := DecodeHead(v0WithSize, 1, h.VolumeID); !errors.Is(err, ErrMalformed) { + t.Fatalf("a v1.0 HEAD with a v1.1 field: %v; want ErrMalformed", err) + } + unknownTop := bytes.Replace(b, []byte(`{"version":1,`), []byte(`{"version":1,"surprise":1,`), 1) + if _, err := DecodeHead(unknownTop, 1, h.VolumeID); !errors.Is(err, ErrMalformed) { + t.Fatalf("an unknown top-level field in a v1.1 HEAD: %v; want ErrMalformed (later fields live in ext)", err) + } + if !strings.Contains(ErrHeadNewerVersion.Error(), "newer version") { + t.Fatal("the newer-version refusal does not say so") + } +} + +// A commit that knows its manifest size writes it as HEAD's CurrentBytes and +// as the size of the snapshot it names, and makes HEAD v1.1. A commit that +// does not know it writes neither and leaves a v1.0 HEAD at v1.0. A replay +// changes nothing. +func TestCommitRecordsTheManifestSize(t *testing.T) { + root := RootName{Hash: Sum([]byte("image"))} + open := func() Head { + h := idleHead() + h.State = StateLive + h.Activity = Activity{Kind: ActSnap, Session: "s"} + return h + } + me := HolderID{Holder: "srv-a", Epoch: 3, ClaimID: "k-a"} + next, changed, err := open().Commit(me, "s", root, 9, "snap", SnapshotMeta{}, StateLive) + if err != nil || !changed { + t.Fatal(err) + } + sized := next.withManifestBytes("snap", u64(777)) + if sized.Version != HeadVersion1 || sized.CurrentBytes == nil || *sized.CurrentBytes != 777 { + t.Fatalf("sized commit: %+v", sized) + } + if s := sized.Snapshots["snap"]; s.ManifestBytes == nil || *s.ManifestBytes != 777 { + t.Fatalf("the named snapshot's size: %+v", s) + } + unsized := next.withManifestBytes("snap", nil) + if unsized.Version != 0 || unsized.CurrentBytes != nil || unsized.Snapshots["snap"].ManifestBytes != nil { + t.Fatalf("a commit that does not know the size: %+v", unsized) + } + // Written once: a later size never rewrites a snapshot's. + again := sized.withManifestBytes("snap", u64(999)) + if s := again.Snapshots["snap"]; *s.ManifestBytes != 777 { + t.Fatalf("a snapshot's size was rewritten: %d", *s.ManifestBytes) + } +} From e4e34c26a64f621324c142bd4ac4f9d79a2fbec6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 23:04:00 -0800 Subject: [PATCH 06/11] chunkstore: keep the manifest size through commits; list it per snapshot On the v1.1 format a full commit writes the sum of its root and segments as HEAD's current_bytes and the named snapshot's manifest_bytes. A commit by change subtracts the base root and the replaced segments and adds the new ones, with no lookups; an unknown size stays unknown. Snapshot listings report manifestBytes, null when unknown. The format doc states the ext contract; a test bounds the fullest HEAD under the inline limit. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/control_types.go | 37 +++--- .../core/frontend/chunkstore/layout/head.go | 28 ++-- .../chunkstore/layout/head_limit_test.go | 72 +++++++++++ .../chunkstore/layout_manifest_size_test.go | 121 ++++++++++++++++++ .../core/frontend/chunkstore/layout_remote.go | 88 +++++++++++-- .../frontend/chunkstore/snapshot_info_b.go | 1 + .../core/host/volume/chunk_control.go | 4 +- .../volume/chunk_manifest_bytes_list_test.go | 62 +++++++++ .../core/storage/chunk_v11_format.go | 5 + seaweed-block/docs/chunk-manifests.md | 22 ++++ 10 files changed, 399 insertions(+), 41 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/head_limit_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_manifest_size_test.go create mode 100644 seaweed-block/core/host/volume/chunk_manifest_bytes_list_test.go diff --git a/seaweed-block/core/frontend/chunkstore/control_types.go b/seaweed-block/core/frontend/chunkstore/control_types.go index 848d58d094..b920f439ae 100644 --- a/seaweed-block/core/frontend/chunkstore/control_types.go +++ b/seaweed-block/core/frontend/chunkstore/control_types.go @@ -108,23 +108,26 @@ type Parent struct { // SnapshotInfo describes one snapshot, with the field names of the HTTP API // (spec §3.2-§3.3). type SnapshotInfo struct { - Root string `json:"root,omitempty"` - Dependents []layout.Dependent `json:"dependents,omitempty"` - VolumeID string `json:"volumeID"` - Name string `json:"name"` - HeadGen uint64 `json:"headGen"` - HeadEpoch uint64 `json:"headEpoch"` - CutLSN uint64 `json:"cutLSN"` - CreatedNs int64 `json:"createdNs"` - State string `json:"state"` - ChunkCount int `json:"chunkCount"` - ManifestBytes int `json:"manifestBytes"` - Consistency string `json:"consistency"` - Labels map[string]string `json:"labels"` - Parent *Parent `json:"parent"` - ExpiresAtNs int64 `json:"expiresAtNs"` - Replayed bool `json:"replayed"` - Class string `json:"class"` + Root string `json:"root,omitempty"` + Dependents []layout.Dependent `json:"dependents,omitempty"` + VolumeID string `json:"volumeID"` + Name string `json:"name"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + CutLSN uint64 `json:"cutLSN"` + CreatedNs int64 `json:"createdNs"` + State string `json:"state"` + ChunkCount int `json:"chunkCount"` + // ManifestBytes is the snapshot's manifest size (its root and every + // segment), written once by the commit that named it; null when unknown + // (a snapshot named before v1.1 recorded it), never 0. + ManifestBytes *uint64 `json:"manifestBytes"` + Consistency string `json:"consistency"` + Labels map[string]string `json:"labels"` + Parent *Parent `json:"parent"` + ExpiresAtNs int64 `json:"expiresAtNs"` + Replayed bool `json:"replayed"` + Class string `json:"class"` attempt string // the attempt the name resolved to, when read by name diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index 555aea058b..9829329990 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -184,14 +184,14 @@ const ( var ErrHeadNewerVersion = errors.New("layout: HEAD written by a newer version") type headDoc struct { - Version int `json:"version,omitempty"` - VolumeID string `json:"volume_id"` - Epoch uint64 `json:"epoch"` - Holder string `json:"holder"` - ClaimID string `json:"claim_id,omitempty"` - Activity Activity `json:"activity"` - Current string `json:"current,omitempty"` - Position uint64 `json:"position"` + Version int `json:"version,omitempty"` + VolumeID string `json:"volume_id"` + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + ClaimID string `json:"claim_id,omitempty"` + Activity Activity `json:"activity"` + Current string `json:"current,omitempty"` + Position uint64 `json:"position"` Snapshots map[string]snapDoc `json:"snapshots,omitempty"` State string `json:"state,omitempty"` CurrentBytes *uint64 `json:"current_bytes,omitempty"` @@ -199,12 +199,12 @@ type headDoc struct { } type snapDoc struct { - Root string `json:"root"` - Position uint64 `json:"position,omitempty"` - CreatedNs int64 `json:"created_ns,omitempty"` - Class string `json:"class,omitempty"` - ExpiresNs int64 `json:"expires_ns,omitempty"` - Labels map[string]string `json:"labels,omitempty"` + Root string `json:"root"` + Position uint64 `json:"position,omitempty"` + CreatedNs int64 `json:"created_ns,omitempty"` + Class string `json:"class,omitempty"` + ExpiresNs int64 `json:"expires_ns,omitempty"` + Labels map[string]string `json:"labels,omitempty"` Dependents []depDoc `json:"dependents,omitempty"` ManifestBytes *uint64 `json:"manifest_bytes,omitempty"` } diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_limit_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_limit_test.go new file mode 100644 index 0000000000..88bca4b021 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/head_limit_test.go @@ -0,0 +1,72 @@ +package layout + +import ( + "fmt" + "math" + "strings" + "testing" +) + +// fullestHead is the largest HEAD the bounds allow: MaxSnapshots snapshots +// whose names and labels are at their byte limits in the character JSON +// escapes widest (a control byte, written as six), MaxDependentsPerHead +// dependents, and the v1.1 sizes at their widest. Volume names, the holder, +// the claim and the session are not bounded by HEAD; 64 bytes each is +// assumed here (the names the catalog writes are far shorter). +func fullestHead(sized bool) Head { + wide := func(n int, tag int) string { + return fmt.Sprintf("%02d", tag) + strings.Repeat("\x01", n-2) + } + root := RootName{Hash: Sum([]byte("image"))} + h := idleHead() + h.Holder, h.ClaimID = wide(64, 0), wide(64, 1) + h.Activity = Activity{Kind: ActSnap, Session: wide(64, 2)} + h.Current, h.Position = &root, math.MaxUint64-1 + h.Snapshots = map[string]Snapshot{} + left := MaxDependentsPerHead + for i := 0; i < MaxSnapshots; i++ { + labels := map[string]string{} + for l := 0; l < MaxSnapshotLabels; l++ { + labels[wide(MaxLabelKeyBytes, l)] = wide(MaxLabelValueBytes, l) + } + s := Snapshot{Root: root, Position: math.MaxUint64 - 1, Meta: SnapshotMeta{ + CreatedNs: math.MaxInt64, Class: ClassScheduled, ExpiresNs: math.MaxInt64, Labels: labels}} + var targets []string + for d := 0; d < MaxDependents && left > 0; d, left = d+1, left-1 { + targets = append(targets, wide(64, 10*i+d)) + } + s.Dependents = deps(root, targets...) + if sized { + s.ManifestBytes = u64(math.MaxUint64) + } + h.Snapshots[wide(MaxSnapshotNameBytes, i)] = s + } + if sized { + h.Version, h.CurrentBytes = HeadVersion1, u64(math.MaxUint64) + } + return h +} + +// The v1.1 fields fit HEAD's inline limit with room to spare: the fullest +// HEAD the bounds allow, with every size at its widest, encodes under +// MaxHeadBytes; v1.1 adds at most 512 bytes to it; and at least 16 KiB stays +// free for ext (the ext contract's budget: a writer's own ext must keep the +// fullest HEAD under the limit, which Encode enforces). +func TestTheFullestHeadFitsWithTheV11Sizes(t *testing.T) { + v0, err := fullestHead(false).Encode() + if err != nil { + t.Fatalf("the fullest v1.0 HEAD: %v", err) + } + v1, err := fullestHead(true).Encode() + if err != nil { + t.Fatalf("the fullest v1.1 HEAD: %v", err) + } + added, free := len(v1)-len(v0), MaxHeadBytes-len(v1) + t.Logf("fullest HEAD: v1.0 %d bytes, v1.1 %d (+%d), %d free of %d", len(v0), len(v1), added, free, MaxHeadBytes) + if added > 512 { + t.Fatalf("v1.1 adds %d bytes to the fullest HEAD, want at most 512", added) + } + if free < 16<<10 { + t.Fatalf("the fullest v1.1 HEAD leaves %d bytes, want at least 16 KiB for ext", free) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_manifest_size_test.go b/seaweed-block/core/frontend/chunkstore/layout_manifest_size_test.go new file mode 100644 index 0000000000..97374f29b4 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_manifest_size_test.go @@ -0,0 +1,121 @@ +package chunkstore + +import ( + "context" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// withManifestSizes turns the v1.1 manifest sizes on for one test. +func withManifestSizes(t *testing.T, on bool) { + t.Helper() + prev := manifestSizesV11 + manifestSizesV11 = func() bool { return on } + t.Cleanup(func() { manifestSizesV11 = prev }) +} + +// currentSize recomputes the size HEAD's current manifest has, from all of +// its objects: what the commits must have kept without lookups. +func currentSize(t *testing.T, ctx context.Context, r *LayoutRemote) (layout.Head, uint64) { + t.Helper() + h, _, err := r.st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + m, err := r.manifest(ctx, *h.Current) + if err != nil { + t.Fatal(err) + } + root, segs, err := layout.Build(m) + if err != nil { + t.Fatal(err) + } + n, err := manifestSize(root, segs) + if err != nil { + t.Fatal(err) + } + return h, n +} + +// On the v1.1 format every commit keeps HEAD's CurrentBytes equal to the +// manifest's real size: the full commit sums every object; a commit by change +// takes the replaced objects out and the new ones in, with no lookups, and +// stays exact (a change in shard 1, then one that empties shard 2). HEAD is +// version 1. On the v1.0 format no size is written and HEAD stays version 0. +func TestCommitsKeepTheManifestSizeExact(t *testing.T) { + t.Run("v1.1", func(t *testing.T) { + withManifestSizes(t, true) + ctx, _, r, h1 := threeShardVolume(t) + h, want := currentSize(t, ctx, r) + if h.Version != layout.HeadVersion1 || h.CurrentBytes == nil || *h.CurrentBytes != want { + t.Fatalf("after the full commit: version %d, size %v, want %d", h.Version, h.CurrentBytes, want) + } + gen, lsn := h1.Gen, uint64(2) + for _, step := range []struct { + name string + changes func() map[uint64]*storage.ChunkRef + }{ + {"a change in shard 1", func() map[uint64]*storage.ChunkRef { + ref := putChunk(t, ctx, r, layout.ShardSize+9, "second") + return map[uint64]*storage.ChunkRef{layout.ShardSize + 9: &ref} + }}, + {"shard 2 emptied", func() map[uint64]*storage.ChunkRef { + return map[uint64]*storage.ChunkRef{2*layout.ShardSize + 7: nil} + }}, + } { + changes := step.changes() + exp := storage.ChunkHeadVersion{Gen: gen, Epoch: 1} + next := storage.ChunkHead{Epoch: 1, RemoteLSN: lsn} + if err := r.CheckCommitDelta(ctx, exp, next, changes); err != nil { + t.Fatal(err) + } + g, err := r.CASHeadDelta(ctx, exp, next, changes) + if err != nil { + t.Fatal(err) + } + gen, lsn = g, lsn+1 + h, want := currentSize(t, ctx, r) + if h.CurrentBytes == nil || *h.CurrentBytes != want { + t.Fatalf("%s: size %v, want %d (the sum of the manifest's objects)", step.name, h.CurrentBytes, want) + } + } + }) + t.Run("v1.0", func(t *testing.T) { + withManifestSizes(t, false) + ctx, _, r, _ := threeShardVolume(t) + h, _, err := r.st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + if h.Version != 0 || h.CurrentBytes != nil { + t.Fatalf("a v1.0-format commit wrote v1.1 fields: version %d, size %v", h.Version, h.CurrentBytes) + } + }) +} + +// A HEAD with no recorded size (a v1.0 HEAD) stays unknown through commits +// by change: they cannot know the objects they did not replace. +func TestACommitByChangeKeepsAnUnknownSizeUnknown(t *testing.T) { + withManifestSizes(t, false) + ctx, _, r, h1 := threeShardVolume(t) // a v1.0 HEAD: no size + withManifestSizes(t, true) + ref := putChunk(t, ctx, r, layout.ShardSize+9, "second") + changes := map[uint64]*storage.ChunkRef{layout.ShardSize + 9: &ref} + exp := storage.ChunkHeadVersion{Gen: h1.Gen, Epoch: 1} + next := storage.ChunkHead{Epoch: 1, RemoteLSN: 2} + if err := r.CheckCommitDelta(ctx, exp, next, changes); err != nil { + t.Fatal(err) + } + if _, err := r.CASHeadDelta(ctx, exp, next, changes); err != nil { + t.Fatal(err) + } + h, _, err := r.st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + if h.CurrentBytes != nil { + t.Fatalf("a commit by change over an unknown size wrote %d", *h.CurrentBytes) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index dd2e0f8623..28b6244947 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -545,8 +545,19 @@ func (l *LayoutRemote) prepareCommitLocked(ctx context.Context, expected storage return layout.Head{}, layout.CommitRequest{}, false, err } req.Delta, req.Plan = &d, &plan - } else if err := l.writeRootLocked(ctx, nextM); err != nil { - return layout.Head{}, layout.CommitRequest{}, false, err + if manifestSizesV11() { + if req.ManifestBytes, err = deltaManifestSize(h.CurrentBytes, d, plan); err != nil { + return layout.Head{}, layout.CommitRequest{}, false, err + } + } + } else { + size, err := l.writeRootLocked(ctx, nextM) + if err != nil { + return layout.Head{}, layout.CommitRequest{}, false, err + } + if manifestSizesV11() { + req.ManifestBytes = &size + } } if next.State == "detached" { req.State = layout.StateDetached @@ -889,15 +900,71 @@ func (l *LayoutRemote) writeDeltaRootLocked(ctx context.Context, plan layout.Com } // writeRootLocked writes next's segments and root in this session, so the -// commit finds them prepared. -func (l *LayoutRemote) writeRootLocked(ctx context.Context, next map[uint64]layout.Ref) error { +// commit finds them prepared, and returns the manifest's size (the root and +// every segment it names). +func (l *LayoutRemote) writeRootLocked(ctx context.Context, next map[uint64]layout.Ref) (uint64, error) { defer storage.MeasureCutWork(ctx, storage.CutSegmentWrites)() root, segs, err := layout.Build(next) if err != nil { - return err + return 0, err + } + size, err := manifestSize(root, segs) + if err != nil { + return 0, err } _, err = layout.PrepareRoot(ctx, manifestSends{l.st}, root, segs, l.session) - return layoutRemoteErr(err) + return size, layoutRemoteErr(err) +} + +// manifestSizesV11 says whether commits write the manifest sizes (v1.1 HEAD +// fields): the build's draft v1.1 format. Tests of this package set it. +var manifestSizesV11 = storage.ChunkV11Format + +// manifestSize is the size of a root and the segments given. +func manifestSize(root layout.Root, segs map[layout.SegName][]byte) (uint64, error) { + rb, err := root.Encode() + if err != nil { + return 0, err + } + n := uint64(len(rb)) + for _, b := range segs { + n += uint64(len(b)) + } + return n, nil +} + +// deltaManifestSize is a commit by change's manifest size, from the size +// HEAD names for its base (prev) with no lookups: the base root and the +// replaced segments it already read come out, the new root and the new +// segments go in. With no base every object is new; with an unknown prev +// the size stays unknown (nil) until a full commit. +func deltaManifestSize(prev *uint64, d layout.CommitDelta, plan layout.CommitPlan) (*uint64, error) { + added, err := manifestSize(plan.RootObject(), plan.Segments()) + if err != nil { + return nil, err + } + if d.Base == nil { + return &added, nil + } + if prev == nil { + return nil, nil + } + removed, err := manifestSize(d.BaseRoot, nil) + if err != nil { + return nil, err + } + for _, seg := range d.Prev { + b, err := seg.Encode() + if err != nil { + return nil, err + } + removed += uint64(len(b)) + } + if removed > *prev { + return nil, nil // HEAD's size cannot have held these objects: unknown + } + size := *prev - removed + added + return &size, nil } // manifestSends counts each root and segment object a commit actually sends @@ -1008,10 +1075,15 @@ func (l *LayoutRemote) CommitPendingSnapshot(ctx context.Context) error { return err } } - if err := l.writeRootLocked(ctx, m); err != nil { + size, err := l.writeRootLocked(ctx, m) + if err != nil { return err } - got, err := layout.RunCommit(ctx, l.st, l.st, l.vol.Name, l.me, layout.CommitRequest{Session: l.session, Prev: m, Next: m, Position: h.Position, State: layout.StateLive, Snapshot: p.name, Meta: p.meta}, layout.CauseSnapshotUnchanged) + req := layout.CommitRequest{Session: l.session, Prev: m, Next: m, Position: h.Position, State: layout.StateLive, Snapshot: p.name, Meta: p.meta} + if manifestSizesV11() { + req.ManifestBytes = &size + } + got, err := layout.RunCommit(ctx, l.st, l.st, l.vol.Name, l.me, req, layout.CauseSnapshotUnchanged) if err != nil { if snapshotRefusal(err) { l.pending = nil diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_info_b.go b/seaweed-block/core/frontend/chunkstore/snapshot_info_b.go index 61259683ad..74ed08668f 100644 --- a/seaweed-block/core/frontend/chunkstore/snapshot_info_b.go +++ b/seaweed-block/core/frontend/chunkstore/snapshot_info_b.go @@ -12,5 +12,6 @@ func SnapshotInfoFromHead(volumeID, name string, h layout.Head) SnapshotInfo { VolumeID: volumeID, Name: name, Root: s.Root.String(), Dependents: s.Dependents, HeadGen: h.Gen, HeadEpoch: h.Epoch, CutLSN: s.Position, State: SnapActive, Class: s.Meta.Class, CreatedNs: s.Meta.CreatedNs, ExpiresAtNs: s.Meta.ExpiresNs, Labels: s.Meta.Labels, + ManifestBytes: s.ManifestBytes, } } diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index f69b43efc6..428a39fcb4 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -185,7 +185,7 @@ type snapshotBody struct { CutLSN uint64 `json:"cutLSN"` CreatedNs int64 `json:"createdNs"` ChunkCount int `json:"chunkCount"` - ManifestBytes int `json:"manifestBytes"` + ManifestBytes *uint64 `json:"manifestBytes"` // null: unknown Consistency string `json:"consistency"` Labels map[string]string `json:"labels"` Replayed bool `json:"replayed"` @@ -766,7 +766,7 @@ func (c *chunkControl) ListSnapshots(ctx context.Context, volumeID string, opts out := make([]chunkstore.SnapshotInfo, 0, len(names)) for _, name := range names { sn := h.Snapshots[name] - out = append(out, chunkstore.SnapshotInfo{VolumeID: volumeID, Name: name, Root: sn.Root.String(), Dependents: sn.Dependents, CreatedNs: sn.Meta.CreatedNs, Class: sn.Meta.Class, ExpiresAtNs: sn.Meta.ExpiresNs, Labels: maps.Clone(sn.Meta.Labels)}) + out = append(out, chunkstore.SnapshotInfo{VolumeID: volumeID, Name: name, Root: sn.Root.String(), Dependents: sn.Dependents, CreatedNs: sn.Meta.CreatedNs, Class: sn.Meta.Class, ExpiresAtNs: sn.Meta.ExpiresNs, Labels: maps.Clone(sn.Meta.Labels), ManifestBytes: sn.ManifestBytes}) } return out, next, nil } diff --git a/seaweed-block/core/host/volume/chunk_manifest_bytes_list_test.go b/seaweed-block/core/host/volume/chunk_manifest_bytes_list_test.go new file mode 100644 index 0000000000..82ded986f3 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_manifest_bytes_list_test.go @@ -0,0 +1,62 @@ +package volume + +import ( + "context" + "encoding/json" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// A listing reports each snapshot's manifest size as its HEAD record holds +// it: the size the naming commit wrote, or null for a snapshot named before +// the size was recorded (unknown, never 0). +func TestListingReportsTheManifestSizeOrUnknown(t *testing.T) { + ctx := context.Background() + f := &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}} + cat, err := chunkstore.NewBCatalog(f, f, "/chunks") + if err != nil { + t.Fatal(err) + } + id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff") + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + h, _, err := cat.ReadHead(ctx, ref) + if err != nil { + t.Fatal(err) + } + r := layout.RootName{Hash: layout.Sum([]byte("root"))} + size := uint64(4242) + h.Version = layout.HeadVersion1 + h.Snapshots = map[string]layout.Snapshot{"new": {Root: r, ManifestBytes: &size}, "old": {Root: r}} + s, _ := cat.Store(ref) + if err := s.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil { + t.Fatal(err) + } + ctl := NewChunkControl(&fakeChunkProvider{}, cat, ref) + list, _, err := ctl.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}) + if err != nil || len(list) != 2 { + t.Fatalf("listing: %d entries, %v", len(list), err) + } + got := map[string]*uint64{} + for _, s := range list { + got[s.Name] = s.ManifestBytes + } + if got["new"] == nil || *got["new"] != size { + t.Fatalf("a sized snapshot lists %v, want %d", got["new"], size) + } + if got["old"] != nil { + t.Fatalf("a snapshot named before the size lists %d, want unknown (null)", *got["old"]) + } + b, err := json.Marshal(list) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(b), `"manifestBytes":4242`) || !strings.Contains(string(b), `"manifestBytes":null`) { + t.Fatalf("listing JSON: %s", b) + } +} diff --git a/seaweed-block/core/storage/chunk_v11_format.go b/seaweed-block/core/storage/chunk_v11_format.go index 161b8ffd89..f08a061655 100644 --- a/seaweed-block/core/storage/chunk_v11_format.go +++ b/seaweed-block/core/storage/chunk_v11_format.go @@ -5,3 +5,8 @@ package storage // build's constant; this package's tests turn it on for the tests that // exercise the format. var chunkV11Format = chunkV11FormatBuild + +// ChunkV11Format reports whether this build (or test) runs the draft v1.1 +// format: what a chunk store's HEAD writer uses to decide whether it may +// write v1.1 HEAD fields. +func ChunkV11Format() bool { return chunkV11Format } diff --git a/seaweed-block/docs/chunk-manifests.md b/seaweed-block/docs/chunk-manifests.md index 87856be1ab..eac8ed1db4 100644 --- a/seaweed-block/docs/chunk-manifests.md +++ b/seaweed-block/docs/chunk-manifests.md @@ -45,3 +45,25 @@ counters after joining workers. The worker queue mutex guards admission and first error only, with no I/O under it. Failure cancels new admission and joins all owned calls before clean-abort intent cleanup. A remote ignoring cancellation can delay that join; it is never reported settled early. + +## HEAD record version and ext + +The HEAD record's own `version` field is separate from the manifest format +above. Absent (version 0) is the v1.0 record, decoded strictly as before. +Version 1 (v1.1) adds `current_bytes` (the size of the current manifest: its +root and every segment it names) and `manifest_bytes` per snapshot (written +once, by the commit that names it). An absent size is unknown, never 0. A +commit by change keeps `current_bytes` without lookups: it subtracts the base +root and the segments it replaces and adds the new ones; an unknown size stays +unknown. Snapshot listings report `manifestBytes`, null when unknown. + +A binary refuses a HEAD with a version newer than it reads as a newer version, +not as damage. Known top-level fields stay strict; a v1.0 record carrying a +v1.1 field is malformed. + +The ext contract: a v1.1 HEAD may carry one `ext` object, which every writer +keeps and re-emits byte for byte while it changes the known fields. Ext holds +only additive facts that such a writer cannot make wrong. A fact an older +writer could invalidate by changing a known field without updating it bumps +the version instead. Ext counts toward the 64 KiB inline limit; the fullest +v1.1 HEAD the bounds allow is about 28 KiB, leaving at least 16 KiB for ext. From b84f55ba3efa440fb41c27c0cfe5e5a2cc122773 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 23:26:55 -0800 Subject: [PATCH 07/11] chunkstore: keep an unchanged touched segment in the size; ext is a canonical object A commit by change subtracts only the touched segments its new root no longer names: a shard whose segment came out unchanged stays in the size. HEAD's ext must be a JSON object in its canonical bytes, on encode and decode, so it round-trips byte for byte. The format doc states the upgrade order (version-aware readers before any v1.1 writer) and that the fullest-HEAD figure is a sizing check. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/head.go | 23 ++++++++++++++ .../chunkstore/layout/head_version_test.go | 31 +++++++++++++++++++ .../chunkstore/layout_manifest_size_test.go | 27 ++++++++++++++++ .../core/frontend/chunkstore/layout_remote.go | 8 ++++- seaweed-block/docs/chunk-manifests.md | 19 +++++++++--- 5 files changed, 103 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index 9829329990..08ed17133d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -225,6 +225,26 @@ func validName(field, v string) error { return nil } +// checkExt refuses an ext that is not a JSON object in its canonical bytes +// (what Encode writes: compact, HTML-escaped), or one on a v1.0 HEAD. Ext +// is carried as raw bytes and written back unchanged, so only canonical +// bytes round-trip byte for byte. +func checkExt(version int, ext json.RawMessage) error { + if ext == nil { + return nil + } + if version == 0 { + return fmt.Errorf("%w: a v1.0 HEAD carries ext", ErrMalformed) + } + if len(ext) == 0 || ext[0] != '{' || !json.Valid(ext) { + return fmt.Errorf("%w: HEAD ext is not a JSON object", ErrMalformed) + } + if canon, err := json.Marshal(ext); err != nil || !bytes.Equal(canon, ext) { + return fmt.Errorf("%w: HEAD ext is not in its canonical bytes", ErrMalformed) + } + return nil +} + // ErrNoNextPosition: a HEAD position with no room for a next LSN. No // commit produces it (Commit refuses); a HEAD that already carries one (an // older or broken writer) is still read, written by every other @@ -235,6 +255,9 @@ func (h Head) check() error { if h.VolumeID.IsZero() { return fmt.Errorf("%w: HEAD without a volume id", ErrMalformed) } + if err := checkExt(h.Version, h.Ext); err != nil { + return err + } switch h.State { case StateLive, StateDetached, StateDeleting, StateDeleted: default: diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go index 201c6de239..c81cee655d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go @@ -117,3 +117,34 @@ func TestCommitRecordsTheManifestSize(t *testing.T) { t.Fatalf("a snapshot's size was rewritten: %d", *s.ManifestBytes) } } + +// Ext is a JSON object in its canonical bytes, so it round-trips byte for +// byte: a HEAD whose ext is not an object, or not canonical (spacing, an +// unescaped character Encode would escape), is refused on decode and on +// encode, never rewritten into other bytes. +func TestHeadExtIsACanonicalObject(t *testing.T) { + root := RootName{Hash: Sum([]byte("image"))} + h := idleHead() + h.Current, h.Position = &root, 9 + h.Version, h.Ext = HeadVersion1, json.RawMessage(`{"a":1}`) + b, err := h.Encode() + if err != nil { + t.Fatal(err) + } + for name, ext := range map[string]string{ + "an array": `[1]`, + "a string": `"x"`, + "spaced": `{ "a":1}`, + "not escaped": `{"a":"<"}`, + } { + bad := bytes.Replace(b, []byte(`"ext":{"a":1}`), []byte(`"ext":`+ext), 1) + if _, err := DecodeHead(bad, 1, h.VolumeID); !errors.Is(err, ErrMalformed) { + t.Fatalf("decode, ext %s: %v; want ErrMalformed", name, err) + } + e := h + e.Ext = json.RawMessage(ext) + if _, err := e.Encode(); !errors.Is(err, ErrMalformed) { + t.Fatalf("encode, ext %s: %v; want ErrMalformed", name, err) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_manifest_size_test.go b/seaweed-block/core/frontend/chunkstore/layout_manifest_size_test.go index 97374f29b4..d7942fefb0 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_manifest_size_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_manifest_size_test.go @@ -119,3 +119,30 @@ func TestACommitByChangeKeepsAnUnknownSizeUnknown(t *testing.T) { t.Fatalf("a commit by change over an unknown size wrote %d", *h.CurrentBytes) } } + +// A commit by change that touches a shard but leaves its segment unchanged +// (a replacement equal to the ref it replaces) keeps that segment: the size +// takes out only the segments the new root no longer names. Mixed witness: +// shard 0 touched and unchanged, shard 1 changed. +func TestACommitByChangeKeepsAnUnchangedTouchedSegmentInTheSize(t *testing.T) { + withManifestSizes(t, true) + ctx, _, r, h1 := threeShardVolume(t) + same, ok := h1.Chunks[7] + if !ok { + t.Fatal("setup: no chunk 7 in HEAD") + } + changed := putChunk(t, ctx, r, layout.ShardSize+9, "second") + changes := map[uint64]*storage.ChunkRef{7: &same, layout.ShardSize + 9: &changed} + exp := storage.ChunkHeadVersion{Gen: h1.Gen, Epoch: 1} + next := storage.ChunkHead{Epoch: 1, RemoteLSN: 2} + if err := r.CheckCommitDelta(ctx, exp, next, changes); err != nil { + t.Fatal(err) + } + if _, err := r.CASHeadDelta(ctx, exp, next, changes); err != nil { + t.Fatal(err) + } + h, want := currentSize(t, ctx, r) + if h.CurrentBytes == nil || *h.CurrentBytes != want { + t.Fatalf("size %v, want %d (the sum of the manifest's objects)", h.CurrentBytes, want) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index 28b6244947..5d56d17433 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -953,7 +953,13 @@ func deltaManifestSize(prev *uint64, d layout.CommitDelta, plan layout.CommitPla if err != nil { return nil, err } - for _, seg := range d.Prev { + for shard, seg := range d.Prev { + // A touched shard whose segment came out unchanged is still named + // by the new root: it stays in the size (and is not in the plan's + // new segments either). + if name, kept := plan.RootObject().Segments[shard]; kept && name == d.BaseRoot.Segments[shard] { + continue + } b, err := seg.Encode() if err != nil { return nil, err diff --git a/seaweed-block/docs/chunk-manifests.md b/seaweed-block/docs/chunk-manifests.md index eac8ed1db4..37d0c18797 100644 --- a/seaweed-block/docs/chunk-manifests.md +++ b/seaweed-block/docs/chunk-manifests.md @@ -61,9 +61,20 @@ A binary refuses a HEAD with a version newer than it reads as a newer version, not as damage. Known top-level fields stay strict; a v1.0 record carrying a v1.1 field is malformed. -The ext contract: a v1.1 HEAD may carry one `ext` object, which every writer -keeps and re-emits byte for byte while it changes the known fields. Ext holds +Upgrade order: every build from this version on reads a version-1 HEAD, but +only a data plane on the draft v1.1 store format writes one; release builds +keep writing version 0. A v1.0.x binary decodes HEAD strictly and refuses a +version-1 record as malformed (it fails closed, it never rewrites it), so +every reader of a volume, the control plane included, must run a +version-aware build before any v1.1 writer touches that volume. + +The ext contract: a v1.1 HEAD may carry one `ext` object, in its canonical +bytes (compact JSON, as HEAD is encoded), which every writer keeps and +re-emits byte for byte while it changes the known fields. An ext that is not +an object, or not canonical, makes the record malformed. Ext holds only additive facts that such a writer cannot make wrong. A fact an older writer could invalidate by changing a known field without updating it bumps -the version instead. Ext counts toward the 64 KiB inline limit; the fullest -v1.1 HEAD the bounds allow is about 28 KiB, leaving at least 16 KiB for ext. +the version instead. Ext counts toward the 64 KiB inline limit, which Encode +enforces. With the holder, claim, session and volume names at 64 bytes, the +fullest v1.1 HEAD the other bounds allow is about 28 KiB; those names have no +HEAD bound of their own, so this is a sizing check, not a proof. From 6eb191c38f5617d2dd45ac8869e7b0816a3773bf Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 23:26:57 -0800 Subject: [PATCH 08/11] storage: on v1.1 a cut of a partial chunk fills it; events take the store's bits M1: on the v1.1 format the HEAD bytes a cut's COW copy fetches for a partial chunk are also installed beneath its local writes, and the absence is resolved as a fill (held until the store's batched mark), so the cut's Hash meets U and the next cut finds the chunk local. Recover's run-time Changed takes an absent chunk's coverage from the store's bits, and the engine bitmap's landing no longer sends Write(all). Release builds are unchanged. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_cut_cow.go | 20 +++ seaweed-block/core/storage/chunk_layer.go | 28 +++- .../core/storage/chunk_record_shadow_test.go | 10 +- .../core/storage/chunk_v11_cut_fill_test.go | 125 ++++++++++++++++++ 4 files changed, 172 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_v11_cut_fill_test.go diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index 24af54495c..f5ff20f4a7 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -520,11 +520,26 @@ func (l *chunkLayerImpl) readLocalBlock(lba uint64, w *cutCOWWindow, dst []byte) // fillMissing completes a COW capture: the blocks listed missing get the cut's // base HEAD bytes. It runs after the local entry is released, bounded by // ReadMissTimeout and the owning cut's cancellation. +// +// On the v1.1 format the fetched HEAD bytes also fill the chunk (M1): they +// are installed beneath every block with a local version, the absence is +// resolved and the record gets its Fill (P to U, held until the store's +// batched mark), so the cut's Hash meets U and a later cut finds the chunk +// local and clean once committed. A fill that no longer belongs to the +// absence installs nothing and leaves the chunk P (the scratch exemption). func (l *chunkLayerImpl) fillMissing(ctx context.Context, base map[uint64]chunkRef, idx uint64, data []byte, missing []uint64) ([]byte, error) { ref, ok := base[idx] if !ok { return nil, fmt.Errorf("storage: cut chunk %d: lazily absent blocks but HEAD has no chunk", idx) } + fill := l.shadow != nil && l.shadow.v11 + var gen, version uint64 + if fill { + l.stMu.Lock() + fill = l.absent[idx] && l.head.Chunks[idx] == ref + gen, version = l.absentGen[idx], l.chunkVersion(idx) + l.stMu.Unlock() + } ctx, cancel := context.WithTimeout(ctx, l.cfg.ReadMissTimeout) defer cancel() head, err := l.remote.Get(ctx, ref.Key) @@ -538,6 +553,11 @@ func (l *chunkLayerImpl) fillMissing(ctx context.Context, base map[uint64]chunkR for _, i := range missing { copy(out[int(i)*l.blockSize:int(i+1)*l.blockSize], head[int(i)*l.blockSize:int(i+1)*l.blockSize]) } + if fill { + if _, err := l.installFill(idx, gen, version, ref, head); err != nil { + return nil, fmt.Errorf("storage: cut chunk %d fill: %w", idx, err) + } + } return out, nil } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 5016eb5ac2..05abf3cab0 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -466,7 +466,8 @@ func (l *chunkLayerImpl) OnExtentWrite(lba uint64, lsn uint64) { if l.absent[idx] { l.localBlocks[lba] = true l.presenceVer++ - if sh := l.shadow; sh != nil && l.chunkLocalLocked(idx) { + // On v1.1 the write's own event carries the store's bits (noteMutation). + if sh := l.shadow; sh != nil && !sh.v11 && l.chunkLocalLocked(idx) { sh.landed(idx) } } @@ -552,7 +553,11 @@ func (l *chunkLayerImpl) recoveredLocked(sh *chunkRecordShadow) { continue } cov := "all" - if l.absent[idx] { + if l.absent[idx] && sh.v11 { + // The store's bits (durable, or WAL-backed), never the engine's + // view: a fill not yet marked is not local after a crash. + cov = localBitsArg(l.s.v3.mapEntries.at(int(idx)).Local) + } else if l.absent[idx] { n, total := uint64(0), uint64(0) for i := uint64(0); i < l.chunkBlocks; i++ { b := idx*l.chunkBlocks + i @@ -686,11 +691,6 @@ func (l *chunkLayerImpl) OnReadMiss(lba uint64) ([]byte, error) { // current absence (generation and HEAD ref unchanged). It reports whether // it resolved the absence. func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chunkRef) (bool, error) { - // current reports whether this fill still belongs to the chunk's present - // absence: same generation, same HEAD ref. Caller holds stMu. - current := func() bool { - return l.absent[idx] && l.absentGen[idx] == gen && l.head.Chunks[idx] == ref - } // Read with the end check's lock: a mutation bumps the version after its // dirty-map insert, so one that lands during the fill changes it. l.stMu.Lock() @@ -703,6 +703,20 @@ func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chun if sha256.Sum256(data) != ref.SHA256 || len(data) != int(l.chunkBlocks)*l.blockSize { return false, fmt.Errorf("storage: chunk %d fetch: %w", idx, errChunkContentMismatch) } + return l.installFill(idx, gen, version, ref, data) +} + +// installFill installs a fetched, verified chunk version: every block with +// no newer local version, as long as the fill still belongs to the chunk's +// current absence (generation and HEAD ref unchanged), and then resolves +// the absence (the record's Fill). version is the chunk's mutation version +// read before the fetch. It reports whether it resolved the absence. +func (l *chunkLayerImpl) installFill(idx, gen, version uint64, ref chunkRef, data []byte) (bool, error) { + // current reports whether this fill still belongs to the chunk's present + // absence: same generation, same HEAD ref. Caller holds stMu. + current := func() bool { + return l.absent[idx] && l.absentGen[idx] == gen && l.head.Chunks[idx] == ref + } first := idx * l.chunkBlocks for i := uint64(0); i < l.chunkBlocks; i++ { b := first + i diff --git a/seaweed-block/core/storage/chunk_record_shadow_test.go b/seaweed-block/core/storage/chunk_record_shadow_test.go index 9eaac29921..2a390ee920 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_test.go @@ -46,9 +46,11 @@ func shadowDefects(l *chunkLayerImpl) int { // extent directly, and a flushed WAL write does not land that way on v3. // Writing every block and flushing leaves P; a cut of it is a scratch cut // (M1): no Hash, no Commit, no refusal. -// - Blocks landing directly (a BASE block) fill the bitmap: P while it is -// partial, U on the last block (never all from one block). Mutant (E1b -// removed): the chunk stays P. +// - Blocks landing directly (a BASE block) fill the bitmap: on v1.0, P +// while it is partial, U on the last block (never all from one block); +// mutant (E1b removed): the chunk stays P. On v1.1 the engine's bitmap +// is never an event's coverage (ChunkStateK3 write_engine_view): the +// chunk stays P until the BASE completion's Changed(all). func TestShadowWriteCoverageFollowsTheStoreBitmap(t *testing.T) { s, l, _ := lazyFreshVolume(t) const idx = 1 @@ -84,7 +86,7 @@ func TestShadowWriteCoverageFollowsTheStoreBitmap(t *testing.T) { for i := uint64(0); i < ctChunkBlocks; i++ { l.OnExtentWrite(base*ctChunkBlocks+i, 0) // a block landing directly want := chunkkernel.Partial - if i == ctChunkBlocks-1 { + if i == ctChunkBlocks-1 && !l.shadow.v11 { want = chunkkernel.Unknown } if k := shadowKind(l, base); k != want { diff --git a/seaweed-block/core/storage/chunk_v11_cut_fill_test.go b/seaweed-block/core/storage/chunk_v11_cut_fill_test.go new file mode 100644 index 0000000000..04d66c57bf --- /dev/null +++ b/seaweed-block/core/storage/chunk_v11_cut_fill_test.go @@ -0,0 +1,125 @@ +package storage + +import ( + "bytes" + "testing" + + "github.com/seaweedfs/seaweed-block/core/chunkkernel" +) + +// M1 on the v1.1 format (ChunkStateK3 FillInstall, MarkDurable; mutants +// hash_partial, page_before_mark): a cut of a partial chunk (one block +// written, the rest only in HEAD) also fills it. The HEAD bytes the cut +// fetched are installed beneath the local write, the absence is resolved, +// and the record's Fill makes the chunk U before the cut's Hash (never Hash +// on P), so the commit leaves it HP. Its page shows P, the state before the +// fill, until the store's batched mark. A second cut compares and uploads +// nothing more, and the chunk reads locally with its write and HEAD's bytes. +func TestV11ACutOfAPartialChunkFillsIt(t *testing.T) { + s, path, l, f := v11LazyVolume(t) + const idx = 3 + written := makeBlock(ctBlockSize, 0xD1) + if _, err := s.Write(idx*ctChunkBlocks+1, written); err != nil { + t.Fatal(err) + } + if k := shadowKind(l, idx); k != chunkkernel.Partial { + t.Fatalf("setup: %s, want P", k) + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + l.stMu.Lock() + absent := l.absent[idx] + l.stMu.Unlock() + l.shadow.mu.Lock() + _, scratch := l.shadow.scratchP[idx] + l.shadow.mu.Unlock() + if absent || scratch { + t.Fatalf("after the cut: absent %v, scratch %v; want the chunk filled", absent, scratch) + } + if k := shadowKind(l, idx); k != chunkkernel.HashPublished { + t.Fatalf("after the cut: %s, want HP (Fill, then Hash and Commit)", k) + } + if n := shadowDefects(l); n != 0 { + t.Fatalf("%d shell events refused", n) + } + if err := l.shadow.rec.Flush(); err != nil { + t.Fatal(err) + } + if k := pageState(t, path, l.numChunks, idx); k != chunkkernel.Partial { + t.Fatalf("page before the mark: %s, want P (the state before the fill)", k) + } + if err := l.markFills(l.shadow); err != nil { + t.Fatal(err) + } + if err := l.shadow.rec.Flush(); err != nil { + t.Fatal(err) + } + if k := pageState(t, path, l.numChunks, idx); k != chunkkernel.HashPublished { + t.Fatalf("page after the mark: %s, want HP", k) + } + + before := f.stats() + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + for i := uint32(0); i < ctChunkBlocks; i++ { + got, err := s.Read(idx*ctChunkBlocks + i) + if err != nil { + t.Fatal(err) + } + want := makeBlock(ctBlockSize, byte(0x40+idx*ctChunkBlocks+i)) + if i == 1 { + want = written + } + if !bytes.Equal(got, want) { + t.Fatalf("block %d of the filled chunk: wrong bytes", i) + } + } + if after := f.stats(); after.puts != before.puts || after.gets != before.gets { + t.Fatalf("second cut and reads: %d puts, %d gets; want none (the chunk is local and clean)", after.puts-before.puts, after.gets-before.gets) + } +} + +// The run-time Changed takes an absent chunk's coverage from the store's +// bits, never from the engine's view (ChunkStateK3 changed_engine_view: the +// engine's bitmap may say local what a crash would not keep). The engine is +// made to say every block local while the store's bits hold one written +// block: Recover's Changed must give P (some), not U. +func TestV11RunTimeChangedTakesTheStoreBits(t *testing.T) { + s, _, l, _ := v11LazyVolume(t) + const idx = 3 + if _, err := s.Write(idx*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xD1)); err != nil { + t.Fatal(err) + } + l.stMu.Lock() + for i := uint64(0); i < ctChunkBlocks; i++ { + l.localBlocks[idx*ctChunkBlocks+i] = true + } + l.stMu.Unlock() + s.mu.Lock() + l.noteAllMutated() + s.mu.Unlock() + if k := shadowKind(l, idx); k != chunkkernel.Partial { + t.Fatalf("Changed over one store bit with the engine saying all: %s, want P", k) + } +} + +// A block landing in the extent of an absent chunk is not a Write with the +// engine bitmap's coverage on v1.1 (ChunkStateK3 write_engine_view): the +// write's own event already carried the store's bits. Every block of a +// chunk landing directly leaves it P; the BASE completion's Changed(all) +// is what makes it U (TestShadowBaseInstallCompletingChangesEveryChunk). +func TestV11ALandingIsNotAWriteFromTheEngineBitmap(t *testing.T) { + _, _, l, _ := v11LazyVolume(t) + const idx = 2 + for i := uint64(0); i < ctChunkBlocks; i++ { + l.OnExtentWrite(idx*ctChunkBlocks+i, 0) + } + if k := shadowKind(l, idx); k != chunkkernel.Partial { + t.Fatalf("every block landed directly: %s, want P", k) + } + if n := shadowDefects(l); n != 0 { + t.Fatalf("%d shell events refused", n) + } +} From da17629e75ffc4f4e10e52fe0ec59a90b07cbc3d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 23:55:47 -0800 Subject: [PATCH 09/11] docs: split collision invariants into single properties --- seaweed-block/docs/design/invariants.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 98405de8b0..8d3a757bad 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -786,7 +786,9 @@ Notes: | `INV-AUTH-ONE-REPLICATED-FACTOR-001` | CreateVolume admits a replicated volume only if the master can decide it: its replication factor equals the master's one slot count (--expected-slots-per-volume) and the lifecycle product loop runs (only that loop binds, mints and promotes it). | M2 none → Bound (a created replicated volume's first line) | `core/host/master/services.go` `CreateVolume`; `core/host/master/host.go` `Config.LifecycleProductLoop`; `core/authority/controller.go` `ExpectedSlotsPerVolume`, `validateVolumeTopology` | `TestAnRF2CreateOnAnRF3MasterIsRefusedAndFailoverContinues`, `TestAReplicatedCreateWithTheProductLoopOffIsRefused` (`core/host/master/create_rf_mismatch_test.go`) | — (an admission check). Limits: single-replica volumes are admitted at any slot count (they never reach the check); a static --topology file with a mismatched volume is not checked at start (a cluster spec is: `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001`) | ACTIVE | | `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001` | blockmaster refuses to start when its cluster spec holds a replicated volume it could never decide: one whose replication factor differs from --expected-slots-per-volume, or any while the lifecycle product loop is off (only that loop binds, mints and promotes it). | M2 none → Bound (a replicated cluster-spec volume's first line) | `cmd/blockmaster/product_loop_guard.go` `requireProductLoop`; `cmd/blockmaster/main.go` `run` | `TestReplicatedClusterSpecWithTheProductLoopOffIsRefused`, `TestTheProductLoopGuardPassesWhatItShould`, `TestAClusterSpecVolumeOfAnotherReplicationFactorIsRefused`, `TestAPlacementOnlyClusterSpecVolumeIsChecked` (`cmd/blockmaster/product_loop_guard_test.go`) | — (a startup configuration check). Limits: static `--topology` is not refused (its observation controller mints), and has no automatic failover in v1 | ACTIVE | | `INV-CREATE-ONE-IDENTITY-001` | One name, one layout identity; no directory but the record's holds a live HEAD (not none, not deleted). A served volume's deleted name is never created again. | M2 none → created (CreateVolume, restore target creation) | `core/host/master/services.go` `CreateVolume`, `createLifecycleVolume`; `core/frontend/chunkstore/layout/start.go` `Start` | `TestARefusedRestoreLeavesNoTargetRecord` (`core/host/master/restore_refusal_test.go`), `TestARealCatalogRestoreOfARestoreTargetLeavesNothing`, `TestAServedThenDeletedNameIsStillRefused` (`core/host/master/restore_refusal_catalog_test.go`), `TestCreateVolume` (`core/frontend/chunkstore/layout/create_test.go`), `TestDecodeHead_RefusesAnotherVolumesHead` (`core/frontend/chunkstore/layout/head_test.go`) | VolumeCreate OneIdentity (its second clause: a directory with a live HEAD is the record's). Scope: only a refused restore's record, which never left the creation phase (never assigned, never served), is removed, with no filer write. Limits: a served volume's deleted name stays refused until 1.1 | ACTIVE | -| `INV-CREATE-DIR-COLLISION-001` | Only a rejected exclusive VOLUME create proving a valid foreign full identity in the same name/id8 directory permits a pending ordinary create to replace its id. Ready, attached and restore records refuse replacement. No foreign metadata or payload is modified; a lost replacement sync reply settles its existing disk identity. | M2 pending create collision → pending create with fresh id | `core/frontend/chunkstore/layout_create.go` `CreateVolumeRecord`; `core/lifecycle/store.go` `RedrawPendingLayoutID`; `core/host/master/services.go` `createLifecycleVolume` | `TestCreateVolumeExclusiveCollisionRedraws`, `TestCollisionExistingVolumeSafety`, `TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal`, `TestRedrawPendingLayoutID` | MasterCreate3 MUST-VIOLATE rows 220-224; no-proof redraw, use-before-persist and remint-on-replay mutants violate OneIdentity; no change to HEAD ownership/lease rules | ACTIVE | +| `INV-CREATE-DIR-COLLISION-001` | Only a rejected exclusive VOLUME create proving a valid foreign full id in the selected name/id8 directory permits an unready, unattached ordinary create to redraw. Ready, attached and restore records refuse redraw. | M2 pending create collision → pending create with fresh id | `core/frontend/chunkstore/layout_create.go` `CreateVolumeRecord`; `core/lifecycle/store.go` `RedrawPendingLayoutID`; `core/host/master/services.go` `createLifecycleVolume` | `TestCreateVolumeExclusiveCollisionRedraws`, `TestCollisionExistingVolumeSafety`, `TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal`, `TestRedrawPendingLayoutID` | MasterCreate3 MUST-VIOLATE rows 220-224; no-proof redraw, use-before-persist and remint-on-replay mutants violate OneIdentity; no change to HEAD ownership/lease rules | ACTIVE | +| `INV-CREATE-DIR-COLLISION-SETTLE-001` | A collision replacement is persisted before use. A lost synchronization reply settles the identity already on disk; a retry never remints it. | M2 pending create collision → pending create with fresh id | `core/frontend/chunkstore/layout_create.go` `CreateVolumeRecord`; `core/lifecycle/store.go` `RedrawPendingLayoutID`; `core/host/master/services.go` `createLifecycleVolume` | `TestCreateVolumeExclusiveCollisionRedraws`, `TestCollisionExistingVolumeSafety`, `TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal`, `TestRedrawPendingLayoutID` | MasterCreate3 MUST-VIOLATE rows 220-224; no-proof redraw, use-before-persist and remint-on-replay mutants violate OneIdentity; no change to HEAD ownership/lease rules | ACTIVE | +| `INV-CREATE-DIR-COLLISION-FOREIGN-001` | A rejected exclusive create leaves the colliding volume metadata and payload byte-identical, with no new activity or lock; that volume remains attachable and serves its data. | M2 pending create collision → pending create with fresh id | `core/frontend/chunkstore/layout_create.go` `CreateVolumeRecord`; `core/lifecycle/store.go` `RedrawPendingLayoutID`; `core/host/master/services.go` `createLifecycleVolume` | `TestCreateVolumeExclusiveCollisionRedraws`, `TestCollisionExistingVolumeSafety`, `TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal`, `TestRedrawPendingLayoutID` | MasterCreate3 MUST-VIOLATE rows 220-224; no-proof redraw, use-before-persist and remint-on-replay mutants violate OneIdentity; no change to HEAD ownership/lease rules | ACTIVE | | `INV-CLI-TYPED-REFUSAL-001` | The chunk CLI reports a restore the master refused for a foreign source as `restore_source_not_own` (from the master's typed reason, never its text) and a volume the master does not know as `volume_not_found`. | M2 none → created (restore refusal); CLI volume resolve | `core/host/master/services.go` `CreateVolume`; `core/rpc/lifecycleclient/reason.go` `WithReason`, `Reason`; `cmd/sw-block/chunk_b.go` `chunkRestore`, `run` | `TestOpsChunkTypedRefusalCodes` (`cmd/sw-block/chunk_typed_codes_test.go`), `TestReasonRoundTrip` (`core/rpc/lifecycleclient/reason_test.go`), `TestARealCatalogRestoreOfARestoreTargetLeavesNothing` (`core/host/master/restore_refusal_catalog_test.go`) | — (reporting only; the refusal is `INV-CREATE-ONE-IDENTITY-001`'s). Limits: other FailedPrecondition refusals stay the generic `not_admitted` | ACTIVE | | `INV-CLI-RESTORE-VERB-001` | `volume restore --abort` changes nothing unless the master records this command's source, snapshot and request id for the target and this host's settings name exactly it (volume, master, `--layout-id` alone in the extra arguments); a re-run counts only this replica's published line as placed. | client (no state machine): the CLI side of M2 restore create, placement and delete | `cmd/sw-block/volume_backup.go` `volumeRestoreAbort`, `volumeRestore`, `restorePlaced`; `core/host/master/services.go` `lifecycleVolumeResponse` | `TestVolumeRestoreAbortRefusesAForeignTarget`, `TestVolumeRestoreAbortRefusesAnotherLocalInstallation`, `TestVolumeRestoreAbortInterruptedAtEveryStepCompletes`, `TestVolumeRestoreCrashTableBothWays`, `TestVolumeRestorePublicationDuringThePlacement`, `TestVolumeRestorePlacementOfAnotherLineRefuses`, `TestVolumeRestoreCreatesPlacesAndStarts`, `TestVolumeBackupTakesOneSnapshotAndRerunReplays`, `TestVolumeBackupRefusals`, `TestVolumeBackupIncompleteAnswerIsUnknown` (`cmd/sw-block/volume_backup_test.go`), `TestGetVolumeAnswersTheRecordedRestoreTuple` (`core/host/master/volume_restore_tuple_test.go`) | — (the command's model is checked outside the repository; its trace is on the pull request) | ACTIVE | | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`); also in `core/authority/layout_granted_epoch_guard_test.go` | `ControlPlane` `UniqueEpoch` | ACTIVE | @@ -1209,7 +1211,7 @@ Notes: | `INV-WS-DELETE-WITHOUT-ACK-001` | A delete without the holder's acknowledgement is admitted only while the master's record still awaits a replica store (stage 1), marked durably first; the mark freezes the wait, so the primary never serves. Past stage 1 the live-lease refusal stays. | M2 any authority line, stores still awaited → DeleteReserved without the holder's acknowledgement | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited` | `TestANeverCreatedVolumeIsDeletedWithoutItsHolder`, `TestAnEstablishedVolumeIsNotDeletedUnderALiveLease` (`core/host/master/workspace_delete_never_created_test.go`); `TestAStage2VolumeKeepsTheLiveLeaseRefusal`, `TestTheDeleteMarkFreezesTheStoreWait`, `TestAStage2VolumeIsNotMarkedForADeleteWithoutAck` (`core/host/master/workspace_delete_proof_test.go`); `TestDeleteMarkWriterCensus`, `TestDeleteMarkWriterCensusControls` (`core/host/master/store_attestation_census_test.go`) | CreateEvid2 model rows `mut_delete_on_flag_only`, `mut_no_horizon` | ACTIVE | | `INV-CLI-DELETE-PROGRESS-001` | Volume deletion bounds each sweep, continues across transient filer failures while objects are removed, and returns a retryable unavailable answer with progress after a no-progress window. | M9 deleting → deleted | `cmd/sw-block/chunk_volume_delete.go` `deleteVolumeWithProgress` | `TestVolumeDeleteContinuesAcrossTransientObjectFailures` | Existing ordered delete; no new persisted state. | ACTIVE | | `INV-SNAPK-DELETE-GUARD-001` | A source scan requires DeleteVolume to run no-holder check, deleting, release, object deletes and deleted in that order, and allows it as the only remover besides RemoveUnreachable. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-VOLUME-DIR-001` | After store-ready, a volume's master-minted layout identity is immutable; a pending ordinary create may redraw only a proved directory collision (INV-CREATE-DIR-COLLISION-001); its directory is -, created exclusively and never reused. A foreign chunk's owning directory is checked against its full VOLUME id. | Content-named layout and lifecycle create/lookup/launch | `core/frontend/chunkstore/layout` `VolumeDir`; `core/lifecycle/store.go` `CreateVolume`; `core/host/master/services.go` `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient`; `core/launcher/k8s_renderer.go`; `cmd/blockvolume/main.go` `parseFlags`; `core/host/volume/chunk_control.go` `catalogVolume`, `ListSnapshots`, `DeleteSnapshot`, `Usage`; `cmd/blockvolume/chunk_remote.go` `chunkAttachCheck`; `core/frontend/chunkstore/layout/read.go` `Image.Chunk`; `core/rpc/lifecycleclient/identity.go` `ResolveVolume` | `TestRead_ForeignChunkFromSourcePool`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`; `TestLifecycleLayoutIdentity`, `TestLayoutIdentityWriterAndReaders`; `TestGetLifecycleVolumeResolvesOnlyTheDurableIdentity`; `TestResolveVolumeNeverInventsAnIdentity`; `TestLauncherCarriesTheMasterLayoutIdentity`; `TestBlockvolumeLayoutIdentitySelectsTheLocalRoot`; `TestChunkControlUsesTheBoundLayoutIdentity`, `TestChunkControlCatalogLookupErrorIsNotAbsence`, `TestChunkAttachCheckAppliesVolumeRules`; `TestHeadReaders_Enumeration`, `TestDeleteAndDirectorySites_Enumeration` | Lifecycle ids are durable record fields, not assignment epochs. Old records without the field are refused by the new-layout lookup; host metadata is bound to the full name/id and does not fall back to a previous incarnation. Data-path, scheduled snapshot and cleaning callers plus Linux crash qualification remain cutover work. | ACTIVE | +| `INV-SNAPK-VOLUME-DIR-001` | A ready volume keeps its master-minted layout identity. Its - directory is created exclusively and never reused. Foreign chunk owners are checked against their full VOLUME identity. | Content-named layout and lifecycle create/lookup/launch | `core/frontend/chunkstore/layout` `VolumeDir`; `core/lifecycle/store.go` `CreateVolume`; `core/host/master/services.go` `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient`; `core/launcher/k8s_renderer.go`; `cmd/blockvolume/main.go` `parseFlags`; `core/host/volume/chunk_control.go` `catalogVolume`, `ListSnapshots`, `DeleteSnapshot`, `Usage`; `cmd/blockvolume/chunk_remote.go` `chunkAttachCheck`; `core/frontend/chunkstore/layout/read.go` `Image.Chunk`; `core/rpc/lifecycleclient/identity.go` `ResolveVolume` | `TestRead_ForeignChunkFromSourcePool`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`; `TestLifecycleLayoutIdentity`, `TestLayoutIdentityWriterAndReaders`; `TestGetLifecycleVolumeResolvesOnlyTheDurableIdentity`; `TestResolveVolumeNeverInventsAnIdentity`; `TestLauncherCarriesTheMasterLayoutIdentity`; `TestBlockvolumeLayoutIdentitySelectsTheLocalRoot`; `TestChunkControlUsesTheBoundLayoutIdentity`, `TestChunkControlCatalogLookupErrorIsNotAbsence`, `TestChunkAttachCheckAppliesVolumeRules`; `TestHeadReaders_Enumeration`, `TestDeleteAndDirectorySites_Enumeration` | Lifecycle ids are durable record fields, not assignment epochs. Old records without the field are refused by the new-layout lookup; host metadata is bound to the full name/id and does not fall back to a previous incarnation. Data-path, scheduled snapshot and cleaning callers plus Linux crash qualification remain cutover work. | ACTIVE | | `INV-SNAPK-TOMBSTONE-001` | For a restore target without HEAD (never created, or a restore died between its two creates) the operator writes a deleted HEAD exclusively in its directory before releasing, so the restore cannot create it later. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent`, `TargetStore.CreateDeletedHead` | `TestOperatorReleaseDependent`, `TestOperatorReleaseDependent_TombstoneLosesToTheRestore`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-KEEP-HEAD-001` | Nothing removes a HEAD, a VOLUME or a volume directory: a volume delete removes only pool, segment and root objects; a source scan lists every delete and every directory-naming site in core/ and cmd/. | M9 deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`; (source scan) | `TestDeleteVolume_RemovesOnlyObjects`, `TestDeleteAndDirectorySites_Enumeration` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-CREATE-001` | A new volume or restore target gets VOLUME then an unclaimed HEAD (epoch 0, no holder, no claim id, idle), each created exclusively; only createVolume and the operator's tombstone create a HEAD; the first Start claims it from a fresh root. | M9 absent → idle | `core/frontend/chunkstore/layout` `create.go` `CreateVolume`, `CreateTarget` | `TestCreateVolume`, `TestCreateVolume_InterruptAtEveryStep`, `TestUnclaimedHead_Shape`, `TestStart_ClaimsAnUnclaimedHeadFromAFreshRoot`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | From 8bdbc05ba9876e583ae8b45ff828afd583b874e3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 00:06:55 -0800 Subject: [PATCH 10/11] layout: omit an empty ext from Head's own JSON Head's Go JSON (the status and CLI show output) wrote a nil Ext as null, which reads back as the bytes null, and the ext check then refused the HEAD as a v1.0 record carrying ext. Ext is now omitted when empty, so a HEAD without ext reads back without one; a v1.1 HEAD keeps its ext. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/head.go | 4 ++- .../chunkstore/layout/head_version_test.go | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index 08ed17133d..9c896a8023 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -169,7 +169,9 @@ type Head struct { // back verbatim (the ext contract: only additive facts that a writer // keeping them verbatim while it changes the known fields cannot make // wrong; anything an older writer could break bumps Version instead). - Ext json.RawMessage + // Omitted when empty in Head's own JSON (status and CLI output), so a + // HEAD without ext reads back without one, never as the bytes null. + Ext json.RawMessage `json:",omitempty"` } // HeadVersion1 is the v1.1 HEAD format; MaxHeadVersion the newest this diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go index c81cee655d..f20a41ccca 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go @@ -148,3 +148,31 @@ func TestHeadExtIsACanonicalObject(t *testing.T) { } } } + +// Head's own JSON (status and CLI output, not the HEAD codec) round-trips +// to a HEAD that still encodes: a v1.0 HEAD has no ext there, never the +// bytes null, and a v1.1 HEAD keeps its ext. +func TestHeadJSONRoundTripKeepsTheExt(t *testing.T) { + root := RootName{Hash: Sum([]byte("image"))} + v1 := idleHead() + v1.Current, v1.Position = &root, 9 + v1.Version, v1.CurrentBytes, v1.Ext = HeadVersion1, u64(10), json.RawMessage(`{"a":1}`) + for name, h := range map[string]Head{"v1.0": idleHead(), "v1.1": v1} { + raw, err := json.Marshal(h) + if err != nil { + t.Fatal(err) + } + var back Head + if err := json.Unmarshal(raw, &back); err != nil { + t.Fatal(err) + } + want, err := h.Encode() + if err != nil { + t.Fatal(err) + } + got, err := back.Encode() + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("%s: Head JSON %s encodes to %s, %v; want %s", name, raw, got, err, want) + } + } +} From c42dbc95a3ad9f2ae083b53d7a41431668dbda64 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 00:24:00 -0800 Subject: [PATCH 11/11] layout: a HEAD of a newer version is malformed to every caller, named as newer ErrHeadNewerVersion now wraps ErrMalformed: every caller that refuses a malformed HEAD for good refuses a newer one the same way (Start stays a final refusal, never a retry loop), and its text says to use a newer binary. The Start classification table pins it. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/frontend/chunkstore/layout/head.go | 8 +++++--- .../frontend/chunkstore/layout/head_version_test.go | 10 ++++++---- .../durable/provider_layout_start_class_test.go | 1 + seaweed-block/docs/chunk-manifests.md | 6 ++++-- 4 files changed, 16 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index 9c896a8023..4f345a8058 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -181,9 +181,11 @@ const ( MaxHeadVersion = HeadVersion1 ) -// ErrHeadNewerVersion refuses a HEAD written by a newer format version: -// not damage, a binary too old to read it. -var ErrHeadNewerVersion = errors.New("layout: HEAD written by a newer version") +// ErrHeadNewerVersion refuses a HEAD written by a newer format version: a +// binary too old to read it, not damage. It wraps ErrMalformed, so every +// caller that refuses a malformed HEAD for good (Start among them) refuses +// this one the same way; its text names the cure. +var ErrHeadNewerVersion = fmt.Errorf("%w: HEAD written by a newer version: use a newer binary", ErrMalformed) type headDoc struct { Version int `json:"version,omitempty"` diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go index f20a41ccca..d9270824d3 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go @@ -54,7 +54,9 @@ func TestHeadVersion1RoundTripsWithItsExtVerbatim(t *testing.T) { } // Decoding by version: a HEAD of a newer version is refused as newer -// (ErrHeadNewerVersion), never as damage; a v1.0 HEAD (no version) that +// (ErrHeadNewerVersion, which wraps ErrMalformed so every final refusal of +// a malformed HEAD stays final for it, and names a newer binary as the +// cure); a v1.0 HEAD (no version) that // carries a v1.1 field is malformed; a known version still refuses an // unknown top-level field (later fields go in ext). func TestHeadDecodeByVersion(t *testing.T) { @@ -67,8 +69,8 @@ func TestHeadDecodeByVersion(t *testing.T) { t.Fatal(err) } newer := bytes.Replace(b, []byte(`{"version":1,`), []byte(`{"version":2,`), 1) - if _, err := DecodeHead(newer, 1, h.VolumeID); !errors.Is(err, ErrHeadNewerVersion) || errors.Is(err, ErrMalformed) { - t.Fatalf("a newer HEAD: %v; want ErrHeadNewerVersion, not ErrMalformed", err) + if _, err := DecodeHead(newer, 1, h.VolumeID); !errors.Is(err, ErrHeadNewerVersion) || !errors.Is(err, ErrMalformed) { + t.Fatalf("a newer HEAD: %v; want ErrHeadNewerVersion, wrapping ErrMalformed", err) } v0WithSize := bytes.Replace(b, []byte(`{"version":1,`), []byte(`{`), 1) if _, err := DecodeHead(v0WithSize, 1, h.VolumeID); !errors.Is(err, ErrMalformed) { @@ -78,7 +80,7 @@ func TestHeadDecodeByVersion(t *testing.T) { if _, err := DecodeHead(unknownTop, 1, h.VolumeID); !errors.Is(err, ErrMalformed) { t.Fatalf("an unknown top-level field in a v1.1 HEAD: %v; want ErrMalformed (later fields live in ext)", err) } - if !strings.Contains(ErrHeadNewerVersion.Error(), "newer version") { + if msg := ErrHeadNewerVersion.Error(); !strings.Contains(msg, "written by a newer version: use a newer binary") || strings.Contains(msg, "corrupt") { t.Fatal("the newer-version refusal does not say so") } } diff --git a/seaweed-block/core/frontend/durable/provider_layout_start_class_test.go b/seaweed-block/core/frontend/durable/provider_layout_start_class_test.go index 85f1e65a72..99b0c09e77 100644 --- a/seaweed-block/core/frontend/durable/provider_layout_start_class_test.go +++ b/seaweed-block/core/frontend/durable/provider_layout_start_class_test.go @@ -28,6 +28,7 @@ func TestFinalLayoutStartRefusalTable(t *testing.T) { {"foreign volume", layout.ErrIdentity, true}, {"corrupt store", layout.ErrCorrupt, true}, {"malformed store", layout.ErrMalformed, true}, + {"HEAD of a newer version", layout.ErrHeadNewerVersion, true}, {"missing VOLUME", layout.ErrMissing, true}, {"oversized HEAD", layout.ErrHeadTooLarge, true}, {"legacy store", chunkstore.ErrLegacyStore, true}, diff --git a/seaweed-block/docs/chunk-manifests.md b/seaweed-block/docs/chunk-manifests.md index 37d0c18797..d05779f676 100644 --- a/seaweed-block/docs/chunk-manifests.md +++ b/seaweed-block/docs/chunk-manifests.md @@ -57,8 +57,10 @@ commit by change keeps `current_bytes` without lookups: it subtracts the base root and the segments it replaces and adds the new ones; an unknown size stays unknown. Snapshot listings report `manifestBytes`, null when unknown. -A binary refuses a HEAD with a version newer than it reads as a newer version, -not as damage. Known top-level fields stay strict; a v1.0 record carrying a +A binary refuses a HEAD with a version newer than it reads with "HEAD written +by a newer version: use a newer binary". That refusal is a kind of malformed +HEAD, so every final refusal of a malformed HEAD (a holder's Start among them) +stays final for it, with no retry loop. Known top-level fields stay strict; a v1.0 record carrying a v1.1 field is malformed. Upgrade order: every build from this version on reads a version-1 HEAD, but