diff --git a/seaweed-block/core/frontend/chunkstore/layout/delta.go b/seaweed-block/core/frontend/chunkstore/layout/delta.go new file mode 100644 index 0000000000..5fbf160a74 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/delta.go @@ -0,0 +1,135 @@ +package layout + +import ( + "fmt" + "sort" +) + +// A commit by change (cost table K3): the new root is the previous root with +// only the changed shards' segments replaced, each built from that shard's +// previous segment and the changed entries. Nothing here reads, writes or +// visits an unchanged shard, so the work grows with the change, not with the +// volume; the result is the root Build of the whole new manifest would name +// (TestDeltaRootIsBuildsRoot). + +// ApplySegment returns shard's segment after changes: prev's entries, with +// each changed index set to its new reference, or removed where the change +// is nil (the index reads as zeros). prev is the shard's previous segment +// (zero Segment when the shard had none). empty reports a segment with no +// entry left: the shard leaves the root. prev is not modified. +func ApplySegment(prev Segment, shard uint64, changes map[uint64]*Ref) (seg Segment, empty bool, err error) { + if len(prev.Chunks) > 0 && prev.Shard != shard { + return Segment{}, false, fmt.Errorf("%w: previous segment of shard %d given for shard %d", ErrMalformed, prev.Shard, shard) + } + out := Segment{Shard: shard, Chunks: make(map[uint64]Ref, len(prev.Chunks)+len(changes))} + for i, r := range prev.Chunks { + out.Chunks[i] = r + } + for i, r := range changes { + if Shard(i) != shard { + return Segment{}, false, fmt.Errorf("%w: change of chunk %d is not in shard %d", ErrMalformed, i, shard) + } + if r == nil { + delete(out.Chunks, i) + continue + } + if r.Chunk.Index != i { + return Segment{}, false, fmt.Errorf("%w: change at %d names chunk %d", ErrMalformed, i, r.Chunk.Index) + } + out.Chunks[i] = *r + } + return out, len(out.Chunks) == 0, nil +} + +// RootWith returns prev with the given shards' segments replaced: a nil name +// removes the shard (its segment became empty). prev is not modified. +func RootWith(prev Root, segs map[uint64]*SegName) (Root, error) { + out := Root{Segments: make(map[uint64]SegName, len(prev.Segments)+len(segs))} + for sh, n := range prev.Segments { + out.Segments[sh] = n + } + for sh, n := range segs { + if n == nil { + delete(out.Segments, sh) + continue + } + if n.Shard != sh { + return Root{}, fmt.Errorf("%w: segment of shard %d given for shard %d", ErrMalformed, n.Shard, sh) + } + out.Segments[sh] = *n + } + return out, nil +} + +// ChangesByShard groups changes (chunk index -> new reference, nil = zeros) +// by shard, the shards in ascending order. +func ChangesByShard(changes map[uint64]*Ref) ([]uint64, map[uint64]map[uint64]*Ref) { + by := map[uint64]map[uint64]*Ref{} + for i, r := range changes { + sh := Shard(i) + if by[sh] == nil { + by[sh] = map[uint64]*Ref{} + } + by[sh][i] = r + } + shards := make([]uint64, 0, len(by)) + for sh := range by { + shards = append(shards, sh) + } + sort.Slice(shards, func(a, b int) bool { return shards[a] < shards[b] }) + return shards, by +} + +// BuildDelta is Build by change: the root of base's image after changes, and +// the bytes of every segment it names that base does not (the changed +// shards' new segments), keyed by name. prev holds the previous segment of +// every changed shard that base names, and only those; each must be the +// segment base names for its shard (a segment of another root would rebuild +// a shard from the wrong image). +func BuildDelta(base Root, prev map[uint64]Segment, changes map[uint64]*Ref) (Root, map[SegName][]byte, error) { + shards, by := ChangesByShard(changes) + for sh := range prev { + if _, ok := by[sh]; !ok { + return Root{}, nil, fmt.Errorf("%w: previous segment of shard %d, which has no change", ErrMalformed, sh) + } + } + names := map[uint64]*SegName{} + segs := map[SegName][]byte{} + for _, sh := range shards { + p, have := prev[sh] + want, named := base.Segments[sh] + if have != named { + return Root{}, nil, fmt.Errorf("%w: shard %d: previous segment given %v, base names one %v", ErrMalformed, sh, have, named) + } + if have { + n, _, err := NameSegment(p) + if err != nil { + return Root{}, nil, err + } + if n != want { + return Root{}, nil, fmt.Errorf("%w: shard %d: previous segment %s is not the base's %s", ErrMalformed, sh, n, want) + } + } + seg, empty, err := ApplySegment(p, sh, by[sh]) + if err != nil { + return Root{}, nil, err + } + if empty { + names[sh] = nil + continue + } + n, b, err := NameSegment(seg) + if err != nil { + return Root{}, nil, err + } + names[sh] = &n + if !named || n != want { + segs[n] = b + } + } + root, err := RootWith(base, names) + if err != nil { + return Root{}, nil, err + } + return root, segs, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/delta_test.go b/seaweed-block/core/frontend/chunkstore/layout/delta_test.go new file mode 100644 index 0000000000..439dc87c19 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/delta_test.go @@ -0,0 +1,162 @@ +package layout + +import ( + "errors" + "fmt" + "math/rand" + "testing" +) + +// deltaRef is a reference to chunk i of owner o holding version v. +func deltaRef(o string, i uint64, v int) Ref { + return Ref{Owner: o, OwnerID: idFor(o), Chunk: NameChunk(i, []byte(fmt.Sprintf("%s/%d/%d", o, i, v)))} +} + +// applyAll is the whole manifest after changes: the reference model. +func applyAll(prev map[uint64]Ref, changes map[uint64]*Ref) map[uint64]Ref { + out := make(map[uint64]Ref, len(prev)) + for i, r := range prev { + out[i] = r + } + for i, r := range changes { + if r == nil { + delete(out, i) + } else { + out[i] = *r + } + } + return out +} + +// prevSegsOf returns, for each changed shard that base names, its segment +// decoded from Build's bytes: what a remote reads for a commit by change. +func prevSegsOf(t *testing.T, base Root, segs map[SegName][]byte, changes map[uint64]*Ref) map[uint64]Segment { + t.Helper() + out := map[uint64]Segment{} + shards, _ := ChangesByShard(changes) + for _, sh := range shards { + n, ok := base.Segments[sh] + if !ok { + continue + } + s, err := DecodeSegment(segs[n]) + if err != nil { + t.Fatal(err) + } + out[sh] = s + } + return out +} + +// The gate of a commit by change: for random images and random change sets +// (new chunks, rewritten chunks, chunks of another owner, chunks becoming +// zeros, a shard emptied, a shard created), the root built from the previous +// root, the changed shards' previous segments and the changes is the root +// Build of the whole new manifest names, and the new segments are exactly +// Build's segments that the previous root does not name. +func TestDeltaRootIsBuildsRoot(t *testing.T) { + rng := rand.New(rand.NewSource(1)) + const shards = 6 + for round := 0; round < 300; round++ { + prev := map[uint64]Ref{} + for sh := uint64(0); sh < shards; sh++ { + if rng.Intn(4) == 0 { + continue // a shard with no chunk + } + for k := 0; k < 1+rng.Intn(5); k++ { + i := sh*ShardSize + uint64(rng.Intn(50)) + owner := "v" + if rng.Intn(5) == 0 { + owner = "src" + } + prev[i] = deltaRef(owner, i, 0) + } + } + changes := map[uint64]*Ref{} + for k := 0; k < rng.Intn(8); k++ { + i := uint64(rng.Intn(shards))*ShardSize + uint64(rng.Intn(50)) + switch rng.Intn(3) { + case 0: + changes[i] = nil // zeros + default: + r := deltaRef("v", i, 1+round) + changes[i] = &r + } + } + if rng.Intn(10) == 0 { // empty one whole shard + for i := range prev { + if Shard(i) == 2 { + changes[i] = nil + } + } + } + base, baseSegs, err := Build(prev) + if err != nil { + t.Fatal(err) + } + next := applyAll(prev, changes) + wantRoot, wantSegs, err := Build(next) + if err != nil { + t.Fatal(err) + } + got, gotSegs, err := BuildDelta(base, prevSegsOf(t, base, baseSegs, changes), changes) + if err != nil { + t.Fatalf("round %d: %v", round, err) + } + wn, _, _ := NameRoot(wantRoot) + gn, _, _ := NameRoot(got) + if wn != gn { + t.Fatalf("round %d: delta root %s, Build's %s", round, gn, wn) + } + known := map[SegName]bool{} + for _, n := range base.Segments { + known[n] = true + } + for n, b := range wantSegs { + if known[n] { + if _, ok := gotSegs[n]; ok { + t.Fatalf("round %d: delta rewrote unchanged segment %s", round, n) + } + continue + } + if string(gotSegs[n]) != string(b) { + t.Fatalf("round %d: new segment %s missing or different", round, n) + } + } + if len(gotSegs) > len(wantSegs) { + t.Fatalf("round %d: delta wrote %d segments, Build has %d", round, len(gotSegs), len(wantSegs)) + } + } +} + +// The delta refuses a previous segment that is not the base's, one for a +// shard with no change, and a missing one for a shard the base names: each +// would rebuild a shard from another image. +func TestBuildDeltaRefusesAWrongPreviousSegment(t *testing.T) { + a, b := deltaRef("v", 1, 0), deltaRef("v", ShardSize+1, 0) + prev := map[uint64]Ref{1: a, ShardSize + 1: b} + base, segs, err := Build(prev) + if err != nil { + t.Fatal(err) + } + r := deltaRef("v", 2, 1) + changes := map[uint64]*Ref{2: &r} + good := prevSegsOf(t, base, segs, changes) + other := Segment{Shard: 0, Chunks: map[uint64]Ref{1: deltaRef("v", 1, 9)}} + shard1, _ := DecodeSegment(segs[base.Segments[1]]) + for _, c := range []struct { + name string + prev map[uint64]Segment + }{ + {"another image's segment", map[uint64]Segment{0: other}}, + {"a segment of an unchanged shard", map[uint64]Segment{0: good[0], 1: shard1}}, + {"no segment for a shard the base names", map[uint64]Segment{}}, + } { + if _, _, err := BuildDelta(base, c.prev, changes); !errors.Is(err, ErrMalformed) { + t.Fatalf("%s: %v, want ErrMalformed", c.name, err) + } + } + if _, _, err := BuildDelta(base, good, changes); err != nil { + t.Fatalf("the base's own segment: %v", err) + } +}