From 517062f05839535c1f5f829645a734565afbdf27 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:21:47 -0800 Subject: [PATCH 01/21] test: require capture uploads to overlap under an intent --- .../storage/chunk_upload_parallel_test.go | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_upload_parallel_test.go diff --git a/seaweed-block/core/storage/chunk_upload_parallel_test.go b/seaweed-block/core/storage/chunk_upload_parallel_test.go new file mode 100644 index 0000000000..8fd66c0e2d --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_parallel_test.go @@ -0,0 +1,38 @@ +package storage + +import ( + "context" + "testing" + "time" +) + +func TestChunkUploads_DefaultOverlapsBeforeCAS(t *testing.T) { + _, f, l, w := precopyLayer(t, 0, 3) + f.mu.Lock() + f.putGate = make(chan struct{}) + gate := f.putGate + f.putEntered = make(chan string, 8) + entered := f.putEntered + f.mu.Unlock() + done := make(chan error, 1) + go func() { _, err := l.Cut(context.Background()); done <- err }() + defer func() { + close(gate) + if err := <-done; err != nil { + t.Error(err) + } + }() + for i := 0; i < 2; i++ { + select { + case <-entered: + case <-time.After(time.Second): + t.Fatalf("only %d upload calls entered before release; default uploads must overlap", i) + } + } + f.mu.Lock() + if len(f.intents) == 0 || f.casCalls != 0 { + t.Error("overlapping uploads require a durable intent and no root CAS") + } + f.mu.Unlock() + _ = w +} From 76c8de6b10ab3d9bfbde0a883aa5cc24f645c9e4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:22:35 -0800 Subject: [PATCH 02/21] feat: bound parallel capture and pre-copy uploads --- seaweed-block/core/storage/chunk_layer.go | 28 +++++++++---- seaweed-block/core/storage/chunk_seam.go | 3 ++ seaweed-block/core/storage/chunk_upload.go | 49 ++++++++++++++++++++++ 3 files changed, 72 insertions(+), 8 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_upload.go diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 99753e159e..461ea7a337 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -134,6 +134,12 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) if remote == nil || cfg.Bitmap == nil || cfg.ChunkBlocks == 0 { return nil, errors.New("storage: chunk layer needs a remote, a bitmap store and ChunkBlocks > 0") } + if cfg.UploadConcurrency < 0 || cfg.UploadConcurrency > 64 { + return nil, errors.New("storage: upload concurrency must be between 1 and 64 (0 defaults to 8)") + } + if cfg.UploadConcurrency == 0 { + cfg.UploadConcurrency = 8 + } if cfg.ReadMissTimeout <= 0 { cfg.ReadMissTimeout = defaultReadMissTimeout } @@ -846,12 +852,15 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } intents = append(intents, id) } + if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error { + u := uploads[i] + return l.remote.Put(ctx, u.key, u.c.data) + }); err != nil { + l.abortCut(all) + l.dropIntents(ctx, intents) + return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w: %w", errChunkRemoteUnavailable, err) + } for _, u := range uploads { - if err := l.remote.Put(ctx, u.key, u.c.data); err != nil { - l.abortCut(all) - l.dropIntents(ctx, intents) - return chunkCutResult{}, fmt.Errorf("storage: capture upload chunk %d: %w: %w", u.c.idx, errChunkRemoteUnavailable, err) - } next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum} newKeys[u.c.idx] = u.key changed = append(changed, u.c.idx) @@ -1454,10 +1463,13 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint return nil, intents, fmt.Errorf("storage: capture stage intent: %w: %w", errChunkRemoteUnavailable, err) } intents = append(intents, id) + if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error { + u := uploads[i] + return l.remote.Put(ctx, u.key, u.data) + }); err != nil { + return nil, intents, fmt.Errorf("storage: capture stage upload: %w: %w", errChunkRemoteUnavailable, err) + } for _, u := range uploads { - if err := l.remote.Put(ctx, u.key, u.data); err != nil { - return nil, intents, fmt.Errorf("storage: capture stage chunk %d: %w: %w", u.idx, errChunkRemoteUnavailable, err) - } st.UploadedChunks++ st.UploadedBytes += int64(len(u.data)) u.data = nil diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 2a11147c43..f72e31e5ed 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -333,6 +333,9 @@ type chunkLayerConfig struct { // Zero: unbounded, no staging. BarrierBound int + // UploadConcurrency bounds capture/pre-copy Put calls (0 defaults to 8). + UploadConcurrency int + // testReconcileHold, set only by this package's tests, holds the // reconciler before each slice until a token is received or the // channel is closed. diff --git a/seaweed-block/core/storage/chunk_upload.go b/seaweed-block/core/storage/chunk_upload.go new file mode 100644 index 0000000000..b1e79b7b2f --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload.go @@ -0,0 +1,49 @@ +package storage + +import ( + "context" + "sync" +) + +// uploadBatch owns and joins all Put calls before its caller settles intents. +// No storage/publication lock is acquired by workers. Cancellation stops new +// admission; a remote ignoring cancellation remains joined, never declared done. +func (l *chunkLayerImpl) uploadBatch(ctx context.Context, n int, put func(context.Context, int) error) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + var mu sync.Mutex + next := 0 + var first error + var wg sync.WaitGroup + workers := min(l.cfg.UploadConcurrency, n) + for j := 0; j < workers; j++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + mu.Lock() + if first != nil || next == n || ctx.Err() != nil { + mu.Unlock() + return + } + i := next + next++ + mu.Unlock() + if err := put(ctx, i); err != nil { + mu.Lock() + if first == nil { + first = err + cancel() + } + mu.Unlock() + return + } + } + }() + } + wg.Wait() + if first != nil { + return first + } + return ctx.Err() +} From c1a917b6bf286ba1a7d58805381335fa94757cec Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:23:31 -0800 Subject: [PATCH 03/21] test: require a real capture to publish a segmented root --- .../core/frontend/chunkstore/manifest_test.go | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/manifest_test.go diff --git a/seaweed-block/core/frontend/chunkstore/manifest_test.go b/seaweed-block/core/frontend/chunkstore/manifest_test.go new file mode 100644 index 0000000000..7055bfd47e --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest_test.go @@ -0,0 +1,64 @@ +package chunkstore + +import ( + "bytes" + "context" + "encoding/json" + "path" + "path/filepath" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestManifest_CapturePublishesSegmentRoot(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + ctx := context.Background() + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + p := filepath.Join(t.TempDir(), "volume") + s, err := storage.CreateWALStore(p, 64, 4096) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if _, err = s.Recover(); err != nil { + t.Fatal(err) + } + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true, Bitmap: storage.NewFileChunkBitmapStore(p + ".bitmap")}) + if err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0x61}, 4096) + if _, err = s.Write(0, want); err != nil { + t.Fatal(err) + } + if _, err = l.Capture(ctx); err != nil { + t.Fatal(err) + } + e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) + if err != nil { + t.Fatal(err) + } + var doc struct { + Format int `json:"format"` + Chunks map[string]any `json:"chunks"` + Segments map[string]any `json:"segments"` + } + if err = json.Unmarshal(e.Content, &doc); err != nil { + t.Fatal(err) + } + if doc.Format != 2 || len(doc.Chunks) != 0 || len(doc.Segments) != 1 { + t.Fatalf("cut did not publish a small segmented root: %s", e.Content) + } + h, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + data, err := r.Get(ctx, h.Chunks[0].Key) + if err != nil || !bytes.Equal(data[:4096], want) { + t.Fatalf("resolved cut bytes: %v", err) + } +} From 9dfef3b4fd52613b2d06c560c0027271f04a160f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:25:01 -0800 Subject: [PATCH 04/21] feat: build immutable range manifests before the fenced root CAS --- .../core/frontend/chunkstore/chunk_remote.go | 44 ++++- .../core/frontend/chunkstore/manifest.go | 170 ++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 21 ++- seaweed-block/core/storage/chunk_manifest.go | 18 ++ seaweed-block/core/storage/chunk_seam.go | 17 +- 5 files changed, 254 insertions(+), 16 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/manifest.go create mode 100644 seaweed-block/core/storage/chunk_manifest.go diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index cdea709acf..6e5aadd22c 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -329,12 +329,15 @@ func decodeIntent(p string, e *filerpb.Entry) (storage.ChunkIntent, error) { } type headDoc struct { - Format int `json:"format"` - Gen uint64 `json:"gen"` - Epoch uint64 `json:"epoch"` - Holder string `json:"holder"` - RemoteLSN uint64 `json:"remote_lsn"` - Chunks map[uint64]refDoc `json:"chunks"` + Segments map[uint64]storage.ChunkSegment `json:"segments,omitempty"` + ChunkBytes uint64 `json:"chunk_bytes,omitempty"` + ChunkCount int `json:"chunk_count,omitempty"` + Format int `json:"format"` + Gen uint64 `json:"gen"` + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + RemoteLSN uint64 `json:"remote_lsn"` + Chunks map[uint64]refDoc `json:"chunks,omitempty"` // State is "active" or "detached"; a document without it is active. // DetachedBy names the holder whose final cut (this generation) a // detached HEAD is; it is absent unless State is detached. @@ -364,7 +367,11 @@ func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { if err != nil { return storage.ChunkHead{}, err } - return decodeHead(path.Join(r.root, headName), e) + h, err := decodeHead(path.Join(r.root, headName), e) + if err != nil { + return h, err + } + return r.resolveManifest(ctx, h) } // CASHead installs next, at generation expected.Gen+1, only if the stored @@ -422,6 +429,13 @@ func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) { } doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} } + if h.Segments != nil { + doc.Format = 2 + doc.Chunks = nil + doc.Segments = h.Segments + doc.ChunkBytes = h.ChunkBytes + doc.ChunkCount = h.ManifestChunkCount + } body, err := json.Marshal(doc) if err != nil { return nil, err @@ -481,7 +495,7 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) { if err := json.Unmarshal(content, &doc); err != nil { return fail("decode: %v", err) } - if doc.Format != headFormat { + if doc.Format != headFormat && doc.Format != 2 { return fail("format %d not supported (want %d)", doc.Format, headFormat) } if doc.Gen == 0 { @@ -519,6 +533,20 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) { copy(cr.SHA256[:], sum) h.Chunks[idx] = cr } + if doc.Format == 2 { + if len(doc.Chunks) != 0 { + return fail("segmented root contains flat chunks") + } + h.Segments = doc.Segments + if h.Segments == nil { + h.Segments = map[uint64]storage.ChunkSegment{} + } + h.ChunkBytes = doc.ChunkBytes + h.ManifestChunkCount = doc.ChunkCount + if err := validateRoot(h); err != nil { + return h, err + } + } return h, nil } diff --git a/seaweed-block/core/frontend/chunkstore/manifest.go b/seaweed-block/core/frontend/chunkstore/manifest.go new file mode 100644 index 0000000000..dc4c7ef9ec --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest.go @@ -0,0 +1,170 @@ +package chunkstore + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "path" + "reflect" + "strings" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// One segment spans a fixed logical GiB. This is a format constant, not a knob. +const manifestSegmentBytes uint64 = 1 << 30 +const maxManifestBytes = 64 << 20 + +type segmentDoc struct { + Format int `json:"format"` + Range uint64 `json:"range"` + ChunkBytes uint64 `json:"chunk_bytes"` + Owner string `json:"owner"` + Chunks map[uint64]storage.ChunkRef `json:"chunks"` +} + +func qualified(owner, key string) string { + if strings.HasPrefix(key, "@") { + return key + } + return "@" + owner + "/" + key +} + +func manifestCount(h storage.ChunkHead) int { + if h.Segments != nil { + return h.ManifestChunkCount + } + return len(h.Chunks) +} + +func validateRoot(h storage.ChunkHead) error { + if h.ChunkBytes < 4096 || h.ChunkBytes > manifestSegmentBytes || manifestSegmentBytes%h.ChunkBytes != 0 || h.ManifestChunkCount < 0 { + return errors.New("chunkstore: invalid manifest geometry/count") + } + count := 0 + for group, ref := range h.Segments { + if CheckVolumeID(ref.Owner) != nil || storage.ValidChunkKey(ref.Key) != nil || ref.Count <= 0 || uint64(ref.Count) > manifestSegmentBytes/h.ChunkBytes || group > ^uint64(0)/(manifestSegmentBytes/h.ChunkBytes) { + return errors.New("chunkstore: invalid segment reference") + } + count += ref.Count + } + if count != h.ManifestChunkCount { + return errors.New("chunkstore: manifest count mismatch") + } + return nil +} + +// PrepareManifest never changes generation/epoch or publishes the root. All +// segment keys are protected before their Put; the cut owns returned intents. +func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.ChunkHead, chunkBytes uint64) (storage.ChunkHead, []string, error) { + next.ChunkBytes = chunkBytes + next.ManifestChunkCount = len(next.Chunks) + next.Segments = map[uint64]storage.ChunkSegment{} + if chunkBytes < 4096 || chunkBytes > manifestSegmentBytes || manifestSegmentBytes%chunkBytes != 0 { + return next, nil, errors.New("chunkstore: invalid segment geometry") + } + per := manifestSegmentBytes / chunkBytes + owner := path.Base(r.root) + groups := map[uint64]map[uint64]storage.ChunkRef{} + canonical := make(map[uint64]storage.ChunkRef, len(next.Chunks)) + for idx, ref := range next.Chunks { + ref.Key = qualified(owner, ref.Key) + canonical[idx] = ref + group := idx / per + if groups[group] == nil { + groups[group] = map[uint64]storage.ChunkRef{} + } + groups[group][idx] = ref + } + next.Chunks = canonical + type upload struct { + key string + data []byte + } + var uploads []upload + for group, chunks := range groups { + old := map[uint64]storage.ChunkRef{} + for idx, ref := range base.Chunks { + if idx/per == group { + ref.Key = qualified(owner, ref.Key) + old[idx] = ref + } + } + if previous, ok := base.Segments[group]; ok && base.ChunkBytes == chunkBytes && reflect.DeepEqual(chunks, old) { + next.Segments[group] = previous + continue + } + body, err := json.Marshal(segmentDoc{1, group, chunkBytes, owner, chunks}) + if err != nil { + return next, nil, err + } + if len(body) > maxManifestBytes { + return next, nil, errors.New("chunkstore: manifest too large") + } + nonce := make([]byte, 16) + if _, err := rand.Read(nonce); err != nil { + return next, nil, err + } + key := fmt.Sprintf("manifests/%x", nonce) + next.Segments[group] = storage.ChunkSegment{Key: qualified(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks)} + uploads = append(uploads, upload{key, body}) + } + if err := validateRoot(next); err != nil { + return next, nil, err + } + if len(uploads) == 0 { + return next, nil, nil + } + keys := make([]string, len(uploads)) + for i, u := range uploads { + keys[i] = u.key + } + id, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: base.Gen, Epoch: next.Epoch, Holder: next.Holder, Keys: keys}) + if err != nil { + return next, nil, err + } + ids := []string{id} + for _, u := range uploads { + if err := r.Put(ctx, u.key, u.data); err != nil { + return next, ids, err + } + } + return next, ids, nil +} + +func (r *ChunkRemote) resolveManifest(ctx context.Context, h storage.ChunkHead) (storage.ChunkHead, error) { + if h.Segments == nil { + return h, nil + } + if err := validateRoot(h); err != nil { + return h, err + } + h.Chunks = map[uint64]storage.ChunkRef{} + for group, ref := range h.Segments { + body, err := r.Get(ctx, ref.Key) + if err != nil { + return h, fmt.Errorf("chunkstore: read published segment: %w", err) + } + if len(body) > maxManifestBytes || sha256.Sum256(body) != ref.SHA256 { + return h, errors.New("chunkstore: segment hash/size mismatch") + } + var doc segmentDoc + if err := json.Unmarshal(body, &doc); err != nil { + return h, err + } + if doc.Format != 1 || doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count { + return h, errors.New("chunkstore: invalid segment contents") + } + for idx, cr := range doc.Chunks { + if idx/(manifestSegmentBytes/h.ChunkBytes) != group || storage.ValidChunkKey(cr.Key) != nil { + return h, errors.New("chunkstore: segment index/key invalid") + } + cr.Key = qualified(ref.Owner, cr.Key) + h.Chunks[idx] = cr + } + } + return h, nil +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 461ea7a337..f005af7267 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -266,6 +266,12 @@ func copyHead(h chunkHead) chunkHead { d := *h.DetachedBy out.DetachedBy = &d } + if h.Segments != nil { + out.Segments = make(map[uint64]ChunkSegment, len(h.Segments)) + for k, v := range h.Segments { + out.Segments[k] = v + } + } out.Chunks = make(map[uint64]chunkRef, len(h.Chunks)) for k, v := range h.Chunks { out.Chunks[k] = v @@ -867,8 +873,21 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.UploadedChunks++ st.UploadedBytes += int64(len(u.c.data)) } + upgrade := false + if builder, ok := l.remote.(ChunkManifestBuilder); ok { + upgrade = baseHead.Segments == nil + var ids []string + var err error + next, ids, err = builder.PrepareManifest(ctx, baseHead, next, uint64(l.blockSize)*l.chunkBlocks) + intents = append(intents, ids...) + if err != nil { + l.abortCut(all) + l.dropIntents(ctx, intents) + return chunkCutResult{}, err + } + } st.UploadNs = time.Since(uploadStart).Nanoseconds() - if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) { + if !upgrade && !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) { // A no-op cut still observes authority: a fresh host may have // claimed HEAD without uploading a single chunk since our last cut. cur, err := l.remote.GetHead(ctx) diff --git a/seaweed-block/core/storage/chunk_manifest.go b/seaweed-block/core/storage/chunk_manifest.go new file mode 100644 index 0000000000..2125321931 --- /dev/null +++ b/seaweed-block/core/storage/chunk_manifest.go @@ -0,0 +1,18 @@ +package storage + +import "context" + +// ChunkSegment names an immutable range manifest. Owner is the namespace in +// which that manifest was encoded; forks preserve it without rewriting data. +type ChunkSegment struct { + Key string `json:"key"` + SHA256 [32]byte `json:"sha256"` + Owner string `json:"owner"` + Count int `json:"count"` +} + +// ChunkManifestBuilder prepares immutable segments before the existing root +// CAS. Returned intents belong to the cut and follow its settlement rules. +type ChunkManifestBuilder interface { + PrepareManifest(context.Context, ChunkHead, ChunkHead, uint64) (ChunkHead, []string, error) +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index f72e31e5ed..ef63dae8ed 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -175,13 +175,16 @@ type chunkHeadVersion struct { // move). Every normal cut publishes State = active and no DetachedBy; a new // holder's takeover does the same. type chunkHead struct { - Gen uint64 - Epoch uint64 - Holder string - RemoteLSN uint64 - Chunks map[uint64]chunkRef - State string - DetachedBy *chunkDetachedBy + Gen uint64 + Epoch uint64 + Holder string + RemoteLSN uint64 + Chunks map[uint64]chunkRef + Segments map[uint64]ChunkSegment + ChunkBytes uint64 + ManifestChunkCount int + State string + DetachedBy *chunkDetachedBy } // HEAD states. From 11b7aa94d89bd3258448da44e20f107f354f5429 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:25:58 -0800 Subject: [PATCH 05/21] test: retain segmented fork data after deleting the parent snapshot --- .../core/frontend/chunkstore/manifest_test.go | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/manifest_test.go b/seaweed-block/core/frontend/chunkstore/manifest_test.go index 7055bfd47e..4c44f4f9dc 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_test.go @@ -7,6 +7,7 @@ import ( "path" "path/filepath" "testing" + "time" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -62,3 +63,75 @@ func TestManifest_CapturePublishesSegmentRoot(t *testing.T) { t.Fatalf("resolved cut bytes: %v", err) } } + +func publishSegmented(t *testing.T, f *fakeFiler, b gcBlobs) (*ChunkRemote, storage.ChunkHead) { + t.Helper() + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41), 1: chunkBytes(0x42)}) + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + next, ids, err := r.PrepareManifest(context.Background(), h, h, 32768) + if err != nil { + t.Fatal(err) + } + gen, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next) + if err != nil { + t.Fatal(err) + } + next.Gen = gen + for _, id := range ids { + if err = r.DeleteIntent(context.Background(), id); err != nil { + t.Fatal(err) + } + } + return r, next +} + +func TestManifest_ForkAfterParentSnapshotDelete(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, h := publishSegmented(t, f, b) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { + t.Fatal(err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + fork, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) + fh, err := fork.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if len(fh.Segments) != 1 || len(fh.Chunks) != 2 { + t.Fatalf("fork lost root/children: %+v", fh) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN}); err != nil { + t.Fatal(err) + } + for i := 0; i < 3; i++ { + if _, err := g.Run(ctx); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + } + fh, err = fork.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + for idx, ref := range fh.Chunks { + got, err := fork.Get(ctx, ref.Key) + if err != nil || !bytes.Equal(got, chunkBytes(byte(0x41+idx))) { + t.Fatalf("fork lost shared chunk %d after parent delete: %v", idx, err) + } + } +} + +func TestManifest_GCReadsPublishedSegments(t *testing.T) { + f, b, _, g, _ := gcFixture(t) + publishSegmented(t, f, b) + out, err := g.Preview(context.Background()) + if err != nil || len(out.Roots) == 0 { + t.Fatalf("GC cannot trace published segment: %+v %v", out, err) + } +} From 631e30537b38e50ee46af715d54dd6309b367307 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:26:44 -0800 Subject: [PATCH 06/21] feat: preserve root-only forks and trace segment children during GC --- .../core/frontend/chunkstore/catalog.go | 24 +++++++++-- .../core/frontend/chunkstore/chunk_remote.go | 18 ++++---- seaweed-block/core/frontend/chunkstore/gc.go | 41 ++++++++++++++++++- .../core/frontend/chunkstore/manifest.go | 10 ++--- seaweed-block/core/storage/chunk_seam.go | 14 ++++--- 5 files changed, 83 insertions(+), 24 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 2ce0cc98a0..f1fe223022 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -664,7 +664,7 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) { } return SnapshotInfo{ VolumeID: doc.VolumeID, Name: doc.Name, HeadGen: head.Gen, HeadEpoch: head.Epoch, CutLSN: head.RemoteLSN, - CreatedNs: doc.CreatedNs, State: state, ChunkCount: len(head.Chunks), ManifestBytes: len(e.GetContent()), + CreatedNs: doc.CreatedNs, State: state, ChunkCount: manifestCount(head), ManifestBytes: len(e.GetContent()), Consistency: doc.Consistency, Labels: doc.Labels, Parent: doc.Parent, ExpiresAtNs: doc.ExpiresAtNs, Class: doc.Class, head: head, geo: doc.Geometry, }, doc.RequestID, nil @@ -785,6 +785,13 @@ func headDigest(h storage.ChunkHead) (string, error) { } func headKeys(h storage.ChunkHead) []string { + if h.Segments != nil { + keys := make([]string, 0, len(h.Segments)) + for _, ref := range h.Segments { + keys = append(keys, ref.Key) + } + return keys + } keys := make([]string, 0, len(h.Chunks)) for _, ref := range h.Chunks { keys = append(keys, ref.Key) @@ -864,7 +871,7 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe tag := "snapshot:" + vol + "/" + req.Name + "/" + attempt deadline := readAt.Add(c.deadline()) - id, err := putIntent(ctx, c.f, root, storage.ChunkIntent{Gen: head.Gen, Epoch: head.Epoch, Holder: tag, Keys: headKeys(head), + id, err := putIntent(ctx, c.f, root, storage.ChunkIntent{Gen: head.Gen, Epoch: head.Epoch, Holder: tag, Keys: headKeys(head), Segments: head.Segments, ChunkBytes: head.ChunkBytes, DeadlineNs: deadline.UnixNano()}) if err != nil { return SnapshotInfo{}, remoteErr(err, "intent for snapshot %s/%s", vol, req.Name) @@ -1185,6 +1192,15 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) } head := storage.ChunkHead{Gen: 1, Epoch: 0, Holder: "", RemoteLSN: src.RemoteLSN, Chunks: make(map[uint64]storage.ChunkRef, len(src.Chunks)), State: storage.ChunkHeadActive} qualified := 0 + if src.Segments != nil { + head.Segments = make(map[uint64]storage.ChunkSegment, len(src.Segments)) + head.ChunkBytes, head.ManifestChunkCount = src.ChunkBytes, src.ManifestChunkCount + for idx, ref := range src.Segments { + ref.Key = qualifyManifestKey(req.Source, ref.Key) + head.Segments[idx] = ref + qualified++ + } + } for idx, ref := range src.Chunks { if !strings.HasPrefix(ref.Key, "@") { ref.Key = "@" + req.Source + "/" + ref.Key @@ -1193,7 +1209,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) head.Chunks[idx] = ref } record := &ForkRecord{RequestID: req.RequestID, Source: req.Source, Snapshot: req.Snapshot, SourceGen: snap.HeadGen, - HeadSHA256: digest, RemoteLSN: head.RemoteLSN, ChunkCount: len(head.Chunks), QualifiedRefs: qualified} + HeadSHA256: digest, RemoteLSN: head.RemoteLSN, ChunkCount: manifestCount(head), QualifiedRefs: qualified} if ok { // An incomplete fork of this request resumes only on the same image. @@ -1230,7 +1246,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) } he.Extended[extReq] = []byte(req.RequestID) deadline := readAt.Add(c.deadline()) - id, err := putIntent(ctx, c.f, dstRoot, storage.ChunkIntent{Gen: 0, Epoch: 0, Holder: tag, Keys: headKeys(head), + id, err := putIntent(ctx, c.f, dstRoot, storage.ChunkIntent{Gen: 0, Epoch: 0, Holder: tag, Keys: headKeys(head), Segments: head.Segments, ChunkBytes: head.ChunkBytes, DeadlineNs: deadline.UnixNano()}) if err != nil { return ForkResult{}, remoteErr(err, "intent for fork %s", req.Target) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 6e5aadd22c..8f3b801a53 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -214,12 +214,14 @@ func (r *ChunkRemote) Get(ctx context.Context, key string) ([]byte, error) { func (r *ChunkRemote) Delete(context.Context, string) error { return ErrDeleteUnsupported } type intentDoc struct { - Format int `json:"format"` - Gen uint64 `json:"gen"` - Epoch uint64 `json:"epoch"` - Holder string `json:"holder"` - Keys []string `json:"keys"` - CreatedNs int64 `json:"created_ns"` + Segments map[uint64]storage.ChunkSegment `json:"segments,omitempty"` + ChunkBytes uint64 `json:"chunk_bytes,omitempty"` + Format int `json:"format"` + Gen uint64 `json:"gen"` + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + Keys []string `json:"keys"` + CreatedNs int64 `json:"created_ns"` // DeadlineNs: a copy intent's publication deadline (0: a capture intent). DeadlineNs int64 `json:"deadline_ns,omitempty"` } @@ -246,7 +248,7 @@ func putIntent(ctx context.Context, f Filer, root string, in storage.ChunkIntent return "", err } now := time.Now() - body, err := json.Marshal(intentDoc{Format: intentFormat, Gen: in.Gen, Epoch: in.Epoch, Holder: in.Holder, Keys: in.Keys, CreatedNs: now.UnixNano(), DeadlineNs: in.DeadlineNs}) + body, err := json.Marshal(intentDoc{Format: intentFormat, Gen: in.Gen, Epoch: in.Epoch, Holder: in.Holder, Keys: in.Keys, CreatedNs: now.UnixNano(), DeadlineNs: in.DeadlineNs, Segments: in.Segments, ChunkBytes: in.ChunkBytes}) if err != nil { return "", err } @@ -325,7 +327,7 @@ func decodeIntent(p string, e *filerpb.Entry) (storage.ChunkIntent, error) { return fail("name or extended gen/epoch/holder disagree with the document") } return storage.ChunkIntent{ID: e.GetName(), Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, - Keys: append([]string(nil), doc.Keys...), CreatedNs: doc.CreatedNs, DeadlineNs: doc.DeadlineNs}, nil + Keys: append([]string(nil), doc.Keys...), CreatedNs: doc.CreatedNs, DeadlineNs: doc.DeadlineNs, Segments: doc.Segments, ChunkBytes: doc.ChunkBytes}, nil } type headDoc struct { diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 32a3740c44..5e44a840d6 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -130,7 +130,7 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e } result.Volumes = len(volumes) for _, vol := range volumes { - r, e := NewChunkRemote(g.cat.f, nilBlobs{}, path.Join(g.cat.base, vol)) + r, e := NewChunkRemote(g.cat.f, gcBlobReader{g.blobs}, path.Join(g.cat.base, vol)) if e != nil { return result, e } @@ -139,6 +139,19 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e return result, e } addHead := func(kind, id string, head storage.ChunkHead) error { + var err error + head, err = r.resolveManifest(ctx, head) + if err != nil { + return err + } + for _, ref := range head.Segments { + dir, name, err := r.keyLocation(ref.Key) + if err != nil { + return err + } + roots[path.Join(dir, name)] = true + } + keys := make([]string, 0, len(head.Chunks)) for _, ref := range head.Chunks { keys = append(keys, ref.Key) @@ -212,6 +225,15 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e if strings.HasPrefix(in.Holder, "snapshot:") || strings.HasPrefix(in.Holder, "fork:") { kind = "retained_copy_intent" } + if in.Segments != nil { + h := storage.ChunkHead{Segments: in.Segments, ChunkBytes: in.ChunkBytes} + for _, ref := range in.Segments { + h.ManifestChunkCount += ref.Count + } + if err := addHead(kind, in.ID, h); err != nil { + return result, err + } + } result.Roots = append(result.Roots, GCRoot{Kind: kind, Volume: vol, ID: in.ID, Keys: append([]string{}, in.Keys...), Epoch: in.Epoch, Holder: in.Holder}) for _, key := range in.Keys { dir, name, e := r.keyLocation(key) @@ -337,3 +359,20 @@ func (nilBlobs) Get(context.Context, string) ([]byte, error) { // The binding name was already validated before reclamation admission. func mustUnescapeGCKey(name string) string { k, _ := url.PathUnescape(name); return k } + +// GC needs immutable segment bytes as well as deletion. Flat-only legacy +// adapters remain usable; a segmented root without a reader refuses the mark. +type gcBlobReader struct{ BlobDeleter } + +func (b gcBlobReader) Put(context.Context, []byte) (string, error) { + return "", errors.New("chunkstore: GC is read-only during mark") +} +func (b gcBlobReader) Get(ctx context.Context, fid string) ([]byte, error) { + reader, ok := b.BlobDeleter.(interface { + Get(context.Context, string) ([]byte, error) + }) + if !ok { + return nil, errors.New("chunkstore: GC segment reader unavailable") + } + return reader.Get(ctx, fid) +} diff --git a/seaweed-block/core/frontend/chunkstore/manifest.go b/seaweed-block/core/frontend/chunkstore/manifest.go index dc4c7ef9ec..a67e78d9f0 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest.go +++ b/seaweed-block/core/frontend/chunkstore/manifest.go @@ -26,7 +26,7 @@ type segmentDoc struct { Chunks map[uint64]storage.ChunkRef `json:"chunks"` } -func qualified(owner, key string) string { +func qualifyManifestKey(owner, key string) string { if strings.HasPrefix(key, "@") { return key } @@ -71,7 +71,7 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch groups := map[uint64]map[uint64]storage.ChunkRef{} canonical := make(map[uint64]storage.ChunkRef, len(next.Chunks)) for idx, ref := range next.Chunks { - ref.Key = qualified(owner, ref.Key) + ref.Key = qualifyManifestKey(owner, ref.Key) canonical[idx] = ref group := idx / per if groups[group] == nil { @@ -89,7 +89,7 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch old := map[uint64]storage.ChunkRef{} for idx, ref := range base.Chunks { if idx/per == group { - ref.Key = qualified(owner, ref.Key) + ref.Key = qualifyManifestKey(owner, ref.Key) old[idx] = ref } } @@ -109,7 +109,7 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch return next, nil, err } key := fmt.Sprintf("manifests/%x", nonce) - next.Segments[group] = storage.ChunkSegment{Key: qualified(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks)} + next.Segments[group] = storage.ChunkSegment{Key: qualifyManifestKey(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks)} uploads = append(uploads, upload{key, body}) } if err := validateRoot(next); err != nil { @@ -162,7 +162,7 @@ func (r *ChunkRemote) resolveManifest(ctx context.Context, h storage.ChunkHead) if idx/(manifestSegmentBytes/h.ChunkBytes) != group || storage.ValidChunkKey(cr.Key) != nil { return h, errors.New("chunkstore: segment index/key invalid") } - cr.Key = qualified(ref.Owner, cr.Key) + cr.Key = qualifyManifestKey(ref.Owner, cr.Key) h.Chunks[idx] = cr } } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index ef63dae8ed..9c74e1317a 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -243,12 +243,14 @@ type chunkRemote interface { // chunkIntent is one live intent: the keys a holder at HEAD generation Gen // and epoch Epoch is about to publish. type chunkIntent struct { - ID string // "-"; assigned by PutIntent - Gen uint64 - Epoch uint64 - Holder string - Keys []string - CreatedNs int64 // assigned by PutIntent + Segments map[uint64]ChunkSegment + ChunkBytes uint64 + ID string // "-"; assigned by PutIntent + Gen uint64 + Epoch uint64 + Holder string + Keys []string + CreatedNs int64 // assigned by PutIntent // DeadlineNs (unix ns) is a copy intent's publication deadline, kept as // metadata: a GC sweep settles a dead copy attempt by claiming its // publishing entry with a tombstone, never by the deadline alone (W5 From ce6e4449d871811565fd54286c2a0ef820ca7483 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:27:57 -0800 Subject: [PATCH 07/21] feat: expose upload concurrency and retain manifest-aware contract checks --- seaweed-block/cmd/blockvolume/chunk_remote.go | 18 +++++++++++------- seaweed-block/cmd/blockvolume/main.go | 2 ++ .../core/frontend/chunkstore/catalog_test.go | 4 ++-- .../frontend/chunkstore/chunk_remote_test.go | 4 ++-- .../core/frontend/chunkstore/manifest_test.go | 4 ++++ .../core/frontend/durable/provider.go | 2 ++ .../core/frontend/durable/provider_chunk.go | 15 ++++++++------- 7 files changed, 31 insertions(+), 18 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index 52cc013570..8c3b41920e 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -29,12 +29,13 @@ const ( ) type chunkFlags struct { - filer string - path string - collection string - replication string - captureInterval time.Duration - dirtyThreshold int + filer string + path string + collection string + replication string + captureInterval time.Duration + dirtyThreshold int + uploadConcurrency int // controlEndpoint mounts the /chunk/* routes on the status listener. controlEndpoint bool } @@ -44,7 +45,7 @@ func validateChunkFlags(f flags) error { if f.durableImpl != "walstore-chunk" { if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath || c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold || - c.controlEndpoint { + c.uploadConcurrency != 8 || c.controlEndpoint { return errors.New("--chunk-* flags require --durable-impl=walstore-chunk") } return nil @@ -64,6 +65,9 @@ func validateChunkFlags(f flags) error { if c.captureInterval < 0 { return fmt.Errorf("--chunk-capture-interval=%s must not be negative", c.captureInterval) } + if c.uploadConcurrency < 1 || c.uploadConcurrency > 64 { + return errors.New("--chunk-upload-concurrency must be between 1 and 64") + } if c.dirtyThreshold < 0 { return fmt.Errorf("--chunk-dirty-threshold=%d must not be negative", c.dirtyThreshold) } diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 214b181c4a..467873372d 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -191,6 +191,7 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.chunk.collection, "chunk-collection", "", "walstore-chunk: collection for chunk needles (empty = filer default / storage rule)") fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)") fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: automatic cut once this long has passed since the last successful cut; 0 (default) disables the timer, e.g. 15m as a host-loss safety net") + fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)") fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: bound on one cut's barrier copy, in chunks; never triggers a cut; 0 = unbounded") fs.BoolVar(&f.chunk.controlEndpoint, "chunk-control-endpoint", false, "walstore-chunk: expose the /chunk/* control routes (cut, snapshot, snapshots, snapshot/delete, detach) on the status HTTP listener; off by default; loopback-only like the listener") fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)") @@ -604,6 +605,7 @@ func run(f flags) int { chunk, chunkErr = newChunkWiring(f.chunk) cfg.ChunkCaptureInterval = f.chunk.captureInterval cfg.ChunkDirtyThreshold = f.chunk.dirtyThreshold + cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency cfg.ChunkHolder = chunkHolder(f) if chunkErr == nil { cfg.ChunkRemoteFor = chunk.remoteFor diff --git a/seaweed-block/core/frontend/chunkstore/catalog_test.go b/seaweed-block/core/frontend/chunkstore/catalog_test.go index 46340a239b..533b82f2ba 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_test.go @@ -489,8 +489,8 @@ func TestFork_ThenFreshHostReadsSnapshotImage(t *testing.T) { if len(keysAfter) != len(keysBefore) { t.Fatalf("the fork's cut wrote %d keys into the source volume", len(keysAfter)-len(keysBefore)) } - if own, _ := f.ListEntries(ctx, catBase+"/v2/keys", "", "", 0); len(own) != 1 { - t.Fatalf("the fork's cut wrote %d keys of its own, want 1", len(own)) + if own, _ := f.ListEntries(ctx, catBase+"/v2/keys", "", "", 0); len(own) != 2 { + t.Fatalf("the fork's cut wrote %d keys of its own, want one data chunk and one manifest", len(own)) } } diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go index 686200308a..203edd33b4 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go @@ -290,8 +290,8 @@ func TestChunkRemote_ChunkLayerCaptureThenFreshHost(t *testing.T) { t.Fatalf("RemoteLSN %d after capture at %d", layer.RemoteLSN(), h) } puts, _, _ := b.counts() - if puts != 4 { // chunks 0, 1, 2 and 7 - t.Fatalf("capture stored %d needles; want 4", puts) + if puts != 5 { // chunks 0, 1, 2 and 7, plus their manifest segment + t.Fatalf("capture stored %d needles; want 4 data chunks plus one manifest", puts) } _ = src.Close() diff --git a/seaweed-block/core/frontend/chunkstore/manifest_test.go b/seaweed-block/core/frontend/chunkstore/manifest_test.go index 4c44f4f9dc..c78e6a9685 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -92,6 +93,9 @@ func TestManifest_ForkAfterParentSnapshotDelete(t *testing.T) { if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { t.Fatal(err) } + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 8d4b5c51a6..9b0322268c 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -152,6 +152,8 @@ type ProviderConfig struct { // cuts are published only by CaptureVolume, MakeVolumeRemoteDurable // (snapshot, detach) and the timer. Zero: unbounded. ChunkDirtyThreshold int + // ChunkUploadConcurrency bounds remote uploads; zero defaults to 8. + ChunkUploadConcurrency int } // DurableProvider is the production frontend.Provider implementation. diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 3d525aebd5..a01512f81e 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -259,13 +259,14 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h remote.setAttach(ctx) // the attach's calls also end with the caller's ctx defer remote.setAttach(nil) cfg := storage.ChunkLayerConfig{ - ChunkBlocks: p.cfg.ChunkBlocks, - Epoch: lin.epoch, - Holder: holder, - FreshFromHead: h.fresh, - ReadMissTimeout: p.cfg.ChunkReadMissTimeout, - Bitmap: storage.NewFileChunkBitmapStore(h.path + ".chunkbitmap"), - BarrierBound: p.cfg.ChunkDirtyThreshold, + ChunkBlocks: p.cfg.ChunkBlocks, + Epoch: lin.epoch, + Holder: holder, + FreshFromHead: h.fresh, + ReadMissTimeout: p.cfg.ChunkReadMissTimeout, + Bitmap: storage.NewFileChunkBitmapStore(h.path + ".chunkbitmap"), + BarrierBound: p.cfg.ChunkDirtyThreshold, + UploadConcurrency: p.cfg.ChunkUploadConcurrency, CaptureAllowed: func() error { cur := p.view.Projection() if !cur.Healthy || cur.VolumeID != volumeID || lin.volumeID != volumeID { From d2b9c5db375687bc33fdcd9b47da554b4de69b74 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:29:46 -0800 Subject: [PATCH 08/21] test: cover immutable segment reuse crash cuts and fail-closed GC --- .../core/frontend/chunkstore/chunk_remote.go | 12 +- .../frontend/chunkstore/chunk_remote_test.go | 2 +- seaweed-block/core/frontend/chunkstore/gc.go | 5 +- .../core/frontend/chunkstore/manifest.go | 66 ++++++++++- .../core/frontend/chunkstore/manifest_test.go | 111 ++++++++++++++++++ 5 files changed, 188 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 8f3b801a53..b4624e9665 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -425,11 +425,13 @@ func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) { if h.DetachedBy != nil { doc.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen} } - for idx, ref := range h.Chunks { - if ref.Key == "" { - return nil, fmt.Errorf("chunkstore: HEAD chunk %d has no key", idx) + if h.Segments == nil { + for idx, ref := range h.Chunks { + if ref.Key == "" { + return nil, fmt.Errorf("chunkstore: HEAD chunk %d has no key", idx) + } + doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} } - doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} } if h.Segments != nil { doc.Format = 2 @@ -494,7 +496,7 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) { return storage.ChunkHead{}, fmt.Errorf("chunkstore: HEAD %s: "+format, append([]any{p}, a...)...) } var doc headDoc - if err := json.Unmarshal(content, &doc); err != nil { + if err := decodeManifestJSON(content, &doc); err != nil { return fail("decode: %v", err) } if doc.Format != headFormat && doc.Format != 2 { diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go index 203edd33b4..61a6951c39 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go @@ -311,6 +311,6 @@ func TestChunkRemote_ChunkLayerCaptureThenFreshHost(t *testing.T) { } } if _, gets, _ := b.counts(); gets != 4 { // each published chunk fetched once - t.Fatalf("fresh host fetched %d needles; want 4", gets) + t.Fatalf("fresh host fetched %d needles; want 4 data chunks plus one manifest", gets) } } diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 5e44a840d6..5d524d0c13 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -152,7 +152,10 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e roots[path.Join(dir, name)] = true } - keys := make([]string, 0, len(head.Chunks)) + keys := make([]string, 0, len(head.Chunks)+len(head.Segments)) + for _, ref := range head.Segments { + keys = append(keys, ref.Key) + } for _, ref := range head.Chunks { keys = append(keys, ref.Key) } diff --git a/seaweed-block/core/frontend/chunkstore/manifest.go b/seaweed-block/core/frontend/chunkstore/manifest.go index a67e78d9f0..a069a2d888 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest.go +++ b/seaweed-block/core/frontend/chunkstore/manifest.go @@ -1,12 +1,14 @@ package chunkstore import ( + "bytes" "context" "crypto/rand" "crypto/sha256" "encoding/json" "errors" "fmt" + "io" "path" "reflect" "strings" @@ -51,6 +53,9 @@ func validateRoot(h storage.ChunkHead) error { } count += ref.Count } + if h.State == storage.ChunkHeadAborted && len(h.Segments) != 0 { + return errors.New("chunkstore: aborted HEAD contains segments") + } if count != h.ManifestChunkCount { return errors.New("chunkstore: manifest count mismatch") } @@ -152,7 +157,7 @@ func (r *ChunkRemote) resolveManifest(ctx context.Context, h storage.ChunkHead) return h, errors.New("chunkstore: segment hash/size mismatch") } var doc segmentDoc - if err := json.Unmarshal(body, &doc); err != nil { + if err := decodeManifestJSON(body, &doc); err != nil { return h, err } if doc.Format != 1 || doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count { @@ -168,3 +173,62 @@ func (r *ChunkRemote) resolveManifest(ctx context.Context, h storage.ChunkHead) } return h, nil } + +// Reject duplicate object keys instead of accepting a last-wins manifest. +func decodeManifestJSON(body []byte, out any) error { + if len(body) > maxManifestBytes { + return errors.New("chunkstore: manifest exceeds byte bound") + } + d := json.NewDecoder(bytes.NewReader(body)) + var value func(int) error + value = func(depth int) error { + if depth > 8 { + return errors.New("chunkstore: manifest nesting exceeds bound") + } + tok, err := d.Token() + if err != nil { + return err + } + delim, ok := tok.(json.Delim) + if !ok { + return nil + } + switch delim { + case '{': + keys := map[string]bool{} + for d.More() { + t, err := d.Token() + if err != nil { + return err + } + k, ok := t.(string) + if !ok || keys[k] { + return errors.New("chunkstore: duplicate manifest key") + } + keys[k] = true + if err := value(depth + 1); err != nil { + return err + } + } + _, err = d.Token() + return err + case '[': + for d.More() { + if err := value(depth + 1); err != nil { + return err + } + } + _, err = d.Token() + return err + default: + return errors.New("chunkstore: invalid manifest delimiter") + } + } + if err := value(0); err != nil { + return err + } + if _, err := d.Token(); err != io.EOF { + return errors.New("chunkstore: trailing manifest bytes") + } + return json.Unmarshal(body, out) +} diff --git a/seaweed-block/core/frontend/chunkstore/manifest_test.go b/seaweed-block/core/frontend/chunkstore/manifest_test.go index c78e6a9685..7f8362602f 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_test.go @@ -3,7 +3,9 @@ package chunkstore import ( "bytes" "context" + "crypto/sha256" "encoding/json" + "fmt" "path" "path/filepath" "testing" @@ -139,3 +141,112 @@ func TestManifest_GCReadsPublishedSegments(t *testing.T) { t.Fatalf("GC cannot trace published segment: %+v %v", out, err) } } + +func TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + ctx := context.Background() + r, h := publishSegmented(t, f, b) + // A second logical GiB uses a different immutable range; no local 1GiB + // allocation is needed to exercise remote manifest publication. + per := manifestSegmentBytes / h.ChunkBytes + key := "second-range" + data := chunkBytes(0x77) + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + h.Chunks[per] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + next, ids, err := r.PrepareManifest(ctx, h, h, h.ChunkBytes) + if err != nil { + t.Fatal(err) + } + if next.Segments[0] != h.Segments[0] { + t.Fatal("unchanged range rewritten") + } + // Simulate death after immutable upload, with no CAS or cleanup. + old, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if len(old.Chunks) != 2 || len(old.Segments) != 1 { + t.Fatal("unpublished segment changed old root") + } + intents, err := r.ListIntents(ctx) + if err != nil || len(intents) != len(ids) { + t.Fatalf("uploaded segment unprotected: %v", err) + } + for _, ref := range old.Chunks { + if _, err := r.Get(ctx, ref.Key); err != nil { + t.Fatal(err) + } + } + gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: old.Gen, Epoch: old.Epoch}, next) + if err != nil || gen != old.Gen+1 { + t.Fatalf("normal CAS semantics: %d %v", gen, err) + } +} + +func TestManifest_UnreadablePublishedSegmentRefusesWholeGC(t *testing.T) { + for _, apply := range []bool{false, true} { + t.Run(fmt.Sprint(apply), func(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, h := publishSegmented(t, f, b) + if err := r.Put(ctx, "unreachable", []byte("orphan")); err != nil { + t.Fatal(err) + } + if _, err := g.Run(ctx); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + var ref storage.ChunkSegment + for _, v := range h.Segments { + ref = v + break + } + dir, name, err := r.keyLocation(ref.Key) + if err != nil { + t.Fatal(err) + } + entry, err := f.LookupEntry(ctx, dir, name) + if err != nil { + t.Fatal(err) + } + b.mu.Lock() + b.data[string(entry.Extended[extFid])] = []byte("corrupted segment") + before := len(b.data) + b.mu.Unlock() + if _, err := g.run(ctx, apply); err == nil { + t.Fatal("unreadable published segment accepted") + } + b.mu.Lock() + after := len(b.data) + b.mu.Unlock() + if before != after { + t.Fatal("failed mark partially deleted data") + } + }) + } +} + +func TestManifest_CopyIntentProtectsChildrenWithoutHead(t *testing.T) { + f, b, _, g, now := gcFixture(t) + ctx := context.Background() + r, h := publishSegmented(t, f, b) + if _, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: h.Gen, Epoch: h.Epoch, Holder: "snapshot:v1/unpublished/attempt", Keys: headKeys(h), Segments: h.Segments, ChunkBytes: h.ChunkBytes}); err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN}); err != nil { + t.Fatal(err) + } + for i := 0; i < 3; i++ { + if out, err := g.Run(ctx); err != nil || out.Reclaimed != 0 { + t.Fatalf("copy intent lost transitive children: %+v %v", out, err) + } + *now = now.Add(2 * time.Hour) + } + for _, ref := range h.Chunks { + if _, err := r.Get(ctx, ref.Key); err != nil { + t.Fatal(err) + } + } +} From 6cf3f9d1b93785e77ccd846d56552b4c15b61171 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:30:53 -0800 Subject: [PATCH 09/21] test: pin upload caps cancellation and flat no-op upgrade lineage --- .../core/frontend/chunkstore/chunk_remote.go | 3 +- .../frontend/chunkstore/chunk_remote_test.go | 2 +- .../core/frontend/chunkstore/manifest_test.go | 40 +++++++++++++ .../storage/chunk_upload_parallel_test.go | 57 +++++++++++++++++++ 4 files changed, 100 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index b4624e9665..38d1e5e668 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -421,11 +421,12 @@ func (r *ChunkRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) { doc := headDoc{Format: headFormat, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, - Chunks: make(map[uint64]refDoc, len(h.Chunks)), State: h.State} + State: h.State} if h.DetachedBy != nil { doc.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen} } if h.Segments == nil { + doc.Chunks = make(map[uint64]refDoc, len(h.Chunks)) for idx, ref := range h.Chunks { if ref.Key == "" { return nil, fmt.Errorf("chunkstore: HEAD chunk %d has no key", idx) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go index 61a6951c39..5e545e0a0a 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go @@ -310,7 +310,7 @@ func TestChunkRemote_ChunkLayerCaptureThenFreshHost(t *testing.T) { t.Fatalf("fresh host block %d = %x...; want %x...", lba, got[:4], exp[:4]) } } - if _, gets, _ := b.counts(); gets != 4 { // each published chunk fetched once + if _, gets, _ := b.counts(); gets != 5 { // four data chunks and one manifest fetched once t.Fatalf("fresh host fetched %d needles; want 4 data chunks plus one manifest", gets) } } diff --git a/seaweed-block/core/frontend/chunkstore/manifest_test.go b/seaweed-block/core/frontend/chunkstore/manifest_test.go index 7f8362602f..c8ab0ec751 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_test.go @@ -250,3 +250,43 @@ func TestManifest_CopyIntentProtectsChildrenWithoutHead(t *testing.T) { } } } + +func TestManifest_NoopFlatUpgradeUsesOneNormalGeneration(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + old, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + p := filepath.Join(t.TempDir(), "store") + s, err := storage.CreateWALStore(p, 64, 4096) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if _, err = s.Recover(); err != nil { + t.Fatal(err) + } + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true, Bitmap: storage.NewFileChunkBitmapStore(p + ".bitmap")}) + if err != nil { + t.Fatal(err) + } + if _, err = l.Capture(ctx); err != nil { + t.Fatal(err) + } + h, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if h.Segments == nil || h.Gen != old.Gen+1 || h.Epoch != 1 || h.RemoteLSN != old.RemoteLSN { + t.Fatalf("upgrade changed normal-cut lineage: old=%+v new=%+v", old, h) + } + if _, err = l.Capture(ctx); err != nil { + t.Fatal(err) + } + again, err := r.GetHead(ctx) + if err != nil || again.Gen != h.Gen || again.Epoch != h.Epoch { + t.Fatalf("second no-op advanced lineage: %+v %v", again, err) + } +} diff --git a/seaweed-block/core/storage/chunk_upload_parallel_test.go b/seaweed-block/core/storage/chunk_upload_parallel_test.go index 8fd66c0e2d..c5b72a547b 100644 --- a/seaweed-block/core/storage/chunk_upload_parallel_test.go +++ b/seaweed-block/core/storage/chunk_upload_parallel_test.go @@ -2,6 +2,7 @@ package storage import ( "context" + "fmt" "testing" "time" ) @@ -36,3 +37,59 @@ func TestChunkUploads_DefaultOverlapsBeforeCAS(t *testing.T) { f.mu.Unlock() _ = w } + +func TestChunkUploads_ConfiguredBoundAndCancellation(t *testing.T) { + for _, limit := range []int{1, 2, 8} { + t.Run(fmt.Sprint(limit), func(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.FreshFromHead = true + cfg.UploadConcurrency = limit + l := mustAttach(t, s, f, cfg) + w := newWriteLog() + for i := 0; i < 8; i++ { + w.write(t, s, uint32(i*ctChunkBlocks), byte(i+1)) + } + gate := make(chan struct{}) + entered := make(chan string, 16) + f.mu.Lock() + f.putGate = gate + f.putEntered = entered + f.mu.Unlock() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { _, err := l.Cut(ctx); done <- err }() + for i := 0; i < limit; i++ { + select { + case <-entered: + case <-time.After(time.Second): + cancel() + <-done + t.Fatal("worker bound not reached") + } + } + select { + case <-entered: + cancel() + <-done + t.Fatal("upload cap exceeded") + case <-time.After(20 * time.Millisecond): + } + cancel() + select { + case err := <-done: + if err == nil { + t.Fatal("cancelled upload succeeded") + } + case <-time.After(time.Second): + t.Fatal("cancelled workers not joined") + } + if f.stats().cas != 0 { + t.Fatal("cancelled upload published root") + } + assertNoIntentsLeft(t, f) // joined abort; no publication can refer to its keys + }) + } +} From e469c5f57508f8f046d05f4b8dcd486c7f210bad Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:33:52 -0800 Subject: [PATCH 10/21] test: measure fsynced 64-chunk cuts and written 10GiB root copies --- .../core/frontend/chunkstore/manifest.go | 2 +- .../frontend/chunkstore/manifest_perf_test.go | 187 ++++++++++++++++++ 2 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/frontend/chunkstore/manifest_perf_test.go diff --git a/seaweed-block/core/frontend/chunkstore/manifest.go b/seaweed-block/core/frontend/chunkstore/manifest.go index a069a2d888..116af3d78b 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest.go +++ b/seaweed-block/core/frontend/chunkstore/manifest.go @@ -113,7 +113,7 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch if _, err := rand.Read(nonce); err != nil { return next, nil, err } - key := fmt.Sprintf("manifests/%x", nonce) + key := fmt.Sprintf("seg/%x", nonce) next.Segments[group] = storage.ChunkSegment{Key: qualifyManifestKey(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks)} uploads = append(uploads, upload{key, body}) } diff --git a/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go b/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go new file mode 100644 index 0000000000..1528806c8b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go @@ -0,0 +1,187 @@ +//go:build manifest_perf + +package chunkstore + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "fmt" + "os" + "path" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// File-backed proxy: every immutable object is written and fsynced. Metadata +// RPCs use the deterministic filer model; results exclude network/guest fsync. +type manifestFiles struct{ dir string } + +func (b manifestFiles) Put(ctx context.Context, data []byte) (string, error) { + if err := ctx.Err(); err != nil { + return "", err + } + f, err := os.CreateTemp(b.dir, "blob-") + if err != nil { + return "", err + } + if _, err = f.Write(data); err == nil { + err = f.Sync() + } + cerr := f.Close() + if err == nil { + err = cerr + } + return filepath.Base(f.Name()), err +} +func (b manifestFiles) Get(ctx context.Context, key string) ([]byte, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + return os.ReadFile(filepath.Join(b.dir, key)) +} + +func TestManifestPerf_64DirtyChunks(t *testing.T) { + for rep := 0; rep < 3; rep++ { + order := []int{1, 8} + if rep%2 == 1 { + order = []int{8, 1} + } + for _, parallel := range order { + dir := t.TempDir() + f := newFakeFiler() + b := manifestFiles{dir} + r, err := NewChunkRemote(f, b, "/chunks/v1") + if err != nil { + t.Fatal(err) + } + s, err := storage.CreateWALStore(filepath.Join(dir, "store"), 64*1024, 4096) + if err != nil { + t.Fatal(err) + } + if _, err = s.Recover(); err != nil { + t.Fatal(err) + } + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 1024, Epoch: 1, Holder: "h1", FreshFromHead: true, UploadConcurrency: parallel, Bitmap: storage.NewFileChunkBitmapStore(filepath.Join(dir, "bitmap"))}) + if err != nil { + t.Fatal(err) + } + for i := 0; i < 64; i++ { + if _, err = s.Write(uint32(i*1024), bytes.Repeat([]byte{byte(i + 1)}, 4096)); err != nil { + t.Fatal(err) + } + } + start := time.Now() + if err = s.Sync(); err != nil { + t.Fatal(err) + } + syncTime := time.Since(start) + start = time.Now() + if _, err = l.Capture(context.Background()); err != nil { + t.Fatal(err) + } + cutTime := time.Since(start) + t.Logf("PERF dirty64 rep=%d parallel=%d chunk_bytes=4194304 upload_bytes=268435456 sync_ms=%.3f cut_ms=%.3f", rep, parallel, float64(syncTime.Microseconds())/1000, float64(cutTime.Microseconds())/1000) + if err = s.Close(); err != nil { + t.Fatal(err) + } + } + } +} + +func TestManifestPerf_Written10GiBSnapshotFork(t *testing.T) { + ctx := context.Background() + f := newFakeFiler() + c := newCat(t, f) + b := manifestFiles{t.TempDir()} + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v1", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(ctx, "v1", Geometry{NumBlocks: 10 * 1024 * 1024 * 1024 / 4096, BlockSize: 4096, ChunkBlocks: 1024}); err != nil { + t.Fatal(err) + } + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + h, _ := r.GetHead(ctx) + next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} + keys := make([]string, 2560) + for i := range keys { + keys[i] = fmt.Sprintf("data/%d", i) + } + intent, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: h.Gen, Epoch: 1, Holder: "h1", Keys: keys}) + if err != nil { + t.Fatal(err) + } + data := bytes.Repeat([]byte{0xa5}, 4<<20) + start := time.Now() + for i, key := range keys { + binary.LittleEndian.PutUint64(data, uint64(i)) + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + next.Chunks[uint64(i)] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next) + if err != nil { + t.Fatal(err) + } + next.Gen = gen + if err = r.DeleteIntent(ctx, intent); err != nil { + t.Fatal(err) + } + t.Logf("PERF materialized_bytes=10737418240 chunks=2560 upload_ms=%.3f", float64(time.Since(start).Microseconds())/1000) + for _, format := range []string{"flat", "segmented"} { + if format == "segmented" { + prepared, ids, err := r.PrepareManifest(ctx, next, next, 4<<20) + if err != nil { + t.Fatal(err) + } + gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: next.Gen, Epoch: next.Epoch}, prepared) + if err != nil { + t.Fatal(err) + } + prepared.Gen = gen + next = prepared + for _, id := range ids { + if err = r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + } + entry, err := headEntry(next) + if err != nil { + t.Fatal(err) + } + segmentBytes := 0 + for _, ref := range next.Segments { + body, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + segmentBytes += len(body) + } + for rep := 0; rep < 3; rep++ { + name := fmt.Sprintf("%s-%d", format, rep) + start := time.Now() + snap, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: name}, next) + if err != nil { + t.Fatal(err) + } + snapTime := time.Since(start) + target := "fork-" + name + if err = f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: target, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + start = time.Now() + if _, err = c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: name, Target: target, RequestID: target}); err != nil { + t.Fatal(err) + } + forkTime := time.Since(start) + t.Logf("PERF written10GiB format=%s rep=%d head_bytes=%d total_segment_bytes=%d snapshot_entry_bytes=%d snapshot_ms=%.3f fork_ms=%.3f", format, rep, len(entry.Content), segmentBytes, snap.ManifestBytes, float64(snapTime.Microseconds())/1000, float64(forkTime.Microseconds())/1000) + } + } +} From 4479bd4361d0dd4231fbf555f682ec6433ce7233 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:35:12 -0800 Subject: [PATCH 11/21] test: trace immutable segments through real blockmaster and filer GC --- .../cmd/sw-block/chunk_gc_integration_test.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go b/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go index 40fe200542..92d2e90d13 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go +++ b/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go @@ -102,7 +102,24 @@ func TestIntegration_OpsChunkGC_RealMasterAndStore(t *testing.T) { h.Holder = "holder-a" h.RemoteLSN = 1 h.Chunks = map[uint64]storage.ChunkRef{0: {Key: "live", SHA256: sha256.Sum256(data)}} + flat := h + segmented, segmentIntents, err := remote.PrepareManifest(ctx, flat, h, 8*4096) + if err != nil { + t.Fatal(err) + } + h = segmented h.Gen, err = remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: 0}, h) + if err == nil { + for _, id := range segmentIntents { + if err = remote.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + } + if h.Segments == nil || len(h.Segments) != 1 { + t.Fatal("real-service acceptance requires a segmented root") + } + if err != nil { t.Fatal(err) } From 806da162bb1addda0afa4d7fc36dea1ca107ae02 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:36:50 -0800 Subject: [PATCH 12/21] test: preserve manifest preparation through the production provider --- .../durable/provider_manifest_test.go | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/provider_manifest_test.go diff --git a/seaweed-block/core/frontend/durable/provider_manifest_test.go b/seaweed-block/core/frontend/durable/provider_manifest_test.go new file mode 100644 index 0000000000..c68b88191d --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_manifest_test.go @@ -0,0 +1,33 @@ +package durable_test + +import ( + "context" + "sync/atomic" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type manifestAwareRemote struct { + *storage.MemChunkRemote + prepared atomic.Int32 +} + +func (r *manifestAwareRemote) PrepareManifest(ctx context.Context, base, next storage.ChunkHead, chunkBytes uint64) (storage.ChunkHead, []string, error) { + r.prepared.Add(1) + return next, nil, ctx.Err() +} +func TestWALStoreChunk_ProviderPreservesManifestCapability(t *testing.T) { + r := &manifestAwareRemote{MemChunkRemote: storage.NewMemChunkRemote()} + p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + s := openRecovered(t, p) + if _, err := s.Write(0, block(0x65)); err != nil { + t.Fatal(err) + } + if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + if r.prepared.Load() != 1 { + t.Fatalf("provider erased remote manifest capability: preparations=%d", r.prepared.Load()) + } +} From 24cad2147456fd805d658913700df6be9ae92189 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:37:33 -0800 Subject: [PATCH 13/21] fix: retain manifest capability and exact root identity through provider cuts --- .../cmd/blockvolume/chunk_remote_test.go | 8 ++++--- .../frontend/chunkstore/manifest_perf_test.go | 2 +- .../core/frontend/durable/provider_chunk.go | 23 ++++++++++++++++--- seaweed-block/core/storage/chunk_layer.go | 9 ++++++++ 4 files changed, 35 insertions(+), 7 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index 8fe091a483..e2224ccf8d 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -54,9 +54,11 @@ func TestWALStoreChunkFlags(t *testing.T) { "--chunk-control-endpoint"), "control endpoint without a status listener": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-control-endpoint"), - "negative threshold": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=-1"), - "threshold on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-dirty-threshold=8"), - "interval on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-capture-interval=5s"), + "zero upload concurrency": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-upload-concurrency=0"), + "too many uploads": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-upload-concurrency=65"), + "negative threshold": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=-1"), + "threshold on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-dirty-threshold=8"), + "interval on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-capture-interval=5s"), } for name, args := range refused { if _, err := parseFlags(args); err == nil { diff --git a/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go b/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go index 1528806c8b..efa205cb31 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go @@ -77,7 +77,7 @@ func TestManifestPerf_64DirtyChunks(t *testing.T) { } } start := time.Now() - if err = s.Sync(); err != nil { + if _, err = s.Sync(); err != nil { t.Fatal(err) } syncTime := time.Since(start) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index a01512f81e..6fe2779609 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -255,9 +255,13 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h if holder == "" { holder = proj.ReplicaID } - remote := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx} - remote.setAttach(ctx) // the attach's calls also end with the caller's ctx - defer remote.setAttach(nil) + bound := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx} + bound.setAttach(ctx) // the attach's calls also end with the caller's ctx + defer bound.setAttach(nil) + var remote storage.ChunkRemote = bound + if builder, ok := inner.(storage.ChunkManifestBuilder); ok { + remote = &manifestBoundRemote{closeBoundRemote: bound, builder: builder} + } cfg := storage.ChunkLayerConfig{ ChunkBlocks: p.cfg.ChunkBlocks, Epoch: lin.epoch, @@ -699,3 +703,16 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st } return r, h.storage.NextLSN() - 1, nil } + +// Preserve the optional manifest capability only when the inner remote has it; +// legacy in-memory/flat remotes keep their existing no-op cut behavior. +type manifestBoundRemote struct { + *closeBoundRemote + builder storage.ChunkManifestBuilder +} + +func (r *manifestBoundRemote) PrepareManifest(ctx context.Context, base, next storage.ChunkHead, chunkBytes uint64) (storage.ChunkHead, []string, error) { + c, end := r.bind(ctx) + defer end() + return r.builder.PrepareManifest(c, base, next, chunkBytes) +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index f005af7267..4c10814263 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1034,6 +1034,15 @@ func (l *chunkLayerImpl) supersededBy(cur chunkHead) bool { } func sameProposal(cur, next chunkHead) bool { + if (cur.Segments == nil) != (next.Segments == nil) || cur.ChunkBytes != next.ChunkBytes || cur.ManifestChunkCount != next.ManifestChunkCount || len(cur.Segments) != len(next.Segments) { + return false + } + for k, v := range next.Segments { + if cur.Segments[k] != v { + return false + } + } + if cur.Epoch != next.Epoch || cur.Holder != next.Holder || cur.RemoteLSN != next.RemoteLSN || len(cur.Chunks) != len(next.Chunks) { return false } From ddae3ac15ed5346b71fa954adde34bcc8645cc5b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:39:35 -0800 Subject: [PATCH 14/21] test: pin failure joins range reuse and document manifest compatibility --- .../core/frontend/chunkstore/chunk_remote.go | 3 + .../core/frontend/chunkstore/manifest_test.go | 21 +++++++ .../storage/chunk_upload_parallel_test.go | 63 +++++++++++++++++++ seaweed-block/docs/chunk-manifests.md | 58 +++++++++++++++++ 4 files changed, 145 insertions(+) create mode 100644 seaweed-block/docs/chunk-manifests.md diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 38d1e5e668..25d16aa34b 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -435,6 +435,9 @@ func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) { } } if h.Segments != nil { + if err := validateRoot(h); err != nil { + return nil, err + } doc.Format = 2 doc.Chunks = nil doc.Segments = h.Segments diff --git a/seaweed-block/core/frontend/chunkstore/manifest_test.go b/seaweed-block/core/frontend/chunkstore/manifest_test.go index c8ab0ec751..58d39ea59c 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_test.go @@ -183,6 +183,27 @@ func TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot(t *testing.T) { if err != nil || gen != old.Gen+1 { t.Fatalf("normal CAS semantics: %d %v", gen, err) } + + published, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + changed := published + changed.Chunks = make(map[uint64]storage.ChunkRef, len(published.Chunks)) + for idx, ref := range published.Chunks { + changed.Chunks[idx] = ref + } + if err = r.Put(ctx, "changed-range-zero", data); err != nil { + t.Fatal(err) + } + changed.Chunks[0] = storage.ChunkRef{Key: "changed-range-zero", SHA256: sha256.Sum256(data)} + rewritten, _, err := r.PrepareManifest(ctx, published, changed, published.ChunkBytes) + if err != nil { + t.Fatal(err) + } + if rewritten.Segments[0] == published.Segments[0] || rewritten.Segments[1] != published.Segments[1] { + t.Fatal("cut must rewrite only the changed range") + } } func TestManifest_UnreadablePublishedSegmentRefusesWholeGC(t *testing.T) { diff --git a/seaweed-block/core/storage/chunk_upload_parallel_test.go b/seaweed-block/core/storage/chunk_upload_parallel_test.go index c5b72a547b..f15df41ec5 100644 --- a/seaweed-block/core/storage/chunk_upload_parallel_test.go +++ b/seaweed-block/core/storage/chunk_upload_parallel_test.go @@ -2,7 +2,9 @@ package storage import ( "context" + "errors" "fmt" + "sync/atomic" "testing" "time" ) @@ -93,3 +95,64 @@ func TestChunkUploads_ConfiguredBoundAndCancellation(t *testing.T) { }) } } + +// A remote may ignore cancellation. Its owned upload must settle before +// failure cleanup can remove the intent; cancellation alone is not a join. +type unjoinedUploadRemote struct { + *fakeChunkRemote + calls atomic.Int32 + second chan struct{} + failed chan struct{} + release chan struct{} +} + +func (r *unjoinedUploadRemote) Put(ctx context.Context, key string, data []byte) error { + if r.calls.Add(1) == 1 { + <-r.second + close(r.failed) + return errFakeRemoteDown + } + close(r.second) + <-r.release + return r.fakeChunkRemote.Put(context.Background(), key, data) +} +func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &unjoinedUploadRemote{fakeChunkRemote: f, second: make(chan struct{}), failed: make(chan struct{}), release: make(chan struct{})} + cfg := ctConfig(1) + cfg.FreshFromHead = true + cfg.UploadConcurrency = 2 + l := mustAttach(t, s, r, cfg) + w := newWriteLog() + w.write(t, s, 0, 0x21) + w.write(t, s, ctChunkBlocks, 0x22) + done := make(chan error, 1) + go func() { _, err := l.Cut(context.Background()); done <- err }() + select { + case <-r.failed: + case <-time.After(time.Second): + close(r.release) + <-done + t.Fatal("uploads did not overlap") + } + select { + case err := <-done: + close(r.release) + t.Fatalf("returned with owned upload still active: %v", err) + case <-time.After(20 * time.Millisecond): + } + if len(liveIntents(t, f)) == 0 { + close(r.release) + <-done + t.Fatal("intent removed before join") + } + close(r.release) + if err := <-done; !errors.Is(err, errFakeRemoteDown) { + t.Fatalf("lost upload failure: %v", err) + } + if f.stats().cas != 0 { + t.Fatal("failed batch published") + } + assertNoIntentsLeft(t, f) +} diff --git a/seaweed-block/docs/chunk-manifests.md b/seaweed-block/docs/chunk-manifests.md new file mode 100644 index 0000000000..311768c7bc --- /dev/null +++ b/seaweed-block/docs/chunk-manifests.md @@ -0,0 +1,58 @@ +# Chunk upload and manifest format + +`blockvolume --durable-impl=walstore-chunk` uploads dirty chunks in parallel. +`--chunk-upload-concurrency` defaults to 8 and accepts 1 through 64; 1 selects +serial upload. The setting applies to both capture and pre-copy. Segment size +is a format constant: each segment covers one logical GiB. + +HEAD format 1 remains readable. A volume's next cut upgrades it to format 2 in +one ordinary fenced root CAS (including an otherwise no-op cut); generation +advances once, with the ordinary epoch/holder/LSN checks. Old binaries cannot +read format 2: deploy format-aware readers and GC before publishing new cuts. +Downgrading a volume after its first format-2 cut is unsupported. + +A format-2 HEAD contains lineage, chunk geometry/count, and immutable segment +references, instead of a flat chunk map. Each segment contains a sparse map of +chunk indices and SHA-256 references; missing indices mean ZERO. Unchanged +ranges retain their exact segment keys. Data and segment keys are protected by +cut intents before upload. A root is published only after its objects exist; +an unknown root CAS retains the intents until reconciliation. + +Segment keys are owner-qualified (`@/seg/`); a segment's chunk +references retain their source namespace. Snapshot/fork copies only the root. +The fork's root alone keeps inherited segments/data live after deleting its +parent snapshot. There is no separate segment claim or segment publication +tombstone. Snapshot attempt tombstones and never-reused volume ids are +unchanged. Reclaimed immutable key bindings keep the existing GC marker that +prevents rebinding an old key. + +GC traces HEADs, snapshot attempts and copy intents through their verified +segments to data. It also marks segment objects themselves. A published +segment that cannot be read or verified refuses the entire mark, in dry-run +and apply; no chunks are deleted after an incomplete mark. Capture intents +protect prospective keys directly, including not-yet-uploaded segments. The +existing higher-epoch plus TTL rule, copy-target tombstone settlement, two +marks separated by grace, upload age floor and unbound-needle retention remain. +A collector adapter without blob reads can collect flat roots but refuses a +segmented root rather than omitting its children. + +## Locks and cancellation + +The existing cut/publication serialization is unchanged. Capture buffers and +staged versions are selected as before; upload workers acquire no WAL, +publication, shard or capture-state lock. Only the caller updates maps and +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. + +## Reproducible proxy measurements + +`go test -tags=manifest_perf ./core/frontend/chunkstore -run '^TestManifestPerf_' -count=1 -timeout=600s -v` + +This materializes and fsyncs immutable files, including all 10 GiB of the large +volume. Metadata uses the deterministic filer model. It compares 64 dirty +4 MiB chunks at concurrency 1/8 in alternating order (three samples each), and +flat versus segmented snapshot/fork operations (three samples each). Reported +root bytes exclude segment bytes, which are reported separately. It excludes +network latency, the block frontend, guest fsync and power-loss behavior. From 701a304257cccd2781ec6f4300cbeaa1788173d9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:55:13 -0800 Subject: [PATCH 15/21] test: refuse mixed roots and cover segmented accounting and clean moves --- .../chunkstore/manifest_review_test.go | 124 ++++++++++++++++++ .../master/workspace_move_integration_test.go | 9 ++ 2 files changed, 133 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/manifest_review_test.go diff --git a/seaweed-block/core/frontend/chunkstore/manifest_review_test.go b/seaweed-block/core/frontend/chunkstore/manifest_review_test.go new file mode 100644 index 0000000000..ea69f1eb64 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest_review_test.go @@ -0,0 +1,124 @@ +package chunkstore + +import ( + "context" + "encoding/json" + "path" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type manifestFilerBlobs struct { + Filer + Blobs +} + +func TestManifest_MixedRepresentationRefusesReadAndWholeGC(t *testing.T) { + for _, format := range []int{1, 2} { + t.Run(string(rune('0'+format)), func(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := publishSegmented(t, f, b) + if err := r.Put(ctx, "eligible-orphan", []byte("keep on mark error")); err != nil { + t.Fatal(err) + } + if _, err := g.Run(ctx); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) + if err != nil { + t.Fatal(err) + } + var doc map[string]json.RawMessage + if err = json.Unmarshal(e.Content, &doc); err != nil { + t.Fatal(err) + } + if format == 1 { + doc["format"] = json.RawMessage("1") + } else { + doc["chunks"] = json.RawMessage("{}") + } + e.Content, err = json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + if h, err := r.GetHead(ctx); err == nil { + t.Errorf("mixed root returned readable image (possibly zeros): %+v", h) + } + if h, _, err := c.ReadHead(ctx, "v1"); err == nil { + t.Errorf("catalog accepted mixed root: %+v", h) + } + _, _, before := b.counts() + for _, apply := range []bool{false, true} { + if _, err := g.run(ctx, apply); err == nil { + t.Errorf("mixed root accepted by GC apply=%v", apply) + } + } + _, _, after := b.counts() + if before != after { + t.Fatal("failed mark deleted objects") + } + }) + } +} + +func TestManifest_UsageCountsOwnedClippedChunksAndForkHolders(t *testing.T) { + ctx := context.Background() + f := newFakeFiler() + b := gcBlobs{newFakeBlobs()} + c, err := NewCatalog(manifestFilerBlobs{f, b}, catBase) + if err != nil { + t.Fatal(err) + } + for _, vol := range []string{"v1", "v2"} { + if err = f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + } + if _, err = c.EnsureVolume(ctx, "v1", Geometry{NumBlocks: 10, BlockSize: 4096, ChunkBlocks: 8}); err != nil { + t.Fatal(err) + } + r, h := publishSegmented(t, f, b) + if _, err = c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s", RequestID: "snapshot"}, h); err != nil { + t.Fatal(err) + } + u, err := c.Usage(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if u.LiveChunks != 2 || u.LiveBytes != 40960 || len(u.Snapshots) != 1 || u.Snapshots[0].Chunks != 2 || u.Snapshots[0].ExclusiveBytes != 0 { + t.Fatalf("segmented clipped usage: %+v", u) + } + if _, err = c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + if _, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN}); err != nil { + t.Fatal(err) + } + u, err = c.Usage(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if u.LiveChunks != 0 || u.Snapshots[0].Chunks != 2 || u.Snapshots[0].ExclusiveBytes != 0 { + t.Fatalf("foreign fork owner omitted: %+v", u) + } + fork, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) + fh, err := fork.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if _, err = fork.CASHead(ctx, storage.ChunkHeadVersion{Gen: fh.Gen, Epoch: fh.Epoch}, storage.ChunkHead{RemoteLSN: fh.RemoteLSN}); err != nil { + t.Fatal(err) + } + u, err = c.Usage(ctx, "v1") + if err != nil || u.Snapshots[0].ExclusiveBytes != 40960 { + t.Fatalf("snapshot exclusivity must use clipped owner bytes: %+v %v", u, err) + } +} diff --git a/seaweed-block/core/host/master/workspace_move_integration_test.go b/seaweed-block/core/host/master/workspace_move_integration_test.go index 6e23aa9232..b6d1dfa5dd 100644 --- a/seaweed-block/core/host/master/workspace_move_integration_test.go +++ b/seaweed-block/core/host/master/workspace_move_integration_test.go @@ -5,6 +5,7 @@ package master import ( "bytes" "context" + "encoding/json" "errors" "sync/atomic" "testing" @@ -142,6 +143,14 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) { t.Fatal(err) } t.Logf("producer HEAD persisted by filer: %s", stored.Content) + var root struct { + Format int `json:"format"` + Segments map[string]json.RawMessage `json:"segments"` + } + if err = json.Unmarshal(stored.Content, &root); err != nil || root.Format != 2 || len(root.Segments) == 0 { + t.Fatalf("CLEAN move must exercise upgraded segmented root: %s %v", stored.Content, err) + } + if _, err = backend.Write(ctx, 0, want); err == nil { t.Fatal("W2 detach left frontend writable") } From ae907d6ea670fb69b29ceb6648be17770e50f085 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:56:14 -0800 Subject: [PATCH 16/21] fix: reject mixed manifests and share segmented roots with master and usage --- .../core/frontend/chunkstore/catalog.go | 8 +-- .../core/frontend/chunkstore/chunk_remote.go | 22 ++++++++ .../core/frontend/chunkstore/usage.go | 54 ++++++++++++++++++- .../core/host/master/workspace_head.go | 6 ++- 4 files changed, 84 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index f1fe223022..a94aa1f2ae 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -281,8 +281,9 @@ type ForkResult struct { // Catalog reads and writes the control-plane entries under one chunk base. type Catalog struct { - f Filer - base string + blobs Blobs // optional immutable-object reader; SWFS supplies it directly + f Filer + base string // OpDeadline bounds a snapshot or fork (DefaultOpDeadline when zero). OpDeadline time.Duration now func() time.Time @@ -300,7 +301,8 @@ func NewCatalog(f Filer, base string) (*Catalog, error) { if !path.IsAbs(base) || path.Clean(base) != base || base == "/" { return nil, fmt.Errorf("chunkstore: chunk base %q must be a clean absolute directory other than /", base) } - return &Catalog{f: f, base: base, now: time.Now}, nil + blobs, _ := f.(Blobs) + return &Catalog{f: f, blobs: blobs, base: base, now: time.Now}, nil } // SetClock replaces the catalog's clock (tests). diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 25d16aa34b..47729e8eb6 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -503,6 +503,22 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) { if err := decodeManifestJSON(content, &doc); err != nil { return fail("decode: %v", err) } + var fields map[string]json.RawMessage + if err := json.Unmarshal(content, &fields); err != nil { + return fail("decode representation: %v", err) + } + if doc.Format == 1 { + for _, name := range []string{"segments", "chunk_bytes", "chunk_count"} { + if _, present := fields[name]; present { + return fail("flat HEAD contains segment field %s", name) + } + } + } + if doc.Format == 2 { + if _, present := fields["chunks"]; present { + return fail("segmented HEAD contains flat chunks field") + } + } if doc.Format != headFormat && doc.Format != 2 { return fail("format %d not supported (want %d)", doc.Format, headFormat) } @@ -565,3 +581,9 @@ func NewSWFSChunkRemote(c *SWFS, root string) (*ChunkRemote, error) { } var _ storage.ChunkRemote = (*ChunkRemote)(nil) + +// DecodeHeadDocument validates a persisted flat or segmented root without +// fetching data. Control-plane readers share the same representation checks. +func DecodeHeadDocument(name string, body []byte) (storage.ChunkHead, error) { + return decodeHeadDoc(name, body) +} diff --git a/seaweed-block/core/frontend/chunkstore/usage.go b/seaweed-block/core/frontend/chunkstore/usage.go index 05ec785f61..8f139aa4d1 100644 --- a/seaweed-block/core/frontend/chunkstore/usage.go +++ b/seaweed-block/core/frontend/chunkstore/usage.go @@ -12,7 +12,8 @@ import ( ) // Space accounting (claude05's rulings, 2026-11-15 22:53Z). Everything is -// computed from manifests and filer listings; no chunk data is read. +// computed from manifests and filer listings; segment objects are verified, +// but data chunks are not read. // // A chunk's bytes are ChunkBlocks x BlockSize, the last chunk clipped to // NumBlocks (ChunkRef carries no size). @@ -99,6 +100,16 @@ func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) { return VolumeUsage{}, err } + head, err = c.usageHead(ctx, vol, head) + if err != nil { + return VolumeUsage{}, err + } + for i := range snaps { + snaps[i].head, err = c.usageHead(ctx, vol, snaps[i].head) + if err != nil { + return VolumeUsage{}, err + } + } // holders counts, per chunk identity (owner volume + key), how many // HEADs and live snapshots of any volume reference it; size is each // identity's byte size as this volume's geometry indexes it. @@ -138,6 +149,10 @@ func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) { return VolumeUsage{}, err } if has { + oh, err = c.usageHead(ctx, other, oh) + if err != nil { + return VolumeUsage{}, err + } addHolder(other, oh, false) } osnaps, err := c.allSnapshots(ctx, other) @@ -145,7 +160,11 @@ func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) { return VolumeUsage{}, err } for _, s := range osnaps { - addHolder(other, s.Head(), false) + otherHead, err := c.usageHead(ctx, other, s.Head()) + if err != nil { + return VolumeUsage{}, err + } + addHolder(other, otherHead, false) } } for _, s := range snaps { @@ -218,3 +237,34 @@ func chunkIdentity(vol, key string) string { } return vol + "\x00" + key } + +func (c *Catalog) usageHead(ctx context.Context, vol string, h storage.ChunkHead) (storage.ChunkHead, error) { + if h.Segments == nil { + return h, nil + } + var blobs Blobs = c.blobs + if blobs == nil { + return h, errors.New("chunkstore: usage segment reader unavailable") + } + r, err := NewChunkRemote(c.f, blobs, path.Join(c.base, vol)) + if err != nil { + return h, err + } + resolved, err := r.resolveManifest(ctx, h) + if err != nil { + return h, err + } + v, ok, err := c.ReadVolume(ctx, vol) + if err != nil { + return h, err + } + if !ok || h.ChunkBytes != uint64(v.Geometry.ChunkBlocks)*uint64(v.Geometry.BlockSize) { + return h, errors.New("chunkstore: usage manifest/volume geometry mismatch") + } + for idx := range resolved.Chunks { + if idx >= (v.Geometry.NumBlocks+uint64(v.Geometry.ChunkBlocks)-1)/uint64(v.Geometry.ChunkBlocks) { + return h, errors.New("chunkstore: usage chunk outside volume") + } + } + return resolved, nil +} diff --git a/seaweed-block/core/host/master/workspace_head.go b/seaweed-block/core/host/master/workspace_head.go index bb81273e76..ef51030272 100644 --- a/seaweed-block/core/host/master/workspace_head.go +++ b/seaweed-block/core/host/master/workspace_head.go @@ -11,6 +11,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" ) // NewWorkspaceHEADReader reads inline HEAD content from the configured filer @@ -63,7 +64,10 @@ func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authori if err := json.Unmarshal(raw, &doc); err != nil { return authority.WorkspaceHead{}, err } - if doc.Format != 1 || doc.Gen == 0 || doc.Epoch == 0 || doc.Holder == "" || doc.LegacyDetached != nil || (doc.State != "" && doc.State != "active" && doc.State != "detached") { + if _, err := chunkstore.DecodeHeadDocument("workspace/"+volume, raw); err != nil { + return authority.WorkspaceHead{}, err + } + if (doc.Format != 1 && doc.Format != 2) || doc.Gen == 0 || doc.Epoch == 0 || doc.Holder == "" || doc.LegacyDetached != nil || (doc.State != "" && doc.State != "active" && doc.State != "detached") { return authority.WorkspaceHead{}, fmt.Errorf("invalid HEAD identity/state") } // Missing state is the legacy active representation. Only a final-cut From 0ff7a4b4b7511f606b92e1f653723e966c76ead8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:56:58 -0800 Subject: [PATCH 17/21] fix: account immutable manifest objects at their exact stored size --- .../core/frontend/chunkstore/chunk_remote.go | 8 ++++++++ seaweed-block/core/frontend/chunkstore/manifest.go | 2 +- .../core/frontend/chunkstore/manifest_review_test.go | 11 +++++++++++ seaweed-block/core/frontend/chunkstore/usage.go | 12 ++++++++++++ 4 files changed, 32 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 47729e8eb6..83b5170a7e 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -146,6 +146,10 @@ func (r *ChunkRemote) keyLocation(key string) (dir, name string, err error) { // create. A key that is already bound fails with storage.ErrChunkKeyExists // and its bytes are untouched. func (r *ChunkRemote) Put(ctx context.Context, key string, data []byte) error { + return r.putObject(ctx, key, data, "") +} + +func (r *ChunkRemote) putObject(ctx context.Context, key string, data []byte, object string) error { if err := storage.ValidChunkKey(key); err != nil { return fmt.Errorf("%w: %v", ErrInvalidKey, err) } @@ -172,6 +176,10 @@ func (r *ChunkRemote) Put(ctx context.Context, key string, data []byte) error { Attributes: &filerpb.FuseAttributes{Mtime: now, Crtime: now, FileMode: 0o644}, Extended: map[string][]byte{extKind: []byte(kindChunkKey), extFid: []byte(fid)}, } + if object == "segment" { + e.Extended["swb.object"] = []byte("segment") + e.Attributes.FileSize = uint64(len(data)) + } if err := r.f.CreateEntry(ctx, r.keyDir(), e, true); err != nil { if errors.Is(err, ErrExists) { return fmt.Errorf("%w: %s", storage.ErrChunkKeyExists, key) diff --git a/seaweed-block/core/frontend/chunkstore/manifest.go b/seaweed-block/core/frontend/chunkstore/manifest.go index 116af3d78b..01781b4b06 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest.go +++ b/seaweed-block/core/frontend/chunkstore/manifest.go @@ -133,7 +133,7 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch } ids := []string{id} for _, u := range uploads { - if err := r.Put(ctx, u.key, u.data); err != nil { + if err := r.putObject(ctx, u.key, u.data, "segment"); err != nil { return next, ids, err } } diff --git a/seaweed-block/core/frontend/chunkstore/manifest_review_test.go b/seaweed-block/core/frontend/chunkstore/manifest_review_test.go index ea69f1eb64..7aa12f6807 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_review_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_review_test.go @@ -96,6 +96,17 @@ func TestManifest_UsageCountsOwnedClippedChunksAndForkHolders(t *testing.T) { if u.LiveChunks != 2 || u.LiveBytes != 40960 || len(u.Snapshots) != 1 || u.Snapshots[0].Chunks != 2 || u.Snapshots[0].ExclusiveBytes != 0 { t.Fatalf("segmented clipped usage: %+v", u) } + segmentBytes := uint64(0) + for _, ref := range h.Segments { + body, e := r.Get(ctx, ref.Key) + if e != nil { + t.Fatal(e) + } + segmentBytes += uint64(len(body)) + } + if u.ManifestBindings != 1 || u.ManifestBytes != segmentBytes || u.StoredBytes != 40960+segmentBytes || u.StoredUpperBound { + t.Fatalf("manifest bytes must not be charged as a full data chunk: %+v", u) + } if _, err = c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s", Target: "v2", RequestID: "fork"}); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/chunkstore/usage.go b/seaweed-block/core/frontend/chunkstore/usage.go index 8f139aa4d1..b16d94903e 100644 --- a/seaweed-block/core/frontend/chunkstore/usage.go +++ b/seaweed-block/core/frontend/chunkstore/usage.go @@ -53,6 +53,8 @@ type VolumeUsage struct { LiveChunks int `json:"liveChunks"` LiveBytes uint64 `json:"liveBytes"` Snapshots []SnapshotUsage `json:"snapshots"` + ManifestBindings int `json:"manifestBindings"` + ManifestBytes uint64 `json:"manifestBytes"` StoredBindings int `json:"storedBindings"` StoredBytes uint64 `json:"storedBytes"` StoredUpperBound bool `json:"storedUpperBound"` @@ -213,6 +215,16 @@ func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) { continue } u.StoredBindings++ + if string(e.Extended["swb.object"]) == "segment" { + if e.Attributes == nil || e.Attributes.FileSize == 0 || e.Attributes.FileSize > maxManifestBytes { + return VolumeUsage{}, errors.New("chunkstore: invalid manifest binding size") + } + u.ManifestBindings++ + u.ManifestBytes += e.Attributes.FileSize + u.StoredBytes += e.Attributes.FileSize + continue + } + if n, ok := size[chunkIdentity(vol, key)]; ok { u.StoredBytes += n } else { From 6c740a1466f986ff4855010f84c22c74481f7865 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:59:22 -0800 Subject: [PATCH 18/21] test: reject case-folded mixed manifest field aliases --- .../frontend/chunkstore/manifest_review_test.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/manifest_review_test.go b/seaweed-block/core/frontend/chunkstore/manifest_review_test.go index 7aa12f6807..66de7277da 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_review_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_review_test.go @@ -133,3 +133,18 @@ func TestManifest_UsageCountsOwnedClippedChunksAndForkHolders(t *testing.T) { t.Fatalf("snapshot exclusivity must use clipped owner bytes: %+v %v", u, err) } } + +func TestManifest_RejectsFieldAliases(t *testing.T) { + for _, field := range []string{`"segments":null`, `"Segments":null`, `"CHUNK_BYTES":0`, `"chunk_count":0`} { + body := []byte(`{"format":1,"gen":1,"epoch":1,"holder":"h","chunks":{},` + field + `}`) + if _, err := DecodeHeadDocument("mixed", body); err == nil { + t.Errorf("format1 accepted residual field %s", field) + } + } + for _, field := range []string{`"chunks":{}`, `"Chunks":null`} { + body := []byte(`{"format":2,"gen":1,"epoch":1,"holder":"h","chunk_bytes":32768,"chunk_count":0,"segments":{},` + field + `}`) + if _, err := DecodeHeadDocument("mixed", body); err == nil { + t.Errorf("format2 accepted residual field %s", field) + } + } +} From 1dace522c233c420d8aa726f451ecf6ebefcb6b8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 18:59:40 -0800 Subject: [PATCH 19/21] fix: reject every case-insensitive mixed representation field --- .../core/frontend/chunkstore/chunk_remote.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 83b5170a7e..48c67a869f 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -515,15 +515,14 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) { if err := json.Unmarshal(content, &fields); err != nil { return fail("decode representation: %v", err) } - if doc.Format == 1 { - for _, name := range []string{"segments", "chunk_bytes", "chunk_count"} { - if _, present := fields[name]; present { - return fail("flat HEAD contains segment field %s", name) - } + for name := range fields { + // encoding/json also matches tagged names case-insensitively; reject + // every such alias rather than let it bypass representation checks. + field := strings.ToLower(name) + if doc.Format == 1 && (field == "segments" || field == "chunk_bytes" || field == "chunk_count") { + return fail("flat HEAD contains segment field %s", name) } - } - if doc.Format == 2 { - if _, present := fields["chunks"]; present { + if doc.Format == 2 && field == "chunks" { return fail("segmented HEAD contains flat chunks field") } } From e2c69c9686fc3d0b835bb6d23622e2135bae793f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 19:10:57 -0800 Subject: [PATCH 20/21] test: reject Unicode folded fields and corrupted-discriminator GC bypass --- .../chunkstore/manifest_review_test.go | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/manifest_review_test.go b/seaweed-block/core/frontend/chunkstore/manifest_review_test.go index 66de7277da..a107b81bfb 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_review_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_review_test.go @@ -4,8 +4,10 @@ import ( "context" "encoding/json" "path" + "strings" "testing" "time" + "unicode" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/storage" @@ -148,3 +150,88 @@ func TestManifest_RejectsFieldAliases(t *testing.T) { } } } + +func TestManifest_FormatSpecificFoldedFields(t *testing.T) { + for _, tc := range []struct { + format int + name string + }{{1, "segments"}, {1, "chunk_bytes"}, {1, "chunk_count"}, {2, "chunks"}} { + variants := map[string]bool{tc.name: true, strings.ToUpper(tc.name): true} + original := []rune(tc.name) + for i, r := range original { + for folded := unicode.SimpleFold(r); folded != r; folded = unicode.SimpleFold(folded) { + key := append([]rune(nil), original...) + key[i] = folded + variants[string(key)] = true + } + } + for key := range variants { + encoded, _ := json.Marshal(key) + suffix := string(encoded) + `:null` + root := `{"format":1,"gen":1,"epoch":1,"holder":"h",` + suffix + `}` + if tc.format == 2 { + root = `{"format":2,"gen":1,"epoch":1,"holder":"h","chunk_bytes":32768,"segments":{},` + suffix + `}` + } + if _, err := DecodeHeadDocument("folded", []byte(root)); err == nil { + t.Errorf("format%d accepted folded residual %s", tc.format, key) + } + } + } + for _, root := range []string{ + `{"format":1,"gen":1,"epoch":1,"holder":"h","\u017fegments":null}`, + `{"format":2,"gen":1,"epoch":1,"holder":"h","chunk_bytes":32768,"segments":{},"chun\u212as":null}`, + } { + if _, err := DecodeHeadDocument("escaped", []byte(root)); err == nil { + t.Errorf("accepted escaped mixed root: %s", root) + } + } +} + +func TestManifest_LongSDiscriminatorCorruptionRefusesReadAndGC(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + r, _ := publishSegmented(t, f, b) + if err := r.Put(ctx, "orphan", []byte("do not delete after bad mark")); err != nil { + t.Fatal(err) + } + if _, err := g.Run(ctx); err != nil { + t.Fatal(err) + } + *now = now.Add(2 * time.Hour) + e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) + if err != nil { + t.Fatal(err) + } + var fields map[string]json.RawMessage + if err = json.Unmarshal(e.Content, &fields); err != nil { + t.Fatal(err) + } + fields["format"] = json.RawMessage("1") + fields["\u017fegments"] = fields["segments"] + delete(fields, "segments") + delete(fields, "chunk_bytes") + delete(fields, "chunk_count") + e.Content, err = json.Marshal(fields) + if err != nil { + t.Fatal(err) + } + if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + if h, err := r.GetHead(ctx); err == nil { + t.Errorf("Unicode mixed root became readable empty image: %+v", h) + } + if h, _, err := c.ReadHead(ctx, "v1"); err == nil { + t.Errorf("catalog accepted Unicode mixed root: %+v", h) + } + _, _, before := b.counts() + for _, apply := range []bool{false, true} { + if _, err := g.run(ctx, apply); err == nil { + t.Errorf("Unicode mixed root accepted by GC apply=%v", apply) + } + } + _, _, after := b.counts() + if before != after { + t.Fatal("Unicode mixed root allowed partial delete") + } +} From bb52a686b8dbb7f9039db6ab6ed11dc53a7c2184 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 19:11:42 -0800 Subject: [PATCH 21/21] fix: decode HEAD with a strict format-specific schema --- .../core/frontend/chunkstore/chunk_remote.go | 22 +----- .../core/frontend/chunkstore/head_decode.go | 69 +++++++++++++++++++ 2 files changed, 71 insertions(+), 20 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/head_decode.go diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 48c67a869f..b477841b8b 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -507,28 +507,10 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) { fail := func(format string, a ...any) (storage.ChunkHead, error) { return storage.ChunkHead{}, fmt.Errorf("chunkstore: HEAD %s: "+format, append([]any{p}, a...)...) } - var doc headDoc - if err := decodeManifestJSON(content, &doc); err != nil { + doc, err := decodeFormatHead(content) + if err != nil { return fail("decode: %v", err) } - var fields map[string]json.RawMessage - if err := json.Unmarshal(content, &fields); err != nil { - return fail("decode representation: %v", err) - } - for name := range fields { - // encoding/json also matches tagged names case-insensitively; reject - // every such alias rather than let it bypass representation checks. - field := strings.ToLower(name) - if doc.Format == 1 && (field == "segments" || field == "chunk_bytes" || field == "chunk_count") { - return fail("flat HEAD contains segment field %s", name) - } - if doc.Format == 2 && field == "chunks" { - return fail("segmented HEAD contains flat chunks field") - } - } - if doc.Format != headFormat && doc.Format != 2 { - return fail("format %d not supported (want %d)", doc.Format, headFormat) - } if doc.Gen == 0 { return fail("generation 0") } diff --git a/seaweed-block/core/frontend/chunkstore/head_decode.go b/seaweed-block/core/frontend/chunkstore/head_decode.go new file mode 100644 index 0000000000..fca0c37eff --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/head_decode.go @@ -0,0 +1,69 @@ +package chunkstore + +import ( + "bytes" + "encoding/json" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Only identity/proof fields are shared between persisted representations. +// Format-specific structs deliberately have no field for the other format: +// DisallowUnknownFields rejects even encoding/json's Unicode-folded aliases. +type headIdentityDoc struct { + Format int `json:"format"` + Gen uint64 `json:"gen"` + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + RemoteLSN uint64 `json:"remote_lsn"` + State string `json:"state,omitempty"` + DetachedBy *detachedByDoc `json:"detachedBy,omitempty"` +} +type flatHeadDoc struct { + headIdentityDoc + Chunks map[uint64]refDoc `json:"chunks"` +} +type segmentedHeadDoc struct { + headIdentityDoc + Segments map[uint64]storage.ChunkSegment `json:"segments"` + ChunkBytes uint64 `json:"chunk_bytes"` + ChunkCount int `json:"chunk_count"` +} + +func (d headIdentityDoc) document() headDoc { + return headDoc{Format: d.Format, Gen: d.Gen, Epoch: d.Epoch, Holder: d.Holder, RemoteLSN: d.RemoteLSN, State: d.State, DetachedBy: d.DetachedBy} +} + +func decodeFormatHead(content []byte) (headDoc, error) { + var discriminator struct { + Format int `json:"format"` + } + // Preserve duplicate/nesting/byte/trailing-byte checks before selecting the + // schema. Unknown fields are allowed ONLY for this discriminator read. + if err := decodeManifestJSON(content, &discriminator); err != nil { + return headDoc{}, err + } + decoder := json.NewDecoder(bytes.NewReader(content)) + decoder.DisallowUnknownFields() + switch discriminator.Format { + case 1: + var flat flatHeadDoc + if err := decoder.Decode(&flat); err != nil { + return headDoc{}, err + } + doc := flat.headIdentityDoc.document() + doc.Chunks = flat.Chunks + return doc, nil + case 2: + var segmented segmentedHeadDoc + if err := decoder.Decode(&segmented); err != nil { + return headDoc{}, err + } + doc := segmented.headIdentityDoc.document() + doc.Segments, doc.ChunkBytes, doc.ChunkCount = segmented.Segments, segmented.ChunkBytes, segmented.ChunkCount + return doc, nil + default: + return headDoc{}, fmt.Errorf("chunkstore: unsupported HEAD format %d", discriminator.Format) + } +}