chunkstore: keep the manifest size through commits; list it per snapshot

On the v1.1 format a full commit writes the sum of its root and segments
as HEAD's current_bytes and the named snapshot's manifest_bytes. A commit
by change subtracts the base root and the replaced segments and adds the
new ones, with no lookups; an unknown size stays unknown. Snapshot
listings report manifestBytes, null when unknown. The format doc states
the ext contract; a test bounds the fullest HEAD under the inline limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-30 23:30:43 -08:00
1 parent ac85a9dc2b
commit e4e34c26a6
10 files changed
+399 -41

No files matched your search

@@ -108,23 +108,26 @@ type Parent struct {
// SnapshotInfo describes one snapshot, with the field names of the HTTP API
// (spec §3.2-§3.3).
type SnapshotInfo struct {
Root string `json:"root,omitempty"`
Dependents []layout.Dependent `json:"dependents,omitempty"`
VolumeID string `json:"volumeID"`
Name string `json:"name"`
HeadGen uint64 `json:"headGen"`
HeadEpoch uint64 `json:"headEpoch"`
CutLSN uint64 `json:"cutLSN"`
CreatedNs int64 `json:"createdNs"`
State string `json:"state"`
ChunkCount int `json:"chunkCount"`
ManifestBytes int `json:"manifestBytes"`
Consistency string `json:"consistency"`
Labels map[string]string `json:"labels"`
Parent *Parent `json:"parent"`
ExpiresAtNs int64 `json:"expiresAtNs"`
Replayed bool `json:"replayed"`
Class string `json:"class"`
Root string `json:"root,omitempty"`
Dependents []layout.Dependent `json:"dependents,omitempty"`
VolumeID string `json:"volumeID"`
Name string `json:"name"`
HeadGen uint64 `json:"headGen"`
HeadEpoch uint64 `json:"headEpoch"`
CutLSN uint64 `json:"cutLSN"`
CreatedNs int64 `json:"createdNs"`
State string `json:"state"`
ChunkCount int `json:"chunkCount"`
// ManifestBytes is the snapshot's manifest size (its root and every
// segment), written once by the commit that named it; null when unknown
// (a snapshot named before v1.1 recorded it), never 0.
ManifestBytes *uint64 `json:"manifestBytes"`
Consistency string `json:"consistency"`
Labels map[string]string `json:"labels"`
Parent *Parent `json:"parent"`
ExpiresAtNs int64 `json:"expiresAtNs"`
Replayed bool `json:"replayed"`
Class string `json:"class"`
attempt string // the attempt the name resolved to, when read by name
@@ -184,14 +184,14 @@ const (
var ErrHeadNewerVersion = errors.New("layout: HEAD written by a newer version")
type headDoc struct {
Version int `json:"version,omitempty"`
VolumeID string `json:"volume_id"`
Epoch uint64 `json:"epoch"`
Holder string `json:"holder"`
ClaimID string `json:"claim_id,omitempty"`
Activity Activity `json:"activity"`
Current string `json:"current,omitempty"`
Position uint64 `json:"position"`
Version int `json:"version,omitempty"`
VolumeID string `json:"volume_id"`
Epoch uint64 `json:"epoch"`
Holder string `json:"holder"`
ClaimID string `json:"claim_id,omitempty"`
Activity Activity `json:"activity"`
Current string `json:"current,omitempty"`
Position uint64 `json:"position"`
Snapshots map[string]snapDoc `json:"snapshots,omitempty"`
State string `json:"state,omitempty"`
CurrentBytes *uint64 `json:"current_bytes,omitempty"`
@@ -199,12 +199,12 @@ type headDoc struct {
}
type snapDoc struct {
Root string `json:"root"`
Position uint64 `json:"position,omitempty"`
CreatedNs int64 `json:"created_ns,omitempty"`
Class string `json:"class,omitempty"`
ExpiresNs int64 `json:"expires_ns,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
Root string `json:"root"`
Position uint64 `json:"position,omitempty"`
CreatedNs int64 `json:"created_ns,omitempty"`
Class string `json:"class,omitempty"`
ExpiresNs int64 `json:"expires_ns,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
Dependents []depDoc `json:"dependents,omitempty"`
ManifestBytes *uint64 `json:"manifest_bytes,omitempty"`
}
@@ -0,0 +1,72 @@
package layout
import (
"fmt"
"math"
"strings"
"testing"
)
// fullestHead is the largest HEAD the bounds allow: MaxSnapshots snapshots
// whose names and labels are at their byte limits in the character JSON
// escapes widest (a control byte, written as six), MaxDependentsPerHead
// dependents, and the v1.1 sizes at their widest. Volume names, the holder,
// the claim and the session are not bounded by HEAD; 64 bytes each is
// assumed here (the names the catalog writes are far shorter).
func fullestHead(sized bool) Head {
wide := func(n int, tag int) string {
return fmt.Sprintf("%02d", tag) + strings.Repeat("\x01", n-2)
}
root := RootName{Hash: Sum([]byte("image"))}
h := idleHead()
h.Holder, h.ClaimID = wide(64, 0), wide(64, 1)
h.Activity = Activity{Kind: ActSnap, Session: wide(64, 2)}
h.Current, h.Position = &root, math.MaxUint64-1
h.Snapshots = map[string]Snapshot{}
left := MaxDependentsPerHead
for i := 0; i < MaxSnapshots; i++ {
labels := map[string]string{}
for l := 0; l < MaxSnapshotLabels; l++ {
labels[wide(MaxLabelKeyBytes, l)] = wide(MaxLabelValueBytes, l)
}
s := Snapshot{Root: root, Position: math.MaxUint64 - 1, Meta: SnapshotMeta{
CreatedNs: math.MaxInt64, Class: ClassScheduled, ExpiresNs: math.MaxInt64, Labels: labels}}
var targets []string
for d := 0; d < MaxDependents && left > 0; d, left = d+1, left-1 {
targets = append(targets, wide(64, 10*i+d))
}
s.Dependents = deps(root, targets...)
if sized {
s.ManifestBytes = u64(math.MaxUint64)
}
h.Snapshots[wide(MaxSnapshotNameBytes, i)] = s
}
if sized {
h.Version, h.CurrentBytes = HeadVersion1, u64(math.MaxUint64)
}
return h
}
// The v1.1 fields fit HEAD's inline limit with room to spare: the fullest
// HEAD the bounds allow, with every size at its widest, encodes under
// MaxHeadBytes; v1.1 adds at most 512 bytes to it; and at least 16 KiB stays
// free for ext (the ext contract's budget: a writer's own ext must keep the
// fullest HEAD under the limit, which Encode enforces).
func TestTheFullestHeadFitsWithTheV11Sizes(t *testing.T) {
v0, err := fullestHead(false).Encode()
if err != nil {
t.Fatalf("the fullest v1.0 HEAD: %v", err)
}
v1, err := fullestHead(true).Encode()
if err != nil {
t.Fatalf("the fullest v1.1 HEAD: %v", err)
}
added, free := len(v1)-len(v0), MaxHeadBytes-len(v1)
t.Logf("fullest HEAD: v1.0 %d bytes, v1.1 %d (+%d), %d free of %d", len(v0), len(v1), added, free, MaxHeadBytes)
if added > 512 {
t.Fatalf("v1.1 adds %d bytes to the fullest HEAD, want at most 512", added)
}
if free < 16<<10 {
t.Fatalf("the fullest v1.1 HEAD leaves %d bytes, want at least 16 KiB for ext", free)
}
}
@@ -0,0 +1,121 @@
package chunkstore
import (
"context"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// withManifestSizes turns the v1.1 manifest sizes on for one test.
func withManifestSizes(t *testing.T, on bool) {
t.Helper()
prev := manifestSizesV11
manifestSizesV11 = func() bool { return on }
t.Cleanup(func() { manifestSizesV11 = prev })
}
// currentSize recomputes the size HEAD's current manifest has, from all of
// its objects: what the commits must have kept without lookups.
func currentSize(t *testing.T, ctx context.Context, r *LayoutRemote) (layout.Head, uint64) {
t.Helper()
h, _, err := r.st.ReadHead(ctx)
if err != nil {
t.Fatal(err)
}
m, err := r.manifest(ctx, *h.Current)
if err != nil {
t.Fatal(err)
}
root, segs, err := layout.Build(m)
if err != nil {
t.Fatal(err)
}
n, err := manifestSize(root, segs)
if err != nil {
t.Fatal(err)
}
return h, n
}
// On the v1.1 format every commit keeps HEAD's CurrentBytes equal to the
// manifest's real size: the full commit sums every object; a commit by change
// takes the replaced objects out and the new ones in, with no lookups, and
// stays exact (a change in shard 1, then one that empties shard 2). HEAD is
// version 1. On the v1.0 format no size is written and HEAD stays version 0.
func TestCommitsKeepTheManifestSizeExact(t *testing.T) {
t.Run("v1.1", func(t *testing.T) {
withManifestSizes(t, true)
ctx, _, r, h1 := threeShardVolume(t)
h, want := currentSize(t, ctx, r)
if h.Version != layout.HeadVersion1 || h.CurrentBytes == nil || *h.CurrentBytes != want {
t.Fatalf("after the full commit: version %d, size %v, want %d", h.Version, h.CurrentBytes, want)
}
gen, lsn := h1.Gen, uint64(2)
for _, step := range []struct {
name string
changes func() map[uint64]*storage.ChunkRef
}{
{"a change in shard 1", func() map[uint64]*storage.ChunkRef {
ref := putChunk(t, ctx, r, layout.ShardSize+9, "second")
return map[uint64]*storage.ChunkRef{layout.ShardSize + 9: &ref}
}},
{"shard 2 emptied", func() map[uint64]*storage.ChunkRef {
return map[uint64]*storage.ChunkRef{2*layout.ShardSize + 7: nil}
}},
} {
changes := step.changes()
exp := storage.ChunkHeadVersion{Gen: gen, Epoch: 1}
next := storage.ChunkHead{Epoch: 1, RemoteLSN: lsn}
if err := r.CheckCommitDelta(ctx, exp, next, changes); err != nil {
t.Fatal(err)
}
g, err := r.CASHeadDelta(ctx, exp, next, changes)
if err != nil {
t.Fatal(err)
}
gen, lsn = g, lsn+1
h, want := currentSize(t, ctx, r)
if h.CurrentBytes == nil || *h.CurrentBytes != want {
t.Fatalf("%s: size %v, want %d (the sum of the manifest's objects)", step.name, h.CurrentBytes, want)
}
}
})
t.Run("v1.0", func(t *testing.T) {
withManifestSizes(t, false)
ctx, _, r, _ := threeShardVolume(t)
h, _, err := r.st.ReadHead(ctx)
if err != nil {
t.Fatal(err)
}
if h.Version != 0 || h.CurrentBytes != nil {
t.Fatalf("a v1.0-format commit wrote v1.1 fields: version %d, size %v", h.Version, h.CurrentBytes)
}
})
}
// A HEAD with no recorded size (a v1.0 HEAD) stays unknown through commits
// by change: they cannot know the objects they did not replace.
func TestACommitByChangeKeepsAnUnknownSizeUnknown(t *testing.T) {
withManifestSizes(t, false)
ctx, _, r, h1 := threeShardVolume(t) // a v1.0 HEAD: no size
withManifestSizes(t, true)
ref := putChunk(t, ctx, r, layout.ShardSize+9, "second")
changes := map[uint64]*storage.ChunkRef{layout.ShardSize + 9: &ref}
exp := storage.ChunkHeadVersion{Gen: h1.Gen, Epoch: 1}
next := storage.ChunkHead{Epoch: 1, RemoteLSN: 2}
if err := r.CheckCommitDelta(ctx, exp, next, changes); err != nil {
t.Fatal(err)
}
if _, err := r.CASHeadDelta(ctx, exp, next, changes); err != nil {
t.Fatal(err)
}
h, _, err := r.st.ReadHead(ctx)
if err != nil {
t.Fatal(err)
}
if h.CurrentBytes != nil {
t.Fatalf("a commit by change over an unknown size wrote %d", *h.CurrentBytes)
}
}
@@ -545,8 +545,19 @@ func (l *LayoutRemote) prepareCommitLocked(ctx context.Context, expected storage
return layout.Head{}, layout.CommitRequest{}, false, err
}
req.Delta, req.Plan = &d, &plan
} else if err := l.writeRootLocked(ctx, nextM); err != nil {
return layout.Head{}, layout.CommitRequest{}, false, err
if manifestSizesV11() {
if req.ManifestBytes, err = deltaManifestSize(h.CurrentBytes, d, plan); err != nil {
return layout.Head{}, layout.CommitRequest{}, false, err
}
}
} else {
size, err := l.writeRootLocked(ctx, nextM)
if err != nil {
return layout.Head{}, layout.CommitRequest{}, false, err
}
if manifestSizesV11() {
req.ManifestBytes = &size
}
}
if next.State == "detached" {
req.State = layout.StateDetached
@@ -889,15 +900,71 @@ func (l *LayoutRemote) writeDeltaRootLocked(ctx context.Context, plan layout.Com
}
// writeRootLocked writes next's segments and root in this session, so the
// commit finds them prepared.
func (l *LayoutRemote) writeRootLocked(ctx context.Context, next map[uint64]layout.Ref) error {
// commit finds them prepared, and returns the manifest's size (the root and
// every segment it names).
func (l *LayoutRemote) writeRootLocked(ctx context.Context, next map[uint64]layout.Ref) (uint64, error) {
defer storage.MeasureCutWork(ctx, storage.CutSegmentWrites)()
root, segs, err := layout.Build(next)
if err != nil {
return err
return 0, err
}
size, err := manifestSize(root, segs)
if err != nil {
return 0, err
}
_, err = layout.PrepareRoot(ctx, manifestSends{l.st}, root, segs, l.session)
return layoutRemoteErr(err)
return size, layoutRemoteErr(err)
}
// manifestSizesV11 says whether commits write the manifest sizes (v1.1 HEAD
// fields): the build's draft v1.1 format. Tests of this package set it.
var manifestSizesV11 = storage.ChunkV11Format
// manifestSize is the size of a root and the segments given.
func manifestSize(root layout.Root, segs map[layout.SegName][]byte) (uint64, error) {
rb, err := root.Encode()
if err != nil {
return 0, err
}
n := uint64(len(rb))
for _, b := range segs {
n += uint64(len(b))
}
return n, nil
}
// deltaManifestSize is a commit by change's manifest size, from the size
// HEAD names for its base (prev) with no lookups: the base root and the
// replaced segments it already read come out, the new root and the new
// segments go in. With no base every object is new; with an unknown prev
// the size stays unknown (nil) until a full commit.
func deltaManifestSize(prev *uint64, d layout.CommitDelta, plan layout.CommitPlan) (*uint64, error) {
added, err := manifestSize(plan.RootObject(), plan.Segments())
if err != nil {
return nil, err
}
if d.Base == nil {
return &added, nil
}
if prev == nil {
return nil, nil
}
removed, err := manifestSize(d.BaseRoot, nil)
if err != nil {
return nil, err
}
for _, seg := range d.Prev {
b, err := seg.Encode()
if err != nil {
return nil, err
}
removed += uint64(len(b))
}
if removed > *prev {
return nil, nil // HEAD's size cannot have held these objects: unknown
}
size := *prev - removed + added
return &size, nil
}
// manifestSends counts each root and segment object a commit actually sends
@@ -1008,10 +1075,15 @@ func (l *LayoutRemote) CommitPendingSnapshot(ctx context.Context) error {
return err
}
}
if err := l.writeRootLocked(ctx, m); err != nil {
size, err := l.writeRootLocked(ctx, m)
if err != nil {
return err
}
got, err := layout.RunCommit(ctx, l.st, l.st, l.vol.Name, l.me, layout.CommitRequest{Session: l.session, Prev: m, Next: m, Position: h.Position, State: layout.StateLive, Snapshot: p.name, Meta: p.meta}, layout.CauseSnapshotUnchanged)
req := layout.CommitRequest{Session: l.session, Prev: m, Next: m, Position: h.Position, State: layout.StateLive, Snapshot: p.name, Meta: p.meta}
if manifestSizesV11() {
req.ManifestBytes = &size
}
got, err := layout.RunCommit(ctx, l.st, l.st, l.vol.Name, l.me, req, layout.CauseSnapshotUnchanged)
if err != nil {
if snapshotRefusal(err) {
l.pending = nil
@@ -12,5 +12,6 @@ func SnapshotInfoFromHead(volumeID, name string, h layout.Head) SnapshotInfo {
VolumeID: volumeID, Name: name, Root: s.Root.String(), Dependents: s.Dependents,
HeadGen: h.Gen, HeadEpoch: h.Epoch, CutLSN: s.Position, State: SnapActive,
Class: s.Meta.Class, CreatedNs: s.Meta.CreatedNs, ExpiresAtNs: s.Meta.ExpiresNs, Labels: s.Meta.Labels,
ManifestBytes: s.ManifestBytes,
}
}
@@ -185,7 +185,7 @@ type snapshotBody struct {
CutLSN uint64 `json:"cutLSN"`
CreatedNs int64 `json:"createdNs"`
ChunkCount int `json:"chunkCount"`
ManifestBytes int `json:"manifestBytes"`
ManifestBytes *uint64 `json:"manifestBytes"` // null: unknown
Consistency string `json:"consistency"`
Labels map[string]string `json:"labels"`
Replayed bool `json:"replayed"`
@@ -766,7 +766,7 @@ func (c *chunkControl) ListSnapshots(ctx context.Context, volumeID string, opts
out := make([]chunkstore.SnapshotInfo, 0, len(names))
for _, name := range names {
sn := h.Snapshots[name]
out = append(out, chunkstore.SnapshotInfo{VolumeID: volumeID, Name: name, Root: sn.Root.String(), Dependents: sn.Dependents, CreatedNs: sn.Meta.CreatedNs, Class: sn.Meta.Class, ExpiresAtNs: sn.Meta.ExpiresNs, Labels: maps.Clone(sn.Meta.Labels)})
out = append(out, chunkstore.SnapshotInfo{VolumeID: volumeID, Name: name, Root: sn.Root.String(), Dependents: sn.Dependents, CreatedNs: sn.Meta.CreatedNs, Class: sn.Meta.Class, ExpiresAtNs: sn.Meta.ExpiresNs, Labels: maps.Clone(sn.Meta.Labels), ManifestBytes: sn.ManifestBytes})
}
return out, next, nil
}
@@ -0,0 +1,62 @@
package volume
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// A listing reports each snapshot's manifest size as its HEAD record holds
// it: the size the naming commit wrote, or null for a snapshot named before
// the size was recorded (unknown, never 0).
func TestListingReportsTheManifestSizeOrUnknown(t *testing.T) {
ctx := context.Background()
f := &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}}
cat, err := chunkstore.NewBCatalog(f, f, "/chunks")
if err != nil {
t.Fatal(err)
}
id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff")
ref := chunkstore.VolumeRef{Name: "v1", ID: id}
if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
t.Fatal(err)
}
h, _, err := cat.ReadHead(ctx, ref)
if err != nil {
t.Fatal(err)
}
r := layout.RootName{Hash: layout.Sum([]byte("root"))}
size := uint64(4242)
h.Version = layout.HeadVersion1
h.Snapshots = map[string]layout.Snapshot{"new": {Root: r, ManifestBytes: &size}, "old": {Root: r}}
s, _ := cat.Store(ref)
if err := s.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil {
t.Fatal(err)
}
ctl := NewChunkControl(&fakeChunkProvider{}, cat, ref)
list, _, err := ctl.ListSnapshots(ctx, "v1", chunkstore.ListOptions{})
if err != nil || len(list) != 2 {
t.Fatalf("listing: %d entries, %v", len(list), err)
}
got := map[string]*uint64{}
for _, s := range list {
got[s.Name] = s.ManifestBytes
}
if got["new"] == nil || *got["new"] != size {
t.Fatalf("a sized snapshot lists %v, want %d", got["new"], size)
}
if got["old"] != nil {
t.Fatalf("a snapshot named before the size lists %d, want unknown (null)", *got["old"])
}
b, err := json.Marshal(list)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(b), `"manifestBytes":4242`) || !strings.Contains(string(b), `"manifestBytes":null`) {
t.Fatalf("listing JSON: %s", b)
}
}
@@ -5,3 +5,8 @@ package storage
// build's constant; this package's tests turn it on for the tests that
// exercise the format.
var chunkV11Format = chunkV11FormatBuild
// ChunkV11Format reports whether this build (or test) runs the draft v1.1
// format: what a chunk store's HEAD writer uses to decide whether it may
// write v1.1 HEAD fields.
func ChunkV11Format() bool { return chunkV11Format }
+22
View File
@@ -45,3 +45,25 @@ counters after joining workers. The worker queue mutex guards admission and
first error only, with no I/O under it. Failure cancels new admission and joins
all owned calls before clean-abort intent cleanup. A remote ignoring
cancellation can delay that join; it is never reported settled early.
## HEAD record version and ext
The HEAD record's own `version` field is separate from the manifest format
above. Absent (version 0) is the v1.0 record, decoded strictly as before.
Version 1 (v1.1) adds `current_bytes` (the size of the current manifest: its
root and every segment it names) and `manifest_bytes` per snapshot (written
once, by the commit that names it). An absent size is unknown, never 0. A
commit by change keeps `current_bytes` without lookups: it subtracts the base
root and the segments it replaces and adds the new ones; an unknown size stays
unknown. Snapshot listings report `manifestBytes`, null when unknown.
A binary refuses a HEAD with a version newer than it reads as a newer version,
not as damage. Known top-level fields stay strict; a v1.0 record carrying a
v1.1 field is malformed.
The ext contract: a v1.1 HEAD may carry one `ext` object, which every writer
keeps and re-emits byte for byte while it changes the known fields. Ext holds
only additive facts that such a writer cannot make wrong. A fact an older
writer could invalidate by changing a known field without updating it bumps
the version instead. Ext counts toward the 64 KiB inline limit; the fullest
v1.1 HEAD the bounds allow is about 28 KiB, leaving at least 16 KiB for ext.