From 790dec338743d434647725bf8c5e987e4ff95ca4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 03:00:31 -0800 Subject: [PATCH] storage, chunkstore: CASHeadDelta, a required commit by change on the seam chunkRemote gains CASHeadDelta and chunkCommitChecker CheckCommitDelta: the new HEAD's identity and the changed chunks (nil: zeros). LayoutRemote reads HEAD's current root and the changed shards' previous segments only, writes their new segments and the root (PrepareRootDelta), and looks up the new chunks, new segments and root; an unchanged segment is not read, written or looked up. Compile-time assertions bind LayoutRemote and MemChunkRemote to the seam; the durable provider's bound wrapper forwards both with its binding. The engine still calls the full-map CASHead and CheckCommit until V4-B, which removes them. The counting test: a one-chunk commit by change on three shards touches only the changed shard's segments, creating one segment and one root, and installs the HEAD the full commit of the same change would; the full commit touches every shard. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/commit.go | 7 +- .../frontend/chunkstore/layout/objects.go | 25 +++ .../core/frontend/chunkstore/layout/read.go | 9 + .../layout_commit_by_change_test.go | 210 ++++++++++++++++++ .../core/frontend/chunkstore/layout_remote.go | 171 ++++++++++++-- .../core/frontend/durable/provider_chunk.go | 19 ++ .../core/storage/chunk_fake_remote_test.go | 11 + seaweed-block/core/storage/chunk_memremote.go | 32 +++ seaweed-block/core/storage/chunk_seam.go | 12 + 9 files changed, 480 insertions(+), 16 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout_commit_by_change_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit.go b/seaweed-block/core/frontend/chunkstore/layout/commit.go index 0fc572afb6..a0436a5211 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit.go @@ -171,6 +171,7 @@ func (h Head) Commit(me HolderID, session string, root RootName, position uint64 // request, outside the conditional HEAD update, so that update's step does no // work that grows with the chunk count, on any attempt. type CommitPlan struct { + rootObj Root // a commit by change's new root (PrepareRootDelta writes it) root RootName segs map[SegName][]byte base RootName @@ -271,7 +272,7 @@ func planDelta(vol string, d CommitDelta, lookups bool) (CommitPlan, error) { if err != nil { return CommitPlan{}, err } - p := CommitPlan{root: rn, segs: segs, prevEmpty: d.Base == nil, lookups: lookups} + p := CommitPlan{rootObj: root, root: rn, segs: segs, prevEmpty: d.Base == nil, lookups: lookups} if d.Base != nil { p.base = *d.Base } @@ -326,6 +327,10 @@ func (p CommitPlan) Root() RootName { return p.root } // shards' new ones (a commit by change). func (p CommitPlan) Segments() map[SegName][]byte { return p.segs } +// RootObject is a commit by change's new root (empty for a full commit, +// whose root PrepareRoot builds from the manifest). +func (p CommitPlan) RootObject() Root { return p.rootObj } + // Lookups are the objects the planned commit looks up, in order. func (p CommitPlan) Lookups() []string { return p.rels } diff --git a/seaweed-block/core/frontend/chunkstore/layout/objects.go b/seaweed-block/core/frontend/chunkstore/layout/objects.go index 1ccc321d2f..3152b9c3bf 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/objects.go +++ b/seaweed-block/core/frontend/chunkstore/layout/objects.go @@ -123,6 +123,31 @@ func PrepareRoot(ctx context.Context, os ObjectStore, root Root, segs map[SegNam return rn, EnsureObject(ctx, os, rn.Path(), rb, session) } +// PrepareRootDelta writes a commit by change's objects in session: each of +// segs (the changed shards' new segments, each named by root), then root. +// The segments root names and segs does not are the previous root's; they +// are not written or read here. +func PrepareRootDelta(ctx context.Context, os ObjectStore, root Root, segs map[SegName][]byte, session string) (RootName, error) { + names := make([]SegName, 0, len(segs)) + for n := range segs { + if root.Segments[n.Shard] != n { + return RootName{}, fmt.Errorf("layout: segment %s is not the one the root names for shard %d", n.Path(), n.Shard) + } + names = append(names, n) + } + sort.Slice(names, func(a, b int) bool { return names[a].Shard < names[b].Shard }) + for _, n := range names { + if err := EnsureObject(ctx, os, n.Path(), segs[n], session); err != nil { + return RootName{}, err + } + } + rn, rb, err := NameRoot(root) + if err != nil { + return RootName{}, err + } + return rn, EnsureObject(ctx, os, rn.Path(), rb, session) +} + // ownedBySession reports whether rel exists, carries session as its writer // and is unmarked: an object a commit of that session may name. // ownedOrAdopted is ownedBySession that first adopts rel when it is an diff --git a/seaweed-block/core/frontend/chunkstore/layout/read.go b/seaweed-block/core/frontend/chunkstore/layout/read.go index 9035314d43..2d2cd2ae8d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/read.go +++ b/seaweed-block/core/frontend/chunkstore/layout/read.go @@ -118,6 +118,15 @@ func (r *Reader) ReadRef(ctx context.Context, ref Ref) ([]byte, error) { return r.get(ctx, dir, ref.Chunk.Path(), ref.Chunk.Hash) } +// Root returns a copy of the image's root (its segment names). +func (img *Image) Root() Root { + out := Root{Segments: make(map[uint64]SegName, len(img.root.Segments))} + for sh, n := range img.root.Segments { + out.Segments[sh] = n + } + return out +} + // Shards returns the shards the image's root names, in order. func (img *Image) Shards() []uint64 { out := make([]uint64, 0, len(img.root.Segments)) diff --git a/seaweed-block/core/frontend/chunkstore/layout_commit_by_change_test.go b/seaweed-block/core/frontend/chunkstore/layout_commit_by_change_test.go new file mode 100644 index 0000000000..b8005795c9 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_commit_by_change_test.go @@ -0,0 +1,210 @@ +package chunkstore + +import ( + "context" + "fmt" + "path" + "reflect" + "sort" + "strings" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// segTouches records, while armed, the shards whose segment objects a +// commit looked up or created, and the pool chunks and roots it created. +type segTouches struct { + mu sync.Mutex + armed bool + shards map[string]bool // shard of every segment path looked up or created + created map[string]int // "seg", "root", "pool": objects created +} + +func (s *segTouches) install(ff *fakeFiler) { + seg := func(p string) { + if s.armed && strings.Contains(p, "/seg/") { + if sh, _, ok := strings.Cut(path.Base(p), "-"); ok { + s.shards[sh] = true + } + } + } + ff.afterLookup = func(p string) { s.mu.Lock(); seg(p); s.mu.Unlock() } + ff.beforeCreate = func(p string) { + s.mu.Lock() + defer s.mu.Unlock() + seg(p) + if !s.armed { + return + } + for _, kind := range []string{"seg", "root", "pool"} { + if strings.Contains(p, "/"+kind+"/") { + s.created[kind]++ + } + } + } +} + +func (s *segTouches) arm() { + s.mu.Lock() + defer s.mu.Unlock() + s.armed, s.shards, s.created = true, map[string]bool{}, map[string]int{} +} + +func (s *segTouches) touched() []string { + s.mu.Lock() + defer s.mu.Unlock() + var out []string + for sh := range s.shards { + out = append(out, sh) + } + sort.Strings(out) + return out +} + +// threeShardVolume is a started volume whose HEAD names one chunk in each +// of three shards, committed by a full commit, and the remote that holds it. +func threeShardVolume(t *testing.T) (context.Context, *fakeFiler, *LayoutRemote, storage.ChunkHead) { + t.Helper() + ctx := context.Background() + ff := newFakeFiler() + cat, err := NewBCatalog(ff, newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + geo := layout.Geometry{SizeBytes: 3 * layout.ShardSize * 4096, BlockSize: 4096, ChunkBytes: 4096} + v := newRef(t, "v") + if _, err := cat.CreateVolume(ctx, v, geo); err != nil { + t.Fatal(err) + } + s, err := cat.Store(v) + if err != nil { + t.Fatal(err) + } + me := layout.HolderID{Epoch: 1, Holder: "a", ClaimID: "k-a"} + if _, err := layout.Start(ctx, s, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "a"}, layout.LocalRoot{Geometry: geo, ClaimID: "k-a", Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatal(err) + } + r, err := NewLayoutRemote(cat, v, me) + if err != nil { + t.Fatal(err) + } + h0, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + first := storage.ChunkHead{Epoch: 1, RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{}} + for sh := uint64(0); sh < 3; sh++ { + i := sh*layout.ShardSize + 7 + first.Chunks[i] = putChunk(t, ctx, r, i, "first") + } + exp := storage.ChunkHeadVersion{Gen: h0.Gen, Epoch: 1} + if err := r.CheckCommit(ctx, exp, first); err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(ctx, exp, first); err != nil { + t.Fatal(err) + } + h1, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + return ctx, ff, r, h1 +} + +func putChunk(t *testing.T, ctx context.Context, r *LayoutRemote, i uint64, tag string) storage.ChunkRef { + t.Helper() + data := []byte(fmt.Sprintf("%s-%d", tag, i)) + key := r.ChunkKey(i, layout.Sum(data)) + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + return storage.ChunkRef{Key: key, SHA256: layout.Sum(data), Encoding: "full"} +} + +// A one-chunk commit by change on a volume of three shards touches only the +// changed shard's segments (its previous one read, its new one written) and +// writes one segment and one root: the other two shards' segments are not +// read, written or looked up. The HEAD it installs names exactly the chunk +// map the full commit of the same change would. The full commit of the +// same change touches every shard (the S-sized work this removes). +func TestOneChunkCommitByChangeTouchesOnlyItsShard(t *testing.T) { + for _, byChange := range []bool{true, false} { + name := map[bool]string{true: "by change", false: "full"}[byChange] + t.Run(name, func(t *testing.T) { + ctx, ff, r, h1 := threeShardVolume(t) + tr := &segTouches{} + tr.install(ff) + i := uint64(layout.ShardSize + 9) // a new chunk in shard 1 + ref := putChunk(t, ctx, r, i, "second") + next := storage.ChunkHead{Epoch: 1, RemoteLSN: 2} + exp := storage.ChunkHeadVersion{Gen: h1.Gen, Epoch: 1} + tr.arm() + var err error + if byChange { + changes := map[uint64]*storage.ChunkRef{i: &ref} + if err = r.CheckCommitDelta(ctx, exp, next, changes); err == nil { + _, err = r.CASHeadDelta(ctx, exp, next, changes) + } + } else { + next.Chunks = storage.ApplyChunkChanges(h1.Chunks, map[uint64]*storage.ChunkRef{i: &ref}) + if err = r.CheckCommit(ctx, exp, next); err == nil { + _, err = r.CASHead(ctx, exp, next) + } + } + if err != nil { + t.Fatal(err) + } + touched := tr.touched() + t.Logf("%s: segment shards touched %v, created %v", name, touched, tr.created) + if byChange { + if !reflect.DeepEqual(touched, []string{"1"}) || tr.created["seg"] != 1 || tr.created["root"] != 1 { + t.Fatalf("a one-chunk commit by change touched shards %v and created %v; want shard 1 only, one segment and one root", touched, tr.created) + } + } else if len(touched) != 3 { + t.Fatalf("the full commit touched shards %v; this control expects all three", touched) + } + got, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + want := storage.ApplyChunkChanges(h1.Chunks, map[uint64]*storage.ChunkRef{i: &ref}) + if !reflect.DeepEqual(got.Chunks, want) || got.RemoteLSN != 2 { + t.Fatalf("HEAD after the commit names %d chunks at %d; want the full new map at 2", len(got.Chunks), got.RemoteLSN) + } + }) + } +} + +// A commit by change that zeroes a shard's only chunk drops the shard from +// the root and writes no segment; one that rewrites a chunk with the same +// reference writes no segment either. Both install the HEAD the full commit +// would. +func TestCommitByChangeOfZerosAndUnchangedRefs(t *testing.T) { + ctx, ff, r, h1 := threeShardVolume(t) + tr := &segTouches{} + tr.install(ff) + same := h1.Chunks[7] + changes := map[uint64]*storage.ChunkRef{2*layout.ShardSize + 7: nil, 7: &same} + exp := storage.ChunkHeadVersion{Gen: h1.Gen, Epoch: 1} + next := storage.ChunkHead{Epoch: 1, RemoteLSN: 2} + tr.arm() + if err := r.CheckCommitDelta(ctx, exp, next, changes); err != nil { + t.Fatal(err) + } + if _, err := r.CASHeadDelta(ctx, exp, next, changes); err != nil { + t.Fatal(err) + } + if tr.created["seg"] != 0 || tr.created["root"] != 1 { + t.Fatalf("created %v; want no segment and one root", tr.created) + } + got, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if want := storage.ApplyChunkChanges(h1.Chunks, changes); !reflect.DeepEqual(got.Chunks, want) { + t.Fatalf("HEAD names %v; want %v", got.Chunks, want) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index c3c028d206..8713abceeb 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -73,6 +73,8 @@ type LayoutRemote struct { session string expected storage.ChunkHeadVersion next storage.ChunkHead + delta bool + changes map[uint64]*storage.ChunkRef // a commit by change's changes req layout.CommitRequest } pending *pendingSnapshot @@ -136,6 +138,13 @@ var ( // NewLayoutRemote returns the remote of volume v for the holder me (the // line its Start claimed). +// The layout remote implements the whole seam, the commit by change +// included (a required method, never an optional capability). +var ( + _ storage.ChunkRemote = (*LayoutRemote)(nil) + _ storage.ChunkCommitChecker = (*LayoutRemote)(nil) +) + func NewLayoutRemote(cat *BCatalog, v VolumeRef, me layout.HolderID) (*LayoutRemote, error) { if me.Epoch == 0 || me.Holder == "" || me.ClaimID == "" { return nil, errors.New("chunkstore: layout remote needs the holder's epoch, holder and claim id") @@ -472,7 +481,12 @@ func boundedManifest(ctx context.Context, r *layout.Reader, rn layout.RootName, // a foreign claim or detached/deleted state remains a final refusal. // prepareCommitLocked reads HEAD and builds next's commit request in the // open session, its root and segments written (CASHead and CheckCommit). -func (l *LayoutRemote) prepareCommitLocked(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (layout.Head, layout.CommitRequest, bool, error) { +// +// A commit by change (delta: CASHeadDelta, CheckCommitDelta) reads HEAD's +// current root and the previous segment of each changed shard only, and +// writes the changed shards' new segments and the root; its plan is built +// here and carried in the request. +func (l *LayoutRemote) prepareCommitLocked(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead, delta bool, changes map[uint64]*storage.ChunkRef) (layout.Head, layout.CommitRequest, bool, error) { l.takeAbandonLocked() if expected.Epoch != l.me.Epoch || next.Epoch != l.me.Epoch { return layout.Head{}, layout.CommitRequest{}, false, storage.ErrChunkHeadPrecondition @@ -488,12 +502,18 @@ func (l *LayoutRemote) prepareCommitLocked(ctx context.Context, expected storage if expected.Gen != l.visible { return layout.Head{}, layout.CommitRequest{}, false, storage.ErrChunkHeadPrecondition } - if l.isCheckedLocked(expected, next) { + if l.isCheckedLocked(expected, next, delta, changes) { // The checked commit, in its still open session: its manifests, root // and segments are already prepared and its plan built. return h, l.checked.req, true, nil } - prev, nextM, err := l.manifests(ctx, h, next) + var prev, nextM map[uint64]layout.Ref + var d layout.CommitDelta + if delta { + d, err = l.deltaLocked(ctx, h, changes) + } else { + prev, nextM, err = l.manifests(ctx, h, next) + } if err != nil { return layout.Head{}, layout.CommitRequest{}, false, err } @@ -505,10 +525,19 @@ func (l *LayoutRemote) prepareCommitLocked(ctx context.Context, expected storage return layout.Head{}, layout.CommitRequest{}, false, err } } - if err := l.writeRootLocked(ctx, nextM); err != nil { + req := layout.CommitRequest{Session: l.session, Prev: prev, Next: nextM, Position: next.RemoteLSN, State: layout.StateLive} + if delta { + plan, err := layout.PlanCommit(l.vol.Name, layout.CommitRequest{Delta: &d}, true) + if err != nil { + return layout.Head{}, layout.CommitRequest{}, false, layoutRemoteErr(err) + } + if err := l.writeDeltaRootLocked(ctx, plan); err != nil { + return layout.Head{}, layout.CommitRequest{}, false, err + } + req.Delta, req.Plan = &d, &plan + } else if err := l.writeRootLocked(ctx, nextM); err != nil { return layout.Head{}, layout.CommitRequest{}, false, err } - req := layout.CommitRequest{Session: l.session, Prev: prev, Next: nextM, Position: next.RemoteLSN, State: layout.StateLive} if next.State == "detached" { req.State = layout.StateDetached } @@ -522,25 +551,41 @@ func (l *LayoutRemote) prepareCommitLocked(ctx context.Context, expected storage // CASHead skips those lookups for this (session, root). A failed check // leaves the session open for a retry. func (l *LayoutRemote) CheckCommit(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) error { + return l.checkCommit(ctx, expected, next, false, nil) +} + +// CheckCommitDelta is CheckCommit of the commit by change CASHeadDelta +// makes with the same arguments: it reads, writes and looks up only what +// the change touches. +func (l *LayoutRemote) CheckCommitDelta(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead, changes map[uint64]*storage.ChunkRef) error { + return l.checkCommit(ctx, expected, next, true, changes) +} + +func (l *LayoutRemote) checkCommit(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead, delta bool, changes map[uint64]*storage.ChunkRef) error { + if delta { + next.Chunks, next.Segments = nil, nil // a commit by change names its identity only + } l.mu.Lock() defer l.mu.Unlock() l.takeAbandonLocked() - if l.isCheckedLocked(expected, next) { + if l.isCheckedLocked(expected, next, delta, changes) { // Already checked in this open session (a re-proposal after an // unknown outcome): the check holds for every attempt of the // session, and redoing it would look up every object again. return nil } l.clearCheckedLocked() - h, req, _, err := l.prepareCommitLocked(ctx, expected, next) + h, req, _, err := l.prepareCommitLocked(ctx, expected, next, delta, changes) if err != nil { return err } - plan, err := layout.PlanCommit(l.vol.Name, req, true) - if err != nil { - return err + if req.Plan == nil { + plan, err := layout.PlanCommit(l.vol.Name, req, true) + if err != nil { + return err + } + req.Plan = &plan } - req.Plan = &plan if err := layout.CheckCommitObjects(ctx, h, l.st, l.vol.Name, l.me, req); err != nil { if errors.Is(err, layout.ErrNotPrepared) { l.forceView = true // as CASHead: the re-read drops what the ended session staged @@ -549,9 +594,27 @@ func (l *LayoutRemote) CheckCommit(ctx context.Context, expected storage.ChunkHe return layoutRemoteErr(err) } l.checked.session, l.checked.expected, l.checked.next, l.checked.req = req.Session, expected, cloneChunkHead(next), req + l.checked.delta, l.checked.changes = delta, cloneChanges(changes) return nil } +// cloneChanges copies a commit by change's changes, so a later change by +// the caller cannot make another commit compare equal. +func cloneChanges(c map[uint64]*storage.ChunkRef) map[uint64]*storage.ChunkRef { + if c == nil { + return nil + } + out := make(map[uint64]*storage.ChunkRef, len(c)) + for i, r := range c { + if r != nil { + v := *r + r = &v + } + out[i] = r + } + return out +} + // cloneChunkHead copies h with its maps and pointer, so a later change by // the caller to what it passed cannot make another next HEAD compare equal. func cloneChunkHead(h storage.ChunkHead) storage.ChunkHead { @@ -587,14 +650,24 @@ func (l *LayoutRemote) commitStepLocked(ctx context.Context, req layout.CommitRe // isCheckedLocked reports whether expected and next are exactly the checked // commit, in its still open session. -func (l *LayoutRemote) isCheckedLocked(expected storage.ChunkHeadVersion, next storage.ChunkHead) bool { +func (l *LayoutRemote) isCheckedLocked(expected storage.ChunkHeadVersion, next storage.ChunkHead, delta bool, changes map[uint64]*storage.ChunkRef) bool { c := &l.checked - return c.session != "" && c.session == l.session && c.expected == expected && reflect.DeepEqual(c.next, next) + if c.session == "" || c.session != l.session || c.expected != expected || c.delta != delta { + return false + } + if delta { + // A commit by change: its identity and changes, never the whole map. + n := next + n.Chunks, n.Segments = nil, nil + return reflect.DeepEqual(c.next, n) && reflect.DeepEqual(c.changes, changes) + } + return reflect.DeepEqual(c.next, next) } // clearCheckedLocked forgets the checked commit. func (l *LayoutRemote) clearCheckedLocked() { l.checked.session, l.checked.expected, l.checked.next, l.checked.req = "", storage.ChunkHeadVersion{}, storage.ChunkHead{}, layout.CommitRequest{} + l.checked.delta, l.checked.changes = false, nil } // BoundsHeadStep: CASHead bounds its own HEAD step by @@ -613,19 +686,32 @@ func headStep(ctx context.Context) (context.Context, context.CancelFunc) { } func (l *LayoutRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + return l.casHead(ctx, expected, next, false, nil) +} + +// CASHeadDelta is CASHead by change (storage.ChunkRemote): it reads HEAD's +// current root and the changed shards' previous segments, writes their new +// segments and the root, and looks up the new chunks, the new segments and +// the root. An unchanged segment is not read, written or looked up. +func (l *LayoutRemote) CASHeadDelta(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead, changes map[uint64]*storage.ChunkRef) (uint64, error) { + next.Chunks, next.Segments = nil, nil // a commit by change names its identity only + return l.casHead(ctx, expected, next, true, changes) +} + +func (l *LayoutRemote) casHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead, delta bool, changes map[uint64]*storage.ChunkRef) (uint64, error) { l.mu.Lock() defer l.mu.Unlock() // The checked commit's preparation is reused on every attempt of this // session; any other commit is prepared and planned (with its lookups) // here. Either way the preparation runs under ctx, the caller's budget: // only each attempt's HEAD step is bounded by the step budget. - h, req, reused, err := l.prepareCommitLocked(ctx, expected, next) + h, req, reused, err := l.prepareCommitLocked(ctx, expected, next, delta, changes) if err != nil { return 0, err } if reused { req.ObjectsChecked = true - } else { + } else if req.Plan == nil { plan, err := layout.PlanCommit(l.vol.Name, req, true) if err != nil { return 0, layoutRemoteErr(err) @@ -735,6 +821,61 @@ func (l *LayoutRemote) manifests(ctx context.Context, h layout.Head, next storag return prev, nm, nil } +// deltaLocked is a commit by change's base: HEAD's current root (read, not +// its segments), the previous segment of each changed shard it names, and +// the changes as layout references (a key the engine got from HEAD keeps its +// reference; a chunk it uploaded is this volume's by name). It reads one +// root and at most one segment per changed shard. +func (l *LayoutRemote) deltaLocked(ctx context.Context, h layout.Head, changes map[uint64]*storage.ChunkRef) (layout.CommitDelta, error) { + defer storage.MeasureCutWork(ctx, storage.CutManifestRead)() + d := layout.CommitDelta{Changes: make(map[uint64]*layout.Ref, len(changes)), Prev: map[uint64]layout.Segment{}} + for idx, c := range changes { + if c == nil { + d.Changes[idx] = nil + continue + } + if c.Encoding != "full" { + return layout.CommitDelta{}, fmt.Errorf("%w: chunk %d encoding %q (only full: the stored bytes are the logical bytes)", ErrUnsupportedEncoding, idx, c.Encoding) + } + ref, err := ParseLayoutKey(c.Key) + if err != nil { + return layout.CommitDelta{}, err + } + if ref.Chunk.Index != idx || ref.Chunk.Hash != c.SHA256 { + return layout.CommitDelta{}, fmt.Errorf("%w: chunk %d key %q does not name its bytes", storage.ErrChunkKeyInvalid, idx, c.Key) + } + d.Changes[idx] = &ref + } + if h.Current == nil { + return d, nil + } + img, err := l.r.Open(ctx, *h.Current) + if err != nil { + return layout.CommitDelta{}, layoutRemoteErr(err) + } + base := *h.Current + d.Base, d.BaseRoot = &base, img.Root() + shards, _ := layout.ChangesByShard(d.Changes) + for _, sh := range shards { + seg, ok, err := img.Segment(ctx, sh) + if err != nil { + return layout.CommitDelta{}, layoutRemoteErr(err) + } + if ok { + d.Prev[sh] = seg + } + } + return d, nil +} + +// writeDeltaRootLocked writes a commit by change's new segments and root in +// this session, so the commit finds them prepared. +func (l *LayoutRemote) writeDeltaRootLocked(ctx context.Context, plan layout.CommitPlan) error { + defer storage.MeasureCutWork(ctx, storage.CutSegmentWrites)() + _, err := layout.PrepareRootDelta(ctx, l.st, plan.RootObject(), plan.Segments(), l.session) + return layoutRemoteErr(err) +} + // writeRootLocked writes next's segments and root in this session, so the // commit finds them prepared. func (l *LayoutRemote) writeRootLocked(ctx context.Context, next map[uint64]layout.Ref) error { diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 9cb0d75b50..f84121b9fc 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -753,6 +753,25 @@ func (r *closeBoundRemote) CheckCommit(ctx context.Context, expected storage.Chu return fmt.Errorf("%w: CheckCommit unavailable", errChunkRemoteCapabilities) } +// CASHeadDelta forwards the commit by change with the same binding as +// CASHead. +func (r *closeBoundRemote) CASHeadDelta(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead, changes map[uint64]*storage.ChunkRef) (uint64, error) { + c, end := r.bind(ctx) + defer end() + return r.ChunkRemote.CASHeadDelta(c, expected, next, changes) +} + +// CheckCommitDelta forwards the object check of a commit by change with the +// same binding as CheckCommit; a remote without it refuses. +func (r *closeBoundRemote) CheckCommitDelta(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead, changes map[uint64]*storage.ChunkRef) error { + c, end := r.bind(ctx) + defer end() + if checker, ok := r.ChunkRemote.(storage.ChunkCommitChecker); ok { + return checker.CheckCommitDelta(c, expected, next, changes) + } + return fmt.Errorf("%w: CheckCommitDelta unavailable", errChunkRemoteCapabilities) +} + // BoundsHeadStep forwards whether the wrapped remote bounds its own HEAD // step (storage.ChunkHeadStepBounder); a remote without it does not. func (r *closeBoundRemote) BoundsHeadStep() bool { diff --git a/seaweed-block/core/storage/chunk_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index ac19aa1526..74e89b4412 100644 --- a/seaweed-block/core/storage/chunk_fake_remote_test.go +++ b/seaweed-block/core/storage/chunk_fake_remote_test.go @@ -1137,3 +1137,14 @@ func crashOwnedMap(s *WALStore) { _ = s.v3.ownedMap.fd.Close() } } + +// CASHeadDelta is CASHead of the current chunk map with changes applied +// (the engine calls CASHead until V4-B; this keeps the fake a whole seam). +func (f *fakeChunkRemote) CASHeadDelta(ctx context.Context, expected chunkHeadVersion, next chunkHead, changes map[uint64]*chunkRef) (uint64, error) { + h, err := f.GetHead(ctx) + if err != nil { + return 0, err + } + next.Chunks = ApplyChunkChanges(h.Chunks, changes) + return f.CASHead(ctx, expected, next) +} diff --git a/seaweed-block/core/storage/chunk_memremote.go b/seaweed-block/core/storage/chunk_memremote.go index a9543e5fa8..53b3c7f4ce 100644 --- a/seaweed-block/core/storage/chunk_memremote.go +++ b/seaweed-block/core/storage/chunk_memremote.go @@ -142,3 +142,35 @@ func (m *MemChunkRemote) Puts() int { } var _ chunkRemote = (*MemChunkRemote)(nil) + +// CASHeadDelta is CASHead of HEAD's chunk map with changes applied (nil: +// the index reads as zeros). The memory remote keeps a flat map, so this is +// a convenience, not a cost bound. The map is built from the HEAD read here; +// CASHead's own generation check refuses it if HEAD moved since. +func (m *MemChunkRemote) CASHeadDelta(ctx context.Context, expected chunkHeadVersion, next chunkHead, changes map[uint64]*chunkRef) (uint64, error) { + if err := ctx.Err(); err != nil { + return 0, err + } + m.mu.Lock() + next.Chunks = ApplyChunkChanges(m.head.Chunks, changes) + m.mu.Unlock() + return m.CASHead(ctx, expected, next) +} + +// ApplyChunkChanges returns base with changes applied: a changed index set +// to its new reference, or removed where the change is nil (zeros). base is +// not modified. +func ApplyChunkChanges(base map[uint64]chunkRef, changes map[uint64]*chunkRef) map[uint64]chunkRef { + out := make(map[uint64]chunkRef, len(base)+len(changes)) + for i, r := range base { + out[i] = r + } + for i, r := range changes { + if r == nil { + delete(out, i) + } else { + out[i] = *r + } + } + return out +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 3dba8a708b..535fd05dfe 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -234,11 +234,20 @@ func chunkHeadIsDetached(h chunkHead) bool { return h.State == chunkHeadDetached // writes belongs to the session until CASHead commits it. // - Abort is the notice that a cut ended without a commit. It never // blocks: the remote rolls the session back at its next HEAD read. +// +// CASHeadDelta is CASHead by change (cost table K3): next carries HEAD's new +// identity (epoch, holder, position, state; its Chunks are ignored), and +// changes the chunks that differ from the HEAD expected names, by index +// (nil: the index now reads as zeros). The remote reads, builds and checks +// only what the change touches; the resulting HEAD is the one CASHead of the +// whole new chunk map would install. Until the engine keeps no flat map +// (V4-B), it still calls CASHead, which V4-B removes. type chunkRemote interface { Put(ctx context.Context, key string, data []byte) error Get(ctx context.Context, key string) ([]byte, error) GetHead(ctx context.Context) (chunkHead, error) CASHead(ctx context.Context, expected chunkHeadVersion, next chunkHead) (uint64, error) + CASHeadDelta(ctx context.Context, expected chunkHeadVersion, next chunkHead, changes map[uint64]*chunkRef) (uint64, error) Delete(ctx context.Context, key string) error Begin(ctx context.Context) (string, error) Abort() @@ -250,6 +259,9 @@ type chunkRemote interface { // the same next skips that check. type chunkCommitChecker interface { CheckCommit(ctx context.Context, expected chunkHeadVersion, next chunkHead) error + // CheckCommitDelta is CheckCommit of the commit by change CASHeadDelta + // makes with the same arguments. + CheckCommitDelta(ctx context.Context, expected chunkHeadVersion, next chunkHead, changes map[uint64]*chunkRef) error } // chunkHeadStepBounder is a chunkRemote whose CASHead bounds its own HEAD