From 76cae100de4dd0a41d512c1f63459f17e1fa0f02 Mon Sep 17 00:00:00 2001 From: MapleWhiteZZZ <421700801@qq.com> Date: Wed, 2 Dec 2026 04:00:31 +0800 Subject: [PATCH] filer: leave the manifests an update keeps unread when finding its garbage (#13224) MinusChunks finds the chunks an update drops by resolving every manifest of the old entry and of the new one. A manifest both entries list is the same needle on both sides: all it holds is held by both, so none of it can be dropped, yet it was read from a volume server twice on every update. A file whose older chunks are folded into manifests paid that on each chmod, utimes, setxattr and append. Manifests listed on both sides are now taken out of both lists before the others are resolved. They are read only when something else the old entry holds might still be held through one of them, and then subtracted, so the result is the one resolving everything gives. An attribute change or an append that keeps the manifests reads none of them, and a kept manifest that cannot be read no longer fails an update that drops nothing. Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com> --- weed/filer/filechunks.go | 70 ++++++++- weed/filer/filechunks_minus_test.go | 222 ++++++++++++++++++++++++++++ 2 files changed, 290 insertions(+), 2 deletions(-) create mode 100644 weed/filer/filechunks_minus_test.go diff --git a/weed/filer/filechunks.go b/weed/filer/filechunks.go index 928550e3d5..54622387b1 100644 --- a/weed/filer/filechunks.go +++ b/weed/filer/filechunks.go @@ -141,8 +141,19 @@ func FindGarbageChunks(visibles *IntervalList[*VisibleInterval], start int64, st return } +// MinusChunks returns the chunks as reads that bs does not: data chunks and +// manifests, with manifests on both sides resolved to what they hold. +// +// A manifest both lists hold is the same needle on both sides, so all it holds +// is held by both and none of it can be in the result. Such manifests are left +// out of both lists and read only if something else as holds might be held by +// bs through one of them. An update that keeps a file's manifests, such as an +// attribute change or an append to a file whose older chunks are folded, then +// reads none of them, where it used to read each one twice. func MinusChunks(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, as, bs []*filer_pb.FileChunk, invalidator CacheInvalidator) (delta []*filer_pb.FileChunk, err error) { + as, bs, shared := splitSharedManifests(as, bs) + aData, aMeta, aErr := ResolveChunkManifest(ctx, lookupFileIdFn, as, 0, math.MaxInt64, invalidator, false) if aErr != nil { return nil, aErr @@ -152,11 +163,66 @@ func MinusChunks(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFuncti return nil, bErr } - delta = append(delta, DoMinusChunks(aData, bData)...) - delta = append(delta, DoMinusChunks(aMeta, bMeta)...) + dataDelta := DoMinusChunks(aData, bData) + metaDelta := DoMinusChunks(aMeta, bMeta) + if len(shared) > 0 && (len(dataDelta) > 0 || len(metaDelta) > 0) { + // bs may still hold some of these through a manifest both sides keep + sData, sMeta, sErr := ResolveChunkManifest(ctx, lookupFileIdFn, shared, 0, math.MaxInt64, invalidator, false) + if sErr != nil { + return nil, sErr + } + dataDelta = DoMinusChunks(dataDelta, sData) + metaDelta = DoMinusChunks(metaDelta, sMeta) + } + + delta = append(delta, dataDelta...) + delta = append(delta, metaDelta...) return } +// splitSharedManifests takes the manifests that both as and bs resolve out of +// both lists and returns them apart, as bs lists them. +func splitSharedManifests(as, bs []*filer_pb.FileChunk) (aRest, bRest, shared []*filer_pb.FileChunk) { + // what ResolveChunkManifest over a whole file visits: a chunk with an + // empty span is skipped, along with all it holds + resolved := func(chunk *filer_pb.FileChunk) bool { + return chunk.IsChunkManifest && max(chunk.Offset, 0) < min(chunk.Offset+int64(chunk.Size), math.MaxInt64) + } + inA := make(map[string]bool) + for _, chunk := range as { + if resolved(chunk) { + inA[ChunkIdentity(chunk.GetFileIdString())] = true + } + } + both := make(map[string]bool) + for _, chunk := range bs { + if resolved(chunk) { + if id := ChunkIdentity(chunk.GetFileIdString()); inA[id] { + both[id] = true + } + } + } + if len(both) == 0 { + return as, bs, nil + } + // a skipped listing of a shared manifest adds nothing on either side + keep := func(chunks []*filer_pb.FileChunk, collect bool) (rest []*filer_pb.FileChunk) { + for _, chunk := range chunks { + if chunk.IsChunkManifest && both[ChunkIdentity(chunk.GetFileIdString())] { + if collect && resolved(chunk) { + shared = append(shared, chunk) + } + continue + } + rest = append(rest, chunk) + } + return rest + } + aRest = keep(as, false) + bRest = keep(bs, true) + return aRest, bRest, shared +} + func DoMinusChunks(as, bs []*filer_pb.FileChunk) (delta []*filer_pb.FileChunk) { fileIds := make(map[string]bool) diff --git a/weed/filer/filechunks_minus_test.go b/weed/filer/filechunks_minus_test.go new file mode 100644 index 0000000000..149c00e000 --- /dev/null +++ b/weed/filer/filechunks_minus_test.go @@ -0,0 +1,222 @@ +package filer + +import ( + "context" + "fmt" + "math" + "math/rand" + "net/http" + "net/http/httptest" + "sort" + "strings" + "sync/atomic" + "testing" + + "google.golang.org/protobuf/proto" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" +) + +// manifestVolume serves the manifests of a testManifestStore by file id, as a +// volume server would, and counts the reads. +type manifestVolume struct { + store *testManifestStore + reads atomic.Int64 + url string +} + +func newManifestVolume(t *testing.T) *manifestVolume { + t.Helper() + v := &manifestVolume{store: newTestManifestStore()} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + v.reads.Add(1) + data, ok := v.store.stored[strings.TrimPrefix(r.URL.Path, "/")] + if !ok { + http.NotFound(w, r) + return + } + w.Write(data) + })) + t.Cleanup(srv.Close) + v.url = srv.URL + return v +} + +func (v *manifestVolume) lookup(ctx context.Context, fileId string) ([]string, error) { + return []string{v.url + "/" + fileId}, nil +} + +// manifest stores a manifest holding chunks and returns its chunk. +func (v *manifestVolume) manifest(t *testing.T, chunks ...*filer_pb.FileChunk) *filer_pb.FileChunk { + t.Helper() + held := make([]*filer_pb.FileChunk, len(chunks)) + for i, c := range chunks { + held[i] = proto.Clone(c).(*filer_pb.FileChunk) + } + filer_pb.BeforeEntrySerialization(held) + data, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: held}) + if err != nil { + t.Fatal(err) + } + // a manifest covers the span of what it holds + start, stop := int64(math.MaxInt64), int64(0) + for _, c := range chunks { + start, stop = min(start, c.Offset), max(stop, c.Offset+int64(c.Size)) + } + v.store.nextID++ + m := &filer_pb.FileChunk{ + Fid: &filer_pb.FileId{VolumeId: 999, FileKey: uint64(v.store.nextID), Cookie: 7}, + IsChunkManifest: true, + Offset: start, + Size: uint64(stop - start), + } + v.store.stored[m.GetFileIdString()] = data + return m +} + +func ids(chunks []*filer_pb.FileChunk) []string { + out := make([]string, 0, len(chunks)) + for _, c := range chunks { + out = append(out, ChunkIdentity(c.GetFileIdString())) + } + sort.Strings(out) + return out +} + +// minusEveryManifest is MinusChunks as it was: every manifest on both sides +// resolved. +func minusEveryManifest(t *testing.T, v *manifestVolume, as, bs []*filer_pb.FileChunk) []*filer_pb.FileChunk { + t.Helper() + aData, aMeta, err := ResolveChunkManifest(context.Background(), v.lookup, as, 0, math.MaxInt64, nil, false) + if err != nil { + t.Fatal(err) + } + bData, bMeta, err := ResolveChunkManifest(context.Background(), v.lookup, bs, 0, math.MaxInt64, nil, false) + if err != nil { + t.Fatal(err) + } + return append(DoMinusChunks(aData, bData), DoMinusChunks(aMeta, bMeta)...) +} + +func TestMinusChunksReadsOnlyTheManifestsAnUpdateChanges(t *testing.T) { + v := newManifestVolume(t) + d := func(i int) *filer_pb.FileChunk { + return testChunk(1, uint64(i), uint32(i), int64(i*100), 100, int64(i)) + } + m1 := v.manifest(t, d(1), d(2), d(3)) + m2 := v.manifest(t, d(4), d(5), d(6)) + m3 := v.manifest(t, d(7), d(8)) + + cases := []struct { + name string + old, new []*filer_pb.FileChunk + want []*filer_pb.FileChunk + wantReads int64 + everyReads int64 // what resolving every manifest costs + }{ + {"attribute change", []*filer_pb.FileChunk{m1, m2, d(7)}, []*filer_pb.FileChunk{m1, m2, d(7)}, nil, 0, 4}, + {"append", []*filer_pb.FileChunk{m1, m2, d(7)}, []*filer_pb.FileChunk{m1, m2, d(7), d(8)}, nil, 0, 4}, + {"fold the tail", []*filer_pb.FileChunk{m1, m2, d(7), d(8)}, []*filer_pb.FileChunk{m1, m2, m3}, nil, 1, 5}, + {"rewrite the tail", []*filer_pb.FileChunk{m1, m2, d(7)}, []*filer_pb.FileChunk{m1, m2, d(9)}, []*filer_pb.FileChunk{d(7)}, 2, 4}, + {"truncate to 0", []*filer_pb.FileChunk{m1, m2, d(7)}, nil, []*filer_pb.FileChunk{d(1), d(2), d(3), d(4), d(5), d(6), d(7), m1, m2}, 2, 2}, + {"a dropped chunk still held through a kept manifest", []*filer_pb.FileChunk{m1, d(2)}, []*filer_pb.FileChunk{m1}, nil, 1, 2}, + {"a dropped manifest", []*filer_pb.FileChunk{m1, m2}, []*filer_pb.FileChunk{m1}, []*filer_pb.FileChunk{d(4), d(5), d(6), m2}, 2, 3}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + v.reads.Store(0) + got, err := MinusChunks(context.Background(), v.lookup, tc.old, tc.new, nil) + if err != nil { + t.Fatal(err) + } + reads := v.reads.Load() + v.reads.Store(0) + every := minusEveryManifest(t, v, tc.old, tc.new) + if g, w := ids(got), ids(tc.want); fmt.Sprint(g) != fmt.Sprint(w) { + t.Errorf("got %v, want %v", g, w) + } + if g, w := ids(got), ids(every); fmt.Sprint(g) != fmt.Sprint(w) { + t.Errorf("got %v, resolving every manifest gives %v", g, w) + } + if reads != tc.wantReads { + t.Errorf("read %d manifests, want %d", reads, tc.wantReads) + } + if r := v.reads.Load(); r != tc.everyReads { + t.Errorf("resolving every manifest read %d, test expects %d", r, tc.everyReads) + } + }) + } +} + +// Random old and new chunk lists, with manifests held by both, nested +// manifests and chunks listed twice: the delta is the one resolving every +// manifest gives. +func TestMinusChunksMatchesResolvingEveryManifest(t *testing.T) { + v := newManifestVolume(t) + rnd := rand.New(rand.NewSource(13)) + data := make([]*filer_pb.FileChunk, 40) + for i := range data { + data[i] = testChunk(uint32(1+i%3), uint64(i+1), uint32(i+1), int64(i*100), 100, int64(i+1)) + } + pick := func(from []*filer_pb.FileChunk, n int) []*filer_pb.FileChunk { + var out []*filer_pb.FileChunk + for i := 0; i < n; i++ { + out = append(out, from[rnd.Intn(len(from))]) + } + return out + } + for iter := 0; iter < 400; iter++ { + var manifests []*filer_pb.FileChunk + for k := 0; k < 1+rnd.Intn(6); k++ { + held := pick(data, 1+rnd.Intn(6)) + if len(manifests) > 0 && rnd.Intn(3) == 0 { + held = append(held, manifests[rnd.Intn(len(manifests))]) // nested + } + manifests = append(manifests, v.manifest(t, held...)) + } + listed := func() []*filer_pb.FileChunk { + out := append(pick(data, rnd.Intn(6)), pick(manifests, rnd.Intn(4))...) + if rnd.Intn(5) == 0 { + // a listing with an empty span, which resolving skips + empty := proto.Clone(manifests[rnd.Intn(len(manifests))]).(*filer_pb.FileChunk) + empty.Size = 0 + out = append(out, empty) + } + return out + } + old, cur := listed(), listed() + if rnd.Intn(4) == 0 { + cur = append(cur, old...) // an update that keeps everything + } + rnd.Shuffle(len(old), func(i, j int) { old[i], old[j] = old[j], old[i] }) + rnd.Shuffle(len(cur), func(i, j int) { cur[i], cur[j] = cur[j], cur[i] }) + + got, err := MinusChunks(context.Background(), v.lookup, old, cur, nil) + if err != nil { + t.Fatal(err) + } + want := minusEveryManifest(t, v, old, cur) + if g, w := ids(got), ids(want); fmt.Sprint(g) != fmt.Sprint(w) { + t.Fatalf("iteration %d: old %v new %v: got %v, resolving every manifest gives %v", iter, ids(old), ids(cur), g, w) + } + } +} + +// A manifest both sides keep is not read, so one that cannot be read does not +// fail an update that drops nothing; one that has to be read still does. +func TestMinusChunksUnreadableKeptManifest(t *testing.T) { + v := newManifestVolume(t) + d := func(i int) *filer_pb.FileChunk { + return testChunk(1, uint64(i), uint32(i), int64(i*100), 100, int64(i)) + } + m1 := v.manifest(t, d(1), d(2)) + delete(v.store.stored, m1.GetFileIdString()) + + got, err := MinusChunks(context.Background(), v.lookup, []*filer_pb.FileChunk{m1, d(3)}, []*filer_pb.FileChunk{m1, d(3), d(4)}, nil) + if err != nil || len(got) != 0 { + t.Fatalf("an update keeping the manifest: got %v, %v; want nothing, no error", ids(got), err) + } + if _, err := MinusChunks(context.Background(), v.lookup, []*filer_pb.FileChunk{m1, d(3)}, []*filer_pb.FileChunk{m1}, nil); err == nil { + t.Fatal("an update dropping a chunk the kept manifest might hold: want the read error") + } +}