Merge pull request #866 from seaweedfs/feat/v4b-pr3a

V4-B 3a: HEAD record version 1 with manifest sizes; on v1.1 a cut of a partial chunk fills it
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-12-01 01:26:33 -08:00
commit 4f98d0ef38
19 files changed
+954 -70

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
@@ -58,6 +58,10 @@ type CommitRequest struct {
// Delta, when set, is the commit by change: Prev and Next are unused,
// and the plan builds and checks only the changed shards and the root.
Delta *CommitDelta
// ManifestBytes, when set, is the size of the committed root's manifest
// (the root and every segment it names): HEAD's CurrentBytes after the
// commit, and the named snapshot's size. nil writes neither (unknown).
ManifestBytes *uint64
}
// CommitDelta is a commit by change (cost table K3): HEAD's current root,
@@ -447,7 +451,27 @@ func commitChecked(ctx context.Context, h Head, os ObjectStore, vol string, me H
return Head{}, false, err
}
}
return h.Commit(me, req.Session, plan.root, req.Position, req.Snapshot, req.Meta, req.State)
next, changed, err := h.Commit(me, req.Session, plan.root, req.Position, req.Snapshot, req.Meta, req.State)
if err == nil && changed {
next = next.withManifestBytes(req.Snapshot, req.ManifestBytes)
}
return next, changed, err
}
// withManifestBytes records the committed root's manifest size: HEAD's
// CurrentBytes (nil: unknown, also when an earlier commit knew it), and the
// size of the snapshot this commit named, written once.
func (h Head) withManifestBytes(snapshot string, size *uint64) Head {
h = h.clone() // the snapshot map is shared with the HEAD it came from
if size != nil && h.Version < HeadVersion1 {
h.Version = HeadVersion1 // the sizes are v1.1 fields
}
h.CurrentBytes = cloneSize(size)
if s, ok := h.Snapshots[snapshot]; snapshot != "" && ok && s.ManifestBytes == nil {
s.ManifestBytes = cloneSize(size)
h.Snapshots[snapshot] = s
}
return h
}
// commitVerifyParallel bounds the object lookups one commit runs at once.
@@ -15,8 +15,11 @@
"current": "Head.Current (including nil)",
"position": "Head.Position",
"state": "Head.State",
"snapshots": "Snapshot name membership and each entry Root, Position, Meta; excludes Dependents of retained entries",
"snapshots[].Dependents": "Dependents of retained snapshot entries, including target name, target id and root; excludes snapshot membership and other snapshot fields"
"snapshots": "Snapshot name membership and each entry Root, Position, Meta, ManifestBytes (written once, when the entry is named); excludes Dependents of retained entries",
"snapshots[].Dependents": "Dependents of retained snapshot entries, including target name, target id and root; excludes snapshot membership and other snapshot fields",
"version": "Head.Version (0 absent: the v1.0 format; 1: v1.1)",
"current_bytes": "Head.CurrentBytes, the manifest size of Current (including nil: unknown)",
"ext": "Head.Ext, the v1.1 extension object, written back verbatim by every writer that does not own an entry in it"
},
"notes": [
"snapshots removal includes removal of its empty dependent list; snapshots with dependents cannot be removed.",
@@ -40,7 +43,10 @@
"position",
"state",
"snapshots",
"snapshots[].Dependents"
"snapshots[].Dependents",
"version",
"current_bytes",
"ext"
]
},
{
@@ -90,7 +96,9 @@
"position",
"activity",
"state",
"snapshots"
"snapshots",
"version",
"current_bytes"
]
},
{
@@ -99,7 +107,9 @@
"may_change": [
"current",
"activity",
"snapshots"
"snapshots",
"version",
"current_bytes"
]
},
{
@@ -178,7 +188,10 @@
"position",
"state",
"snapshots",
"snapshots[].Dependents"
"snapshots[].Dependents",
"version",
"current_bytes",
"ext"
]
}
]
@@ -49,6 +49,11 @@ type Snapshot struct {
Position uint64
Meta SnapshotMeta
Dependents []Dependent
// ManifestBytes is the size of the snapshot's manifest (its root and
// every segment the root names), written once by the commit that named
// it. nil: unknown (a snapshot named before the field, or by a commit
// that did not know the size); never reported as 0.
ManifestBytes *uint64
}
// The retention classes of a snapshot.
@@ -151,28 +156,61 @@ type Head struct {
Position uint64
Snapshots map[string]Snapshot
State string // StateLive, StateDetached, StateDeleting or StateDeleted
// CurrentBytes is the manifest size of Current (its root and every
// segment it names), kept by each commit (nil: unknown). A commit by
// change updates it from the objects it replaces, with no lookups.
CurrentBytes *uint64
// Version is HEAD's format version: 0 (absent in the bytes) is the v1.0
// format, decoded strictly; HeadVersion1 is v1.1, whose own fields are
// CurrentBytes and snapshots' ManifestBytes, and whose Ext carries every
// later field. A writer keeps the version and Ext it read.
Version int
// Ext is a v1.1 HEAD's extension object, kept as raw bytes and written
// back verbatim (the ext contract: only additive facts that a writer
// keeping them verbatim while it changes the known fields cannot make
// wrong; anything an older writer could break bumps Version instead).
// Omitted when empty in Head's own JSON (status and CLI output), so a
// HEAD without ext reads back without one, never as the bytes null.
Ext json.RawMessage `json:",omitempty"`
}
// HeadVersion1 is the v1.1 HEAD format; MaxHeadVersion the newest this
// binary reads.
const (
HeadVersion1 = 1
MaxHeadVersion = HeadVersion1
)
// ErrHeadNewerVersion refuses a HEAD written by a newer format version: a
// binary too old to read it, not damage. It wraps ErrMalformed, so every
// caller that refuses a malformed HEAD for good (Start among them) refuses
// this one the same way; its text names the cure.
var ErrHeadNewerVersion = fmt.Errorf("%w: HEAD written by a newer version: use a newer binary", ErrMalformed)
type headDoc struct {
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"`
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"`
Ext json.RawMessage `json:"ext,omitempty"`
}
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"`
Dependents []depDoc `json:"dependents,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"`
}
type depDoc struct {
@@ -191,6 +229,26 @@ func validName(field, v string) error {
return nil
}
// checkExt refuses an ext that is not a JSON object in its canonical bytes
// (what Encode writes: compact, HTML-escaped), or one on a v1.0 HEAD. Ext
// is carried as raw bytes and written back unchanged, so only canonical
// bytes round-trip byte for byte.
func checkExt(version int, ext json.RawMessage) error {
if ext == nil {
return nil
}
if version == 0 {
return fmt.Errorf("%w: a v1.0 HEAD carries ext", ErrMalformed)
}
if len(ext) == 0 || ext[0] != '{' || !json.Valid(ext) {
return fmt.Errorf("%w: HEAD ext is not a JSON object", ErrMalformed)
}
if canon, err := json.Marshal(ext); err != nil || !bytes.Equal(canon, ext) {
return fmt.Errorf("%w: HEAD ext is not in its canonical bytes", ErrMalformed)
}
return nil
}
// ErrNoNextPosition: a HEAD position with no room for a next LSN. No
// commit produces it (Commit refuses); a HEAD that already carries one (an
// older or broken writer) is still read, written by every other
@@ -201,6 +259,9 @@ func (h Head) check() error {
if h.VolumeID.IsZero() {
return fmt.Errorf("%w: HEAD without a volume id", ErrMalformed)
}
if err := checkExt(h.Version, h.Ext); err != nil {
return err
}
switch h.State {
case StateLive, StateDetached, StateDeleting, StateDeleted:
default:
@@ -294,14 +355,14 @@ func (h Head) Encode() ([]byte, error) {
if err := h.check(); err != nil {
return nil, err
}
d := headDoc{VolumeID: h.VolumeID.String(), Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID, Activity: h.Activity, Position: h.Position, State: h.State}
d := headDoc{Version: h.Version, VolumeID: h.VolumeID.String(), Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID, Activity: h.Activity, Position: h.Position, State: h.State, CurrentBytes: h.CurrentBytes, Ext: h.Ext}
if h.Current != nil {
d.Current = h.Current.String()
}
if len(h.Snapshots) > 0 {
d.Snapshots = map[string]snapDoc{}
for n, s := range h.Snapshots {
sd := snapDoc{Root: s.Root.String(), Position: s.Position, CreatedNs: s.Meta.CreatedNs, Class: s.Meta.Class, ExpiresNs: s.Meta.ExpiresNs}
sd := snapDoc{Root: s.Root.String(), Position: s.Position, CreatedNs: s.Meta.CreatedNs, Class: s.Meta.Class, ExpiresNs: s.Meta.ExpiresNs, ManifestBytes: s.ManifestBytes}
if len(s.Meta.Labels) > 0 {
sd.Labels = s.Meta.Labels
}
@@ -327,17 +388,36 @@ func DecodeHead(b []byte, gen uint64, volume VolumeID) (Head, error) {
if volume.IsZero() {
return Head{}, errors.New("layout: DecodeHead needs the volume's id from its VOLUME")
}
// The version first, read leniently: a newer version is refused as
// newer, never as malformed. Every known version is then decoded
// strictly (unknown top-level fields refused; v1.1's later fields live
// in ext, kept raw).
var probe struct {
Version int `json:"version"`
}
if err := json.Unmarshal(b, &probe); err != nil {
return Head{}, fmt.Errorf("%w: HEAD: %v", ErrMalformed, err)
}
if probe.Version > MaxHeadVersion {
return Head{}, fmt.Errorf("%w: version %d, this binary reads up to %d", ErrHeadNewerVersion, probe.Version, MaxHeadVersion)
}
if probe.Version < 0 {
return Head{}, fmt.Errorf("%w: HEAD version %d", ErrMalformed, probe.Version)
}
var d headDoc
dec := json.NewDecoder(bytes.NewReader(b))
dec.DisallowUnknownFields()
if err := dec.Decode(&d); err != nil {
return Head{}, fmt.Errorf("%w: HEAD: %v", ErrMalformed, err)
}
if d.Version == 0 && (d.CurrentBytes != nil || d.Ext != nil || snapshotsSized(d.Snapshots)) {
return Head{}, fmt.Errorf("%w: HEAD of the v1.0 format carries v1.1 fields", ErrMalformed)
}
vid, err := ParseVolumeID(d.VolumeID)
if err != nil {
return Head{}, err
}
h := Head{Gen: gen, VolumeID: vid, Epoch: d.Epoch, Holder: d.Holder, ClaimID: d.ClaimID, Activity: d.Activity, Position: d.Position, State: d.State}
h := Head{Gen: gen, VolumeID: vid, Epoch: d.Epoch, Holder: d.Holder, ClaimID: d.ClaimID, Activity: d.Activity, Position: d.Position, State: d.State, CurrentBytes: d.CurrentBytes, Version: d.Version, Ext: d.Ext}
if d.Current != "" {
rn, err := ParseRootName(d.Current)
if err != nil {
@@ -352,7 +432,7 @@ func DecodeHead(b []byte, gen uint64, volume VolumeID) (Head, error) {
if err != nil {
return Head{}, err
}
snap := Snapshot{Root: rn, Position: s.Position, Meta: SnapshotMeta{CreatedNs: s.CreatedNs, Class: s.Class, ExpiresNs: s.ExpiresNs, Labels: s.Labels}}
snap := Snapshot{Root: rn, Position: s.Position, Meta: SnapshotMeta{CreatedNs: s.CreatedNs, Class: s.Class, ExpiresNs: s.ExpiresNs, Labels: s.Labels}, ManifestBytes: s.ManifestBytes}
for _, dep := range s.Dependents {
tid, err := ParseVolumeID(dep.TargetID)
if err != nil {
@@ -453,15 +533,36 @@ func (h Head) clone() Head {
rn := *h.Current
c.Current = &rn
}
c.CurrentBytes = cloneSize(h.CurrentBytes)
if h.Ext != nil {
c.Ext = append(json.RawMessage(nil), h.Ext...)
}
if h.Snapshots != nil {
c.Snapshots = make(map[string]Snapshot, len(h.Snapshots))
for n, s := range h.Snapshots {
c.Snapshots[n] = Snapshot{Root: s.Root, Position: s.Position, Meta: s.Meta.clone(), Dependents: append([]Dependent(nil), s.Dependents...)}
c.Snapshots[n] = Snapshot{Root: s.Root, Position: s.Position, Meta: s.Meta.clone(), Dependents: append([]Dependent(nil), s.Dependents...), ManifestBytes: cloneSize(s.ManifestBytes)}
}
}
return c
}
func snapshotsSized(snaps map[string]snapDoc) bool {
for _, s := range snaps {
if s.ManifestBytes != nil {
return true
}
}
return false
}
func cloneSize(p *uint64) *uint64 {
if p == nil {
return nil
}
v := *p
return &v
}
// ErrPrecondition is returned by HeadStore.Update when HEAD is not at the
// expected generation.
var ErrPrecondition = errors.New("layout: HEAD generation moved")
@@ -31,13 +31,13 @@ func TestMachineReadableHeadCensusNamesExactlyTheTypedCauses(t *testing.T) {
if census.SchemaVersion != 1 {
t.Fatalf("schema=%d", census.SchemaVersion)
}
observable := map[string]bool{"volume_id": true, "epoch": true, "holder": true, "claim_id": true, "activity": true, "current": true, "position": true, "state": true, "snapshots": true, "snapshots[].Dependents": true}
observable := map[string]bool{"volume_id": true, "epoch": true, "holder": true, "claim_id": true, "activity": true, "current": true, "position": true, "state": true, "snapshots": true, "snapshots[].Dependents": true, "version": true, "current_bytes": true, "ext": true}
for field := range census.FieldGroups {
if !observable[field] {
t.Fatalf("unobservable census field %s", field)
}
}
headFields := map[string]bool{"Gen": true, "VolumeID": true, "Epoch": true, "Holder": true, "ClaimID": true, "Activity": true, "Current": true, "Position": true, "Snapshots": true, "State": true}
headFields := map[string]bool{"Gen": true, "VolumeID": true, "Epoch": true, "Holder": true, "ClaimID": true, "Activity": true, "Current": true, "Position": true, "Snapshots": true, "State": true, "Version": true, "CurrentBytes": true, "Ext": true}
typ := reflect.TypeOf(Head{})
for n := 0; n < typ.NumField(); n++ {
if !headFields[typ.Field(n).Name] {
@@ -83,8 +83,8 @@ func TestMachineReadableHeadCensusNamesExactlyTheTypedCauses(t *testing.T) {
func changedCensusGroups(before, after Head) []string {
var out []string
a, b := reflect.ValueOf(before), reflect.ValueOf(after)
jsonKeys := map[string]string{"VolumeID": "volume_id", "Epoch": "epoch", "Holder": "holder", "ClaimID": "claim_id", "Activity": "activity", "Current": "current", "Position": "position", "State": "state"}
for _, name := range []string{"VolumeID", "Epoch", "Holder", "ClaimID", "Activity", "Current", "Position", "State"} {
jsonKeys := map[string]string{"VolumeID": "volume_id", "Epoch": "epoch", "Holder": "holder", "ClaimID": "claim_id", "Activity": "activity", "Current": "current", "Position": "position", "State": "state", "Version": "version", "CurrentBytes": "current_bytes", "Ext": "ext"}
for _, name := range []string{"VolumeID", "Epoch", "Holder", "ClaimID", "Activity", "Current", "Position", "State", "Version", "CurrentBytes", "Ext"} {
if !reflect.DeepEqual(a.FieldByName(name).Interface(), b.FieldByName(name).Interface()) {
out = append(out, jsonKeys[name])
}
@@ -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,180 @@
package layout
import (
"bytes"
"encoding/json"
"errors"
"strings"
"testing"
)
func u64(v uint64) *uint64 { return &v }
// A v1.1 HEAD (version 1) carries its sizes and an ext object kept as raw
// bytes: it decodes, and encodes back to the same bytes (the canonical
// check holds with ext re-emitted verbatim). A v1.0 HEAD's bytes are
// unchanged: no version field is written when the version is 0.
func TestHeadVersion1RoundTripsWithItsExtVerbatim(t *testing.T) {
root := RootName{Hash: Sum([]byte("image"))}
h := idleHead()
h.Current, h.Position = &root, 9
h.Version, h.CurrentBytes = HeadVersion1, u64(4096)
h.Ext = json.RawMessage(`{"later":{"a":1}}`)
h.Snapshots = map[string]Snapshot{"s1": {Root: root, Position: 9, ManifestBytes: u64(4096)}}
b, err := h.Encode()
if err != nil {
t.Fatal(err)
}
if !bytes.HasPrefix(b, []byte(`{"version":1,`)) {
t.Fatalf("a v1.1 HEAD does not start with its version: %s", b)
}
back, err := DecodeHead(b, h.Gen, h.VolumeID)
if err != nil {
t.Fatal(err)
}
if back.Version != HeadVersion1 || back.CurrentBytes == nil || *back.CurrentBytes != 4096 || string(back.Ext) != string(h.Ext) {
t.Fatalf("decoded %+v", back)
}
if s := back.Snapshots["s1"]; s.ManifestBytes == nil || *s.ManifestBytes != 4096 {
t.Fatalf("snapshot size lost: %+v", s)
}
again, err := back.Encode()
if err != nil || !bytes.Equal(again, b) {
t.Fatalf("v1.1 HEAD not canonical after a round trip: %s / %s (%v)", again, b, err)
}
v0 := idleHead()
b0, err := v0.Encode()
if err != nil {
t.Fatal(err)
}
if bytes.Contains(b0, []byte(`"version"`)) || bytes.Contains(b0, []byte(`"ext"`)) || bytes.Contains(b0, []byte(`bytes"`)) {
t.Fatalf("a v1.0 HEAD's bytes changed: %s", b0)
}
}
// Decoding by version: a HEAD of a newer version is refused as newer
// (ErrHeadNewerVersion, which wraps ErrMalformed so every final refusal of
// a malformed HEAD stays final for it, and names a newer binary as the
// cure); a v1.0 HEAD (no version) that
// carries a v1.1 field is malformed; a known version still refuses an
// unknown top-level field (later fields go in ext).
func TestHeadDecodeByVersion(t *testing.T) {
root := RootName{Hash: Sum([]byte("image"))}
h := idleHead()
h.Current, h.Position = &root, 9
h.Version, h.CurrentBytes = HeadVersion1, u64(10)
b, err := h.Encode()
if err != nil {
t.Fatal(err)
}
newer := bytes.Replace(b, []byte(`{"version":1,`), []byte(`{"version":2,`), 1)
if _, err := DecodeHead(newer, 1, h.VolumeID); !errors.Is(err, ErrHeadNewerVersion) || !errors.Is(err, ErrMalformed) {
t.Fatalf("a newer HEAD: %v; want ErrHeadNewerVersion, wrapping ErrMalformed", err)
}
v0WithSize := bytes.Replace(b, []byte(`{"version":1,`), []byte(`{`), 1)
if _, err := DecodeHead(v0WithSize, 1, h.VolumeID); !errors.Is(err, ErrMalformed) {
t.Fatalf("a v1.0 HEAD with a v1.1 field: %v; want ErrMalformed", err)
}
unknownTop := bytes.Replace(b, []byte(`{"version":1,`), []byte(`{"version":1,"surprise":1,`), 1)
if _, err := DecodeHead(unknownTop, 1, h.VolumeID); !errors.Is(err, ErrMalformed) {
t.Fatalf("an unknown top-level field in a v1.1 HEAD: %v; want ErrMalformed (later fields live in ext)", err)
}
if msg := ErrHeadNewerVersion.Error(); !strings.Contains(msg, "written by a newer version: use a newer binary") || strings.Contains(msg, "corrupt") {
t.Fatal("the newer-version refusal does not say so")
}
}
// A commit that knows its manifest size writes it as HEAD's CurrentBytes and
// as the size of the snapshot it names, and makes HEAD v1.1. A commit that
// does not know it writes neither and leaves a v1.0 HEAD at v1.0. A replay
// changes nothing.
func TestCommitRecordsTheManifestSize(t *testing.T) {
root := RootName{Hash: Sum([]byte("image"))}
open := func() Head {
h := idleHead()
h.State = StateLive
h.Activity = Activity{Kind: ActSnap, Session: "s"}
return h
}
me := HolderID{Holder: "srv-a", Epoch: 3, ClaimID: "k-a"}
next, changed, err := open().Commit(me, "s", root, 9, "snap", SnapshotMeta{}, StateLive)
if err != nil || !changed {
t.Fatal(err)
}
sized := next.withManifestBytes("snap", u64(777))
if sized.Version != HeadVersion1 || sized.CurrentBytes == nil || *sized.CurrentBytes != 777 {
t.Fatalf("sized commit: %+v", sized)
}
if s := sized.Snapshots["snap"]; s.ManifestBytes == nil || *s.ManifestBytes != 777 {
t.Fatalf("the named snapshot's size: %+v", s)
}
unsized := next.withManifestBytes("snap", nil)
if unsized.Version != 0 || unsized.CurrentBytes != nil || unsized.Snapshots["snap"].ManifestBytes != nil {
t.Fatalf("a commit that does not know the size: %+v", unsized)
}
// Written once: a later size never rewrites a snapshot's.
again := sized.withManifestBytes("snap", u64(999))
if s := again.Snapshots["snap"]; *s.ManifestBytes != 777 {
t.Fatalf("a snapshot's size was rewritten: %d", *s.ManifestBytes)
}
}
// Ext is a JSON object in its canonical bytes, so it round-trips byte for
// byte: a HEAD whose ext is not an object, or not canonical (spacing, an
// unescaped character Encode would escape), is refused on decode and on
// encode, never rewritten into other bytes.
func TestHeadExtIsACanonicalObject(t *testing.T) {
root := RootName{Hash: Sum([]byte("image"))}
h := idleHead()
h.Current, h.Position = &root, 9
h.Version, h.Ext = HeadVersion1, json.RawMessage(`{"a":1}`)
b, err := h.Encode()
if err != nil {
t.Fatal(err)
}
for name, ext := range map[string]string{
"an array": `[1]`,
"a string": `"x"`,
"spaced": `{ "a":1}`,
"not escaped": `{"a":"<"}`,
} {
bad := bytes.Replace(b, []byte(`"ext":{"a":1}`), []byte(`"ext":`+ext), 1)
if _, err := DecodeHead(bad, 1, h.VolumeID); !errors.Is(err, ErrMalformed) {
t.Fatalf("decode, ext %s: %v; want ErrMalformed", name, err)
}
e := h
e.Ext = json.RawMessage(ext)
if _, err := e.Encode(); !errors.Is(err, ErrMalformed) {
t.Fatalf("encode, ext %s: %v; want ErrMalformed", name, err)
}
}
}
// Head's own JSON (status and CLI output, not the HEAD codec) round-trips
// to a HEAD that still encodes: a v1.0 HEAD has no ext there, never the
// bytes null, and a v1.1 HEAD keeps its ext.
func TestHeadJSONRoundTripKeepsTheExt(t *testing.T) {
root := RootName{Hash: Sum([]byte("image"))}
v1 := idleHead()
v1.Current, v1.Position = &root, 9
v1.Version, v1.CurrentBytes, v1.Ext = HeadVersion1, u64(10), json.RawMessage(`{"a":1}`)
for name, h := range map[string]Head{"v1.0": idleHead(), "v1.1": v1} {
raw, err := json.Marshal(h)
if err != nil {
t.Fatal(err)
}
var back Head
if err := json.Unmarshal(raw, &back); err != nil {
t.Fatal(err)
}
want, err := h.Encode()
if err != nil {
t.Fatal(err)
}
got, err := back.Encode()
if err != nil || !bytes.Equal(got, want) {
t.Fatalf("%s: Head JSON %s encodes to %s, %v; want %s", name, raw, got, err, want)
}
}
}
@@ -0,0 +1,148 @@
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)
}
}
// A commit by change that touches a shard but leaves its segment unchanged
// (a replacement equal to the ref it replaces) keeps that segment: the size
// takes out only the segments the new root no longer names. Mixed witness:
// shard 0 touched and unchanged, shard 1 changed.
func TestACommitByChangeKeepsAnUnchangedTouchedSegmentInTheSize(t *testing.T) {
withManifestSizes(t, true)
ctx, _, r, h1 := threeShardVolume(t)
same, ok := h1.Chunks[7]
if !ok {
t.Fatal("setup: no chunk 7 in HEAD")
}
changed := putChunk(t, ctx, r, layout.ShardSize+9, "second")
changes := map[uint64]*storage.ChunkRef{7: &same, layout.ShardSize + 9: &changed}
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, want := currentSize(t, ctx, r)
if h.CurrentBytes == nil || *h.CurrentBytes != want {
t.Fatalf("size %v, want %d (the sum of the manifest's objects)", h.CurrentBytes, want)
}
}
@@ -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,77 @@ 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 shard, seg := range d.Prev {
// A touched shard whose segment came out unchanged is still named
// by the new root: it stays in the size (and is not in the plan's
// new segments either).
if name, kept := plan.RootObject().Segments[shard]; kept && name == d.BaseRoot.Segments[shard] {
continue
}
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 +1081,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,
}
}
@@ -28,6 +28,7 @@ func TestFinalLayoutStartRefusalTable(t *testing.T) {
{"foreign volume", layout.ErrIdentity, true},
{"corrupt store", layout.ErrCorrupt, true},
{"malformed store", layout.ErrMalformed, true},
{"HEAD of a newer version", layout.ErrHeadNewerVersion, true},
{"missing VOLUME", layout.ErrMissing, true},
{"oversized HEAD", layout.ErrHeadTooLarge, true},
{"legacy store", chunkstore.ErrLegacyStore, true},
@@ -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)
}
}
@@ -520,11 +520,26 @@ func (l *chunkLayerImpl) readLocalBlock(lba uint64, w *cutCOWWindow, dst []byte)
// fillMissing completes a COW capture: the blocks listed missing get the cut's
// base HEAD bytes. It runs after the local entry is released, bounded by
// ReadMissTimeout and the owning cut's cancellation.
//
// On the v1.1 format the fetched HEAD bytes also fill the chunk (M1): they
// are installed beneath every block with a local version, the absence is
// resolved and the record gets its Fill (P to U, held until the store's
// batched mark), so the cut's Hash meets U and a later cut finds the chunk
// local and clean once committed. A fill that no longer belongs to the
// absence installs nothing and leaves the chunk P (the scratch exemption).
func (l *chunkLayerImpl) fillMissing(ctx context.Context, base map[uint64]chunkRef, idx uint64, data []byte, missing []uint64) ([]byte, error) {
ref, ok := base[idx]
if !ok {
return nil, fmt.Errorf("storage: cut chunk %d: lazily absent blocks but HEAD has no chunk", idx)
}
fill := l.shadow != nil && l.shadow.v11
var gen, version uint64
if fill {
l.stMu.Lock()
fill = l.absent[idx] && l.head.Chunks[idx] == ref
gen, version = l.absentGen[idx], l.chunkVersion(idx)
l.stMu.Unlock()
}
ctx, cancel := context.WithTimeout(ctx, l.cfg.ReadMissTimeout)
defer cancel()
head, err := l.remote.Get(ctx, ref.Key)
@@ -538,6 +553,11 @@ func (l *chunkLayerImpl) fillMissing(ctx context.Context, base map[uint64]chunkR
for _, i := range missing {
copy(out[int(i)*l.blockSize:int(i+1)*l.blockSize], head[int(i)*l.blockSize:int(i+1)*l.blockSize])
}
if fill {
if _, err := l.installFill(idx, gen, version, ref, head); err != nil {
return nil, fmt.Errorf("storage: cut chunk %d fill: %w", idx, err)
}
}
return out, nil
}
+21 -7
View File
@@ -466,7 +466,8 @@ func (l *chunkLayerImpl) OnExtentWrite(lba uint64, lsn uint64) {
if l.absent[idx] {
l.localBlocks[lba] = true
l.presenceVer++
if sh := l.shadow; sh != nil && l.chunkLocalLocked(idx) {
// On v1.1 the write's own event carries the store's bits (noteMutation).
if sh := l.shadow; sh != nil && !sh.v11 && l.chunkLocalLocked(idx) {
sh.landed(idx)
}
}
@@ -552,7 +553,11 @@ func (l *chunkLayerImpl) recoveredLocked(sh *chunkRecordShadow) {
continue
}
cov := "all"
if l.absent[idx] {
if l.absent[idx] && sh.v11 {
// The store's bits (durable, or WAL-backed), never the engine's
// view: a fill not yet marked is not local after a crash.
cov = localBitsArg(l.s.v3.mapEntries.at(int(idx)).Local)
} else if l.absent[idx] {
n, total := uint64(0), uint64(0)
for i := uint64(0); i < l.chunkBlocks; i++ {
b := idx*l.chunkBlocks + i
@@ -686,11 +691,6 @@ func (l *chunkLayerImpl) OnReadMiss(lba uint64) ([]byte, error) {
// current absence (generation and HEAD ref unchanged). It reports whether
// it resolved the absence.
func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chunkRef) (bool, error) {
// current reports whether this fill still belongs to the chunk's present
// absence: same generation, same HEAD ref. Caller holds stMu.
current := func() bool {
return l.absent[idx] && l.absentGen[idx] == gen && l.head.Chunks[idx] == ref
}
// Read with the end check's lock: a mutation bumps the version after its
// dirty-map insert, so one that lands during the fill changes it.
l.stMu.Lock()
@@ -703,6 +703,20 @@ func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chun
if sha256.Sum256(data) != ref.SHA256 || len(data) != int(l.chunkBlocks)*l.blockSize {
return false, fmt.Errorf("storage: chunk %d fetch: %w", idx, errChunkContentMismatch)
}
return l.installFill(idx, gen, version, ref, data)
}
// installFill installs a fetched, verified chunk version: every block with
// no newer local version, as long as the fill still belongs to the chunk's
// current absence (generation and HEAD ref unchanged), and then resolves
// the absence (the record's Fill). version is the chunk's mutation version
// read before the fetch. It reports whether it resolved the absence.
func (l *chunkLayerImpl) installFill(idx, gen, version uint64, ref chunkRef, data []byte) (bool, error) {
// current reports whether this fill still belongs to the chunk's present
// absence: same generation, same HEAD ref. Caller holds stMu.
current := func() bool {
return l.absent[idx] && l.absentGen[idx] == gen && l.head.Chunks[idx] == ref
}
first := idx * l.chunkBlocks
for i := uint64(0); i < l.chunkBlocks; i++ {
b := first + i
@@ -46,9 +46,11 @@ func shadowDefects(l *chunkLayerImpl) int {
// extent directly, and a flushed WAL write does not land that way on v3.
// Writing every block and flushing leaves P; a cut of it is a scratch cut
// (M1): no Hash, no Commit, no refusal.
// - Blocks landing directly (a BASE block) fill the bitmap: P while it is
// partial, U on the last block (never all from one block). Mutant (E1b
// removed): the chunk stays P.
// - Blocks landing directly (a BASE block) fill the bitmap: on v1.0, P
// while it is partial, U on the last block (never all from one block);
// mutant (E1b removed): the chunk stays P. On v1.1 the engine's bitmap
// is never an event's coverage (ChunkStateK3 write_engine_view): the
// chunk stays P until the BASE completion's Changed(all).
func TestShadowWriteCoverageFollowsTheStoreBitmap(t *testing.T) {
s, l, _ := lazyFreshVolume(t)
const idx = 1
@@ -84,7 +86,7 @@ func TestShadowWriteCoverageFollowsTheStoreBitmap(t *testing.T) {
for i := uint64(0); i < ctChunkBlocks; i++ {
l.OnExtentWrite(base*ctChunkBlocks+i, 0) // a block landing directly
want := chunkkernel.Partial
if i == ctChunkBlocks-1 {
if i == ctChunkBlocks-1 && !l.shadow.v11 {
want = chunkkernel.Unknown
}
if k := shadowKind(l, base); k != want {
@@ -0,0 +1,125 @@
package storage
import (
"bytes"
"testing"
"github.com/seaweedfs/seaweed-block/core/chunkkernel"
)
// M1 on the v1.1 format (ChunkStateK3 FillInstall, MarkDurable; mutants
// hash_partial, page_before_mark): a cut of a partial chunk (one block
// written, the rest only in HEAD) also fills it. The HEAD bytes the cut
// fetched are installed beneath the local write, the absence is resolved,
// and the record's Fill makes the chunk U before the cut's Hash (never Hash
// on P), so the commit leaves it HP. Its page shows P, the state before the
// fill, until the store's batched mark. A second cut compares and uploads
// nothing more, and the chunk reads locally with its write and HEAD's bytes.
func TestV11ACutOfAPartialChunkFillsIt(t *testing.T) {
s, path, l, f := v11LazyVolume(t)
const idx = 3
written := makeBlock(ctBlockSize, 0xD1)
if _, err := s.Write(idx*ctChunkBlocks+1, written); err != nil {
t.Fatal(err)
}
if k := shadowKind(l, idx); k != chunkkernel.Partial {
t.Fatalf("setup: %s, want P", k)
}
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
l.stMu.Lock()
absent := l.absent[idx]
l.stMu.Unlock()
l.shadow.mu.Lock()
_, scratch := l.shadow.scratchP[idx]
l.shadow.mu.Unlock()
if absent || scratch {
t.Fatalf("after the cut: absent %v, scratch %v; want the chunk filled", absent, scratch)
}
if k := shadowKind(l, idx); k != chunkkernel.HashPublished {
t.Fatalf("after the cut: %s, want HP (Fill, then Hash and Commit)", k)
}
if n := shadowDefects(l); n != 0 {
t.Fatalf("%d shell events refused", n)
}
if err := l.shadow.rec.Flush(); err != nil {
t.Fatal(err)
}
if k := pageState(t, path, l.numChunks, idx); k != chunkkernel.Partial {
t.Fatalf("page before the mark: %s, want P (the state before the fill)", k)
}
if err := l.markFills(l.shadow); err != nil {
t.Fatal(err)
}
if err := l.shadow.rec.Flush(); err != nil {
t.Fatal(err)
}
if k := pageState(t, path, l.numChunks, idx); k != chunkkernel.HashPublished {
t.Fatalf("page after the mark: %s, want HP", k)
}
before := f.stats()
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
for i := uint32(0); i < ctChunkBlocks; i++ {
got, err := s.Read(idx*ctChunkBlocks + i)
if err != nil {
t.Fatal(err)
}
want := makeBlock(ctBlockSize, byte(0x40+idx*ctChunkBlocks+i))
if i == 1 {
want = written
}
if !bytes.Equal(got, want) {
t.Fatalf("block %d of the filled chunk: wrong bytes", i)
}
}
if after := f.stats(); after.puts != before.puts || after.gets != before.gets {
t.Fatalf("second cut and reads: %d puts, %d gets; want none (the chunk is local and clean)", after.puts-before.puts, after.gets-before.gets)
}
}
// The run-time Changed takes an absent chunk's coverage from the store's
// bits, never from the engine's view (ChunkStateK3 changed_engine_view: the
// engine's bitmap may say local what a crash would not keep). The engine is
// made to say every block local while the store's bits hold one written
// block: Recover's Changed must give P (some), not U.
func TestV11RunTimeChangedTakesTheStoreBits(t *testing.T) {
s, _, l, _ := v11LazyVolume(t)
const idx = 3
if _, err := s.Write(idx*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xD1)); err != nil {
t.Fatal(err)
}
l.stMu.Lock()
for i := uint64(0); i < ctChunkBlocks; i++ {
l.localBlocks[idx*ctChunkBlocks+i] = true
}
l.stMu.Unlock()
s.mu.Lock()
l.noteAllMutated()
s.mu.Unlock()
if k := shadowKind(l, idx); k != chunkkernel.Partial {
t.Fatalf("Changed over one store bit with the engine saying all: %s, want P", k)
}
}
// A block landing in the extent of an absent chunk is not a Write with the
// engine bitmap's coverage on v1.1 (ChunkStateK3 write_engine_view): the
// write's own event already carried the store's bits. Every block of a
// chunk landing directly leaves it P; the BASE completion's Changed(all)
// is what makes it U (TestShadowBaseInstallCompletingChangesEveryChunk).
func TestV11ALandingIsNotAWriteFromTheEngineBitmap(t *testing.T) {
_, _, l, _ := v11LazyVolume(t)
const idx = 2
for i := uint64(0); i < ctChunkBlocks; i++ {
l.OnExtentWrite(idx*ctChunkBlocks+i, 0)
}
if k := shadowKind(l, idx); k != chunkkernel.Partial {
t.Fatalf("every block landed directly: %s, want P", k)
}
if n := shadowDefects(l); n != 0 {
t.Fatalf("%d shell events refused", n)
}
}
@@ -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 }
+35
View File
@@ -45,3 +45,38 @@ 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 with "HEAD written
by a newer version: use a newer binary". That refusal is a kind of malformed
HEAD, so every final refusal of a malformed HEAD (a holder's Start among them)
stays final for it, with no retry loop. Known top-level fields stay strict; a v1.0 record carrying a
v1.1 field is malformed.
Upgrade order: every build from this version on reads a version-1 HEAD, but
only a data plane on the draft v1.1 store format writes one; release builds
keep writing version 0. A v1.0.x binary decodes HEAD strictly and refuses a
version-1 record as malformed (it fails closed, it never rewrites it), so
every reader of a volume, the control plane included, must run a
version-aware build before any v1.1 writer touches that volume.
The ext contract: a v1.1 HEAD may carry one `ext` object, in its canonical
bytes (compact JSON, as HEAD is encoded), which every writer keeps and
re-emits byte for byte while it changes the known fields. An ext that is not
an object, or not canonical, makes the record malformed. 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, which Encode
enforces. With the holder, claim, session and volume names at 64 bytes, the
fullest v1.1 HEAD the other bounds allow is about 28 KiB; those names have no
HEAD bound of their own, so this is a sizing check, not a proof.