mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Merge main into bindings verifier
This commit is contained in:
commit
8f639975d3
33 files changed
+1586
-81
No files matched your search
@@ -191,7 +191,9 @@ func fencingRoundHeal(t *testing.T, rejoin bool) {
|
||||
// not ready, and the gate then fences once more and continues r1 at the
|
||||
// next epoch, which is the designed answer to a primary that is not
|
||||
// ready, not a failure of the rejoin.
|
||||
epoch := waitRejoinConverged(t, r1.status, 2, "r2", "r3")
|
||||
epoch := waitRejoinConverged(t, r1.status, 2, func() string {
|
||||
return "r2 log tail:\n" + r2.d.tail(40) + "\nr3 log tail:\n" + r3.d.tail(40)
|
||||
}, "r2", "r3")
|
||||
if epoch > 2 {
|
||||
t.Logf("a further fencing round continued r1 at epoch %d after the pause", epoch)
|
||||
}
|
||||
@@ -210,7 +212,10 @@ func fencingRoundHeal(t *testing.T, rejoin bool) {
|
||||
// peer at that same e, all read in one pass; it returns e. Reading the epoch
|
||||
// once and then waiting for that exact epoch would fail if a further round
|
||||
// moved it in between.
|
||||
func waitRejoinConverged(t *testing.T, statusAddr string, minEpoch uint64, rids ...string) uint64 {
|
||||
// On failure it reports the last answer and dump(), the replicas' own logs:
|
||||
// the primary's answer alone cannot tell a replica that never caught up from
|
||||
// one that never answered.
|
||||
func waitRejoinConverged(t *testing.T, statusAddr string, minEpoch uint64, dump func() string, rids ...string) uint64 {
|
||||
t.Helper()
|
||||
c := &http.Client{Timeout: 5 * time.Second}
|
||||
get := func(path string) []byte {
|
||||
@@ -256,7 +261,7 @@ func waitRejoinConverged(t *testing.T, statusAddr string, minEpoch uint64, rids
|
||||
return st.Epoch
|
||||
}
|
||||
}
|
||||
t.Fatalf("the primary and %v never converged on one epoch >= %d; last answer: %s", rids, minEpoch, last)
|
||||
t.Fatalf("the primary and %v never converged on one epoch >= %d; last answer: %s\n%s", rids, minEpoch, last, dump())
|
||||
return 0
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
// master's volume record, never from a name given plus an id read from
|
||||
// that same directory. A new site fails until it is classified here.
|
||||
var deleteSites = map[string]string{
|
||||
"core/frontend/chunkstore/layout_create.go LayoutStore.CreateVolumeRecord -> VolumeDir": "validation only after a rejected exclusive create: a valid full foreign VOLUME must name the already selected name/id8 directory; TestCreateVolumeExclusiveCollisionRedraws; no directory selection or removal",
|
||||
"core/frontend/chunkstore/startup_head_probe.go BCatalog.cleanStartupProbes -> DeleteEntry": "only exact reserved 32-hex probe directories observed before the full active-probe grace; nonrecursive HEAD and empty directory deletes, no volume directory (TestConditionalHeadNextStartCleansCrashLeftovers)",
|
||||
"core/frontend/chunkstore/startup_head_probe.go BCatalog.checkConditionalHead -> DeleteEntry": "only the disposable HEAD and empty random probe directory after successful exclusive create; no volume directory is used (TestCatalogStartupRequiresWrongGenerationHeadRefusal)",
|
||||
"cmd/sw-block/chunk_verify.go chunkVerify -> VolumeDir": "master-resolved full id and requested name; offline form accepts an explicit directory without discovering an identity",
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -16,6 +16,11 @@ type NewVolumeStore interface {
|
||||
CreateVolumeRecord(ctx context.Context, v Volume) error
|
||||
}
|
||||
|
||||
// ErrDirectoryCollision means an exclusive VOLUME create found a valid,
|
||||
// different full identity in the same name/id8 directory. Only a pending
|
||||
// ordinary create may redraw its identity; readers still refuse the mismatch.
|
||||
var ErrDirectoryCollision = fmt.Errorf("%w: volume directory collision", ErrIdentity)
|
||||
|
||||
// Unclaimed is the first HEAD of a volume: its id, epoch 0, no holder, no
|
||||
// claim id, idle, live, position 0, and current (nil for a new volume, the
|
||||
// copied root for a restore target). The first Start claims it from a
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -86,7 +86,9 @@ func TestVolumeWriterRepositorySites(t *testing.T) {
|
||||
"core/frontend/chunkstore/layout/read.go VolumeID VolumeName": 1,
|
||||
"core/frontend/chunkstore/layout/verify.go volumeID VolumeName": 1,
|
||||
"core/frontend/chunkstore/layout_create.go ReadVolumeRecord VolumeName": 1,
|
||||
"core/frontend/chunkstore/layout_create.go CreateVolumeRecord VolumeName": 1,
|
||||
// One exclusive create plus one read-only collision classification;
|
||||
// TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal pins the latter.
|
||||
"core/frontend/chunkstore/layout_create.go CreateVolumeRecord VolumeName": 2,
|
||||
// Read-only cache discriminator; the distinct-object verifier control
|
||||
// proves VOLUME is observed once while HEAD is confirmed separately.
|
||||
"core/frontend/chunkstore/layout_verify.go VerifyLayout VolumeName": 1,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f := NewMemFiler()
|
||||
cat, _ := NewBCatalog(f, newFakeBlobs(), "/blocks")
|
||||
v := VolumeRef{Name: "v", ID: layout.VolumeID{1}}
|
||||
foreign := v
|
||||
foreign.ID[15] = 2
|
||||
g := layout.Geometry{SizeBytes: 1 << 20, BlockSize: 4096, ChunkBytes: 4 << 20}
|
||||
if _, e := cat.CreateVolume(ctx, foreign, g); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
st, _ := cat.Store(v)
|
||||
if _, _, e := st.ReadVolumeRecord(ctx); !errors.Is(e, layout.ErrIdentity) || errors.Is(e, layout.ErrDirectoryCollision) {
|
||||
t.Fatalf("read allowed redraw: %v", e)
|
||||
}
|
||||
if _, e := cat.CreateVolume(ctx, v, g); !errors.Is(e, layout.ErrDirectoryCollision) || !errors.Is(e, layout.ErrIdentity) {
|
||||
t.Fatalf("collision not classified: %v", e)
|
||||
}
|
||||
// A wrong full identity that does not belong in the selected id8 path is
|
||||
// corruption, not evidence that a new random directory would heal it.
|
||||
wrong := foreign
|
||||
wrong.ID[0] = 3
|
||||
raw, e := (layout.Volume{ID: wrong.ID, Name: wrong.Name, Format: layout.VolumeFormat, Geometry: g}).Encode()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
entry, e := f.LookupEntry(ctx, "/blocks/"+v.Dir(), layout.VolumeName)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
entry.Content = raw
|
||||
if e = f.UpdateEntry(ctx, "/blocks/"+v.Dir(), entry, nil); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = cat.CreateVolume(ctx, v, g); !errors.Is(e, layout.ErrIdentity) || errors.Is(e, layout.ErrDirectoryCollision) {
|
||||
t.Fatalf("corruption allowed redraw: %v", e)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
@@ -94,6 +95,19 @@ func (s *LayoutStore) CreateVolumeRecord(ctx context.Context, v layout.Volume) e
|
||||
e.Extended = map[string][]byte{layoutKind: []byte("volume"), layoutVolume: []byte(s.id.String())}
|
||||
err = s.f.CreateEntry(ctx, s.root, e, true)
|
||||
if errors.Is(err, ErrExists) {
|
||||
// Classify only the rejected exclusive VOLUME create, before any
|
||||
// HEAD write. An ordinary read keeps the full-identity refusal.
|
||||
existing, readErr := s.f.LookupEntry(ctx, s.root, layout.VolumeName)
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
got, decodeErr := layout.DecodeVolume(existing.Content)
|
||||
if decodeErr != nil {
|
||||
return fmt.Errorf("%w: VOLUME: %v", layout.ErrCorrupt, decodeErr)
|
||||
}
|
||||
if got.ID != v.ID && got.Name == v.Name && layout.VolumeDir(got.Name, got.ID) == path.Base(s.root) {
|
||||
return layout.ErrDirectoryCollision
|
||||
}
|
||||
return layout.ErrExists
|
||||
}
|
||||
return err
|
||||
|
||||
@@ -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},
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type safetyFiler struct {
|
||||
*chunkstore.MemFiler
|
||||
entries map[string][]byte
|
||||
writes int
|
||||
}
|
||||
|
||||
func (f *safetyFiler) CreateEntry(c context.Context, d string, e *filerpb.Entry, x bool) error {
|
||||
err := f.MemFiler.CreateEntry(c, d, e, x)
|
||||
if err == nil {
|
||||
b, _ := proto.MarshalOptions{Deterministic: true}.Marshal(e)
|
||||
f.entries[d+"/"+e.Name] = b
|
||||
f.writes++
|
||||
}
|
||||
return err
|
||||
}
|
||||
func (f *safetyFiler) UpdateEntry(c context.Context, d string, e *filerpb.Entry, x map[string][]byte) error {
|
||||
err := f.MemFiler.UpdateEntry(c, d, e, x)
|
||||
if err == nil {
|
||||
b, _ := proto.MarshalOptions{Deterministic: true}.Marshal(e)
|
||||
f.entries[d+"/"+e.Name] = b
|
||||
f.writes++
|
||||
}
|
||||
return err
|
||||
}
|
||||
func (f *safetyFiler) DeleteEntry(c context.Context, d, n string, x map[string][]byte) error {
|
||||
err := f.MemFiler.DeleteEntry(c, d, n, x)
|
||||
if err == nil {
|
||||
delete(f.entries, d+"/"+n)
|
||||
f.writes++
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type safetyBlobs struct {
|
||||
data map[string][]byte
|
||||
puts int
|
||||
}
|
||||
|
||||
func (b *safetyBlobs) Put(_ context.Context, d []byte) (string, error) {
|
||||
b.puts++
|
||||
id := fmt.Sprint(b.puts)
|
||||
b.data[id] = append([]byte(nil), d...)
|
||||
return id, nil
|
||||
}
|
||||
func (b *safetyBlobs) Get(_ context.Context, id string) ([]byte, error) {
|
||||
d, ok := b.data[id]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("missing %s", id)
|
||||
}
|
||||
return append([]byte(nil), d...), nil
|
||||
}
|
||||
|
||||
type safetyLease struct{}
|
||||
|
||||
func (safetyLease) OldLeaseEnded(context.Context, uint64) error { return nil }
|
||||
func safetyDigest(m map[string][]byte) string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
h := sha256.New()
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(h, "%d:%s:%d:", len(k), k, len(m[k]))
|
||||
h.Write(m[k])
|
||||
}
|
||||
return fmt.Sprintf("%x", h.Sum(nil))
|
||||
}
|
||||
|
||||
func TestCollisionExistingVolumeSafety(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
defer cancel()
|
||||
h := newTestMaster(t, t.TempDir())
|
||||
defer closeTestMaster(t, h)
|
||||
h.cfg.WorkspaceRPC = true
|
||||
f := &safetyFiler{MemFiler: chunkstore.NewMemFiler(), entries: map[string][]byte{}}
|
||||
b := &safetyBlobs{data: map[string][]byte{}}
|
||||
cat, err := chunkstore.NewBCatalog(f, b, "/collision")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var foreign chunkstore.VolumeRef
|
||||
var g layout.Geometry
|
||||
var beforeMeta, beforeData string
|
||||
var beforeWrites, beforePuts int
|
||||
me := layout.HolderID{Epoch: 1, Holder: "existing-holder", ClaimID: "existing-claim"}
|
||||
attach := func(name string) (*storage.WALStore, storage.ChunkLayer) {
|
||||
t.Helper()
|
||||
s, e := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), name), uint32(g.SizeBytes/uint64(g.BlockSize)), int(g.BlockSize), storage.WALStoreOptions{ChunkBlocks: uint32(g.ChunkBytes / uint64(g.BlockSize))})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.Recover(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
r, e := chunkstore.NewLayoutRemote(cat, foreign, me)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
l, e := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: uint32(g.ChunkBytes / uint64(g.BlockSize)), Epoch: me.Epoch, Holder: me.Holder, FreshFromHead: true})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return s, l
|
||||
}
|
||||
want := bytes.Repeat([]byte{0xa7}, 4096)
|
||||
attempts := 0
|
||||
h.cfg.LayoutCreateVolume = func(c context.Context, spec lifecycle.VolumeSpec) error {
|
||||
id, e := layout.ParseVolumeID(spec.LayoutID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ref := chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}
|
||||
attempts++
|
||||
if attempts == 1 {
|
||||
foreign = ref
|
||||
foreign.ID[15] ^= 1
|
||||
g = layout.Geometry{SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes}
|
||||
if _, e = cat.CreateVolume(c, foreign, g); e != nil {
|
||||
return e
|
||||
}
|
||||
st, _ := cat.Store(foreign)
|
||||
if _, e = layout.Start(c, st, safetyLease{}, layout.HolderID{Epoch: 1, Holder: me.Holder}, layout.LocalRoot{Geometry: g, ClaimID: me.ClaimID, Fresh: true, CanStartFrom: func(layout.Head) error { return nil }}); e != nil {
|
||||
return e
|
||||
}
|
||||
s, l := attach("seed")
|
||||
if _, e = s.Write(0, want); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.Sync(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = l.Capture(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.Close(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
beforeMeta = safetyDigest(f.entries)
|
||||
beforeData = safetyDigest(b.data)
|
||||
beforeWrites = f.writes
|
||||
beforePuts = b.puts
|
||||
}
|
||||
_, e = cat.CreateVolume(c, ref, g)
|
||||
return e
|
||||
}
|
||||
req := &control.CreateVolumeRequest{VolumeId: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}
|
||||
for i := 0; i < 1; i++ {
|
||||
if _, e := newServices(h).CreateVolume(ctx, req); e == nil {
|
||||
t.Fatal("collision unexpectedly healed; reassess witness")
|
||||
}
|
||||
}
|
||||
if safetyDigest(f.entries) != beforeMeta || safetyDigest(b.data) != beforeData || f.writes != beforeWrites || b.puts != beforePuts {
|
||||
t.Fatalf("SAFETY FAILURE metadata/data changed: writes %d->%d puts %d->%d", beforeWrites, f.writes, beforePuts, b.puts)
|
||||
}
|
||||
head, found, e := cat.ReadHead(ctx, foreign)
|
||||
if e != nil || !found || head.Activity.Kind != layout.ActIdle {
|
||||
t.Fatalf("HEAD lock/activity left: %+v %v", head, e)
|
||||
}
|
||||
t.Logf("BYTE_IDENTICAL metadata_sha256=%s blobs_sha256=%s successful_mutations=0 puts=0 directory=%s activity=idle", beforeMeta, beforeData, foreign.Dir())
|
||||
s, l := attach("after-collision")
|
||||
defer s.Close()
|
||||
got, e := s.Read(0)
|
||||
if e != nil || !bytes.Equal(got, want) {
|
||||
t.Fatalf("reattach/read old data failed: %v", e)
|
||||
}
|
||||
next := bytes.Repeat([]byte{0x3c}, 4096)
|
||||
if _, e = s.Write(1, next); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.Sync(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = l.Capture(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got, e = s.Read(1)
|
||||
if e != nil || !bytes.Equal(got, next) {
|
||||
t.Fatalf("serve new write/read failed: %v", e)
|
||||
}
|
||||
t.Log("ATTACH_AND_SERVE_PASS old nonzero data read; new write synced, cut committed, read back; no lock left")
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
)
|
||||
|
||||
type collisionBlobs struct{}
|
||||
|
||||
func (collisionBlobs) Put(context.Context, []byte) (string, error) {
|
||||
return "", errors.New("unexpected payload upload")
|
||||
}
|
||||
func (collisionBlobs) Get(context.Context, string) ([]byte, error) {
|
||||
return nil, errors.New("unexpected payload read")
|
||||
}
|
||||
|
||||
// A full-id mismatch in an exclusively-created VOLUME is a directory collision,
|
||||
// not a replay. The next create attempt must use a newly minted directory.
|
||||
func TestCreateVolumeExclusiveCollisionRedraws(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
h := newTestMaster(t, t.TempDir())
|
||||
defer closeTestMaster(t, h)
|
||||
h.cfg.WorkspaceRPC = true
|
||||
cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), collisionBlobs{}, "/collision")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var first, foreign chunkstore.VolumeRef
|
||||
var old layout.Volume
|
||||
attempts := 0
|
||||
h.cfg.LayoutCreateVolume = func(ctx context.Context, spec lifecycle.VolumeSpec) error {
|
||||
id, err := layout.ParseVolumeID(spec.LayoutID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}
|
||||
g := layout.Geometry{SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes}
|
||||
attempts++
|
||||
if attempts == 1 {
|
||||
first = ref
|
||||
foreign = ref
|
||||
foreign.ID[15] ^= 1
|
||||
if _, err := cat.CreateVolume(ctx, foreign, g); err != nil {
|
||||
return err
|
||||
}
|
||||
old, err = cat.ReadVolume(ctx, foreign)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = cat.CreateVolume(ctx, ref, g)
|
||||
return err
|
||||
}
|
||||
req := &control.CreateVolumeRequest{VolumeId: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}
|
||||
// A retry is allowed, but it must heal the collision rather than stay stuck.
|
||||
resp, err := newServices(h).CreateVolume(ctx, req)
|
||||
if err != nil {
|
||||
resp, err = newServices(h).CreateVolume(ctx, req)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("exclusive-create collision did not redraw: attempts=%d first=%s err=%v", attempts, first.ID, err)
|
||||
}
|
||||
id, err := layout.ParseVolumeID(resp.GetLayoutId())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next := chunkstore.VolumeRef{Name: "v", ID: id}
|
||||
if !resp.GetStoreReady() || id == first.ID || next.Dir() == first.Dir() {
|
||||
t.Fatalf("collision reused identity/directory: first=%s next=%s ready=%v", first.ID, id, resp.GetStoreReady())
|
||||
}
|
||||
got, err := cat.ReadVolume(ctx, foreign)
|
||||
if err != nil || got != old {
|
||||
t.Fatalf("redraw altered the colliding volume: %v %v", got, err)
|
||||
}
|
||||
replay, err := newServices(h).CreateVolume(ctx, req)
|
||||
if err != nil || replay.GetLayoutId() != id.String() {
|
||||
t.Fatalf("settled identity changed on replay: %v %v", replay, err)
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,10 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/auth"
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
@@ -241,6 +241,15 @@ func (h *Host) createLifecycleVolume(ctx context.Context, spec lifecycle.VolumeS
|
||||
}
|
||||
} else {
|
||||
createErr = h.cfg.LayoutCreateVolume(ctx, rec.Spec)
|
||||
if errors.Is(createErr, layout.ErrDirectoryCollision) {
|
||||
// The rejected exclusive create wrote nothing to the colliding
|
||||
// volume. Persist a fresh directory before the next RPC retries;
|
||||
// ordinary store errors keep their original identity for replay.
|
||||
if _, err := h.lifecycle.Volumes.RedrawPendingLayoutID(rec.Spec.VolumeID, rec.Spec.LayoutID); err != nil {
|
||||
return lifecycle.VolumeRecord{}, fmt.Errorf("%w: directory collision; replacement not settled: %w", errLayoutStoreNotReady, err)
|
||||
}
|
||||
return lifecycle.VolumeRecord{}, fmt.Errorf("%w: directory collision; a fresh identity is recorded; retry", errLayoutStoreNotReady)
|
||||
}
|
||||
}
|
||||
if createErr != nil {
|
||||
return lifecycle.VolumeRecord{}, fmt.Errorf("%w: %w", errLayoutStoreNotReady, createErr)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ func TestLayoutIdentityWriterAndReaders(t *testing.T) {
|
||||
// or a lifecycle record; its RPC containment is tested at catalog startup.
|
||||
mintSites := map[string]string{
|
||||
"core/lifecycle/store.go CreateVolume": "durable lifecycle volume identity",
|
||||
"core/lifecycle/store.go RedrawPendingLayoutID": "only a rejected unplaced ordinary create; TestRedrawPendingLayoutID and TestCreateVolumeExclusiveCollisionRedraws",
|
||||
"core/frontend/chunkstore/startup_head_probe.go checkConditionalHead": "disposable HEAD only, exclusive create in its random probe namespace; TestCatalogStartupRequiresWrongGenerationHeadRefusal",
|
||||
}
|
||||
seenMints := map[string]bool{}
|
||||
@@ -24,6 +25,8 @@ func TestLayoutIdentityWriterAndReaders(t *testing.T) {
|
||||
"core/lifecycle/store.go volumeSpecsCompatible": true,
|
||||
"core/lifecycle/store.go validateSpec": true,
|
||||
"core/lifecycle/store.go MarkStoreReady": true,
|
||||
"core/lifecycle/store.go RedrawPendingLayoutID": true,
|
||||
"core/lifecycle/store.go settlePendingLayoutIDLocked": true,
|
||||
"core/lifecycle/workload_plan.go PlanBlockVolumeWorkloads": true,
|
||||
"core/host/master/services.go lifecycleVolumeResponse": true,
|
||||
"core/host/master/services.go CreateVolume": true,
|
||||
@@ -127,11 +130,14 @@ func TestLayoutIdentityWriterAndReaders(t *testing.T) {
|
||||
// Adding a new reader or writer requires a binding probe at that site.
|
||||
func TestRestoreSourceIdentitySites(t *testing.T) {
|
||||
want := map[string]bool{
|
||||
"core/lifecycle/store.go CreateVolume": true,
|
||||
"core/lifecycle/store.go volumeSpecsCompatible": true,
|
||||
"core/lifecycle/store.go validateSpec": true,
|
||||
"core/host/master/services.go CreateVolume": true,
|
||||
"core/host/master/services.go createLifecycleVolume": true,
|
||||
// Restore records are excluded; TestRedrawPendingLayoutID probes both paths.
|
||||
"core/lifecycle/store.go RedrawPendingLayoutID": true,
|
||||
"core/lifecycle/store.go settlePendingLayoutIDLocked": true,
|
||||
"core/lifecycle/store.go CreateVolume": true,
|
||||
"core/lifecycle/store.go volumeSpecsCompatible": true,
|
||||
"core/lifecycle/store.go validateSpec": true,
|
||||
"core/host/master/services.go CreateVolume": true,
|
||||
"core/host/master/services.go createLifecycleVolume": true,
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
root := filepath.Join("..", "..")
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRedrawPendingLayoutID(t *testing.T) {
|
||||
if os.Getenv("SWB_REDRAW_CHILD") != "1" {
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestRedrawPendingLayoutID$", "-test.v")
|
||||
cmd.Env = append(os.Environ(), "SWB_REDRAW_CHILD=1")
|
||||
if out, e := cmd.CombinedOutput(); e != nil {
|
||||
t.Fatalf("child: %v\n%s", e, out)
|
||||
}
|
||||
return
|
||||
}
|
||||
hooks := &durableRecordHooks{}
|
||||
if runtime.GOOS == "windows" {
|
||||
hooks.dirSync = func(string) error { return nil }
|
||||
}
|
||||
durableRecordHooksForTest.Store(hooks)
|
||||
defer durableRecordHooksForTest.Store(nil)
|
||||
s, e := OpenFileStore(t.TempDir())
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
spec := VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}
|
||||
old, e := s.CreateVolume(spec)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.RedrawPendingLayoutID("v", "00000000000000000000000000000001"); !errors.Is(e, ErrVolumeConflict) {
|
||||
t.Fatalf("stale ID accepted: %v", e)
|
||||
}
|
||||
// A lost directory-sync reply after rename must settle the replacement
|
||||
// from disk, even though the in-memory record still has the rejected ID.
|
||||
fail := true
|
||||
hooks.dirSync = func(string) error {
|
||||
if fail {
|
||||
return errors.New("lost directory sync")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, e = s.RedrawPendingLayoutID("v", old.Spec.LayoutID); e == nil {
|
||||
t.Fatal("sync failure hidden")
|
||||
}
|
||||
cur, _ := s.GetVolume("v")
|
||||
if cur != old {
|
||||
t.Fatal("uncertain replacement published")
|
||||
}
|
||||
raw, e := os.ReadFile(s.path("v"))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var disk VolumeRecord
|
||||
if e = json.Unmarshal(raw, &disk); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
fail = false
|
||||
// Exercise the public retry path, including metadata enrichment. It
|
||||
// must settle disk B before a metadata put could overwrite it with A.
|
||||
retry := spec
|
||||
retry.PVCName, retry.PVName = "claim", "pv"
|
||||
public, retryErr := s.CreateVolume(retry)
|
||||
if retryErr != nil || public.Spec.LayoutID != disk.Spec.LayoutID || public.Spec.PVCName != "claim" || public.Spec.PVName != "pv" {
|
||||
t.Fatalf("public retry lost disk replacement: disk=%s public=%+v err=%v", disk.Spec.LayoutID, public, retryErr)
|
||||
}
|
||||
// Re-enter the direct method with its current ID for a separate
|
||||
// replacement; the stale original ID must no longer be admitted.
|
||||
if _, e = s.RedrawPendingLayoutID("v", old.Spec.LayoutID); !errors.Is(e, ErrVolumeConflict) {
|
||||
t.Fatalf("settled replacement accepted stale rejected ID: %v", e)
|
||||
}
|
||||
got := public
|
||||
if got.Spec.LayoutID[:8] == old.Spec.LayoutID[:8] {
|
||||
t.Fatal("replacement reused directory")
|
||||
}
|
||||
reopened, e := OpenFileStore(s.dir)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
again, e := reopened.CreateVolume(spec)
|
||||
if e != nil || again != got {
|
||||
t.Fatalf("restart reminted: %+v %v", again, e)
|
||||
}
|
||||
if _, e = s.MarkStoreReady("v", got.Spec.LayoutID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.RedrawPendingLayoutID("v", got.Spec.LayoutID); !errors.Is(e, ErrVolumeConflict) {
|
||||
t.Fatalf("ready identity redrawn: %v", e)
|
||||
}
|
||||
spec.VolumeID = "attached"
|
||||
attached, e := s.CreateVolume(spec)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.AttachVolume("attached", "host"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.RedrawPendingLayoutID("attached", attached.Spec.LayoutID); !errors.Is(e, ErrVolumeConflict) {
|
||||
t.Fatalf("attached identity redrawn: %v", e)
|
||||
}
|
||||
spec.VolumeID = "restore"
|
||||
spec.SourceVolume = "source"
|
||||
spec.SourceLayoutID = got.Spec.LayoutID
|
||||
spec.SourceSnapshot = "snap"
|
||||
spec.CreateRequestID = "request"
|
||||
restore, e := s.CreateVolume(spec)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.RedrawPendingLayoutID("restore", restore.Spec.LayoutID); !errors.Is(e, ErrVolumeConflict) {
|
||||
t.Fatalf("restore identity redrawn: %v", e)
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,16 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) {
|
||||
if !volumeSpecsCompatible(existing.Spec, spec) {
|
||||
return VolumeRecord{}, ErrVolumeConflict
|
||||
}
|
||||
// A previous collision redraw may have reached disk but lost its
|
||||
// directory-sync reply. Settle it before enriching cached metadata.
|
||||
var err error
|
||||
existing, err = s.settlePendingLayoutIDLocked(existing)
|
||||
if err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
if !volumeSpecsCompatible(existing.Spec, spec) {
|
||||
return VolumeRecord{}, ErrVolumeConflict
|
||||
}
|
||||
merged := existing
|
||||
merged.Spec = mergeVolumeSpecMetadata(existing.Spec, spec)
|
||||
if merged.Spec != existing.Spec {
|
||||
@@ -205,6 +215,86 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) {
|
||||
return rec, nil
|
||||
}
|
||||
|
||||
// RedrawPendingLayoutID replaces only an unplaced ordinary create's rejected
|
||||
// identity. The caller must have proved an exclusive VOLUME directory collision.
|
||||
// A replacement whose directory-sync reply was lost is settled, never reminted.
|
||||
func (s *FileStore) RedrawPendingLayoutID(volumeID, rejectedID string) (VolumeRecord, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
rec, ok := s.records[volumeID]
|
||||
if !ok {
|
||||
return VolumeRecord{}, ErrVolumeNotFound
|
||||
}
|
||||
if rec.Spec.LayoutID != rejectedID || rec.StoreReady || rec.AttachedTo != "" || rec.Spec.SourceVolume != "" || rec.Spec.SourceLayoutID != "" || rec.Spec.SourceSnapshot != "" || rec.Spec.CreateRequestID != "" {
|
||||
return VolumeRecord{}, ErrVolumeConflict
|
||||
}
|
||||
settled, err := s.settlePendingLayoutIDLocked(rec)
|
||||
if err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
if settled.Spec.LayoutID != rejectedID {
|
||||
return settled, nil
|
||||
}
|
||||
disk := settled
|
||||
if disk.Spec.LayoutID == rejectedID {
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
if id.String()[:8] == rejectedID[:8] {
|
||||
return VolumeRecord{}, fmt.Errorf("lifecycle: replacement repeats the rejected directory; retry")
|
||||
}
|
||||
disk.Spec.LayoutID = id.String()
|
||||
}
|
||||
if err := s.putLocked(disk); err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
s.records[volumeID] = disk
|
||||
s.publishLocked()
|
||||
return disk, nil
|
||||
}
|
||||
|
||||
// settlePendingLayoutIDLocked reconciles only an uncertain pending identity
|
||||
// replacement, before either a redraw or public metadata enrichment can write.
|
||||
func (s *FileStore) settlePendingLayoutIDLocked(rec VolumeRecord) (VolumeRecord, error) {
|
||||
if rec.StoreReady || rec.AttachedTo != "" || rec.Spec.SourceVolume != "" || rec.Spec.SourceLayoutID != "" || rec.Spec.SourceSnapshot != "" || rec.Spec.CreateRequestID != "" {
|
||||
return rec, nil
|
||||
}
|
||||
raw, err := os.ReadFile(s.path(rec.Spec.VolumeID))
|
||||
if err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
var disk VolumeRecord
|
||||
if err := json.Unmarshal(raw, &disk); err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
if disk.Spec.LayoutID == rec.Spec.LayoutID {
|
||||
return rec, nil
|
||||
}
|
||||
id, err := layout.ParseVolumeID(disk.Spec.LayoutID)
|
||||
if err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
// Nothing except the identity may differ in an uncertain redraw.
|
||||
disk.Spec.LayoutID = rec.Spec.LayoutID
|
||||
if disk != rec {
|
||||
return VolumeRecord{}, ErrVolumeConflict
|
||||
}
|
||||
if _, err := layout.ParseVolumeID(rec.Spec.LayoutID); err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
if id.String()[:8] == rec.Spec.LayoutID[:8] {
|
||||
return VolumeRecord{}, ErrVolumeConflict
|
||||
}
|
||||
disk.Spec.LayoutID = id.String()
|
||||
if err := s.putLocked(disk); err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
s.records[rec.Spec.VolumeID] = disk
|
||||
s.publishLocked()
|
||||
return disk, nil
|
||||
}
|
||||
|
||||
// MarkStoreReady publishes the durable placement hint after the filer has
|
||||
// accepted both exclusive creates. A retry of the same create may repeat it;
|
||||
// another layout identity may not mark this record ready.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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 }
|
||||
@@ -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.
|
||||
@@ -567,6 +567,7 @@ stateDiagram-v2
|
||||
| From | To | Guard | Enforced in | Protects |
|
||||
|---|---|---|---|---|
|
||||
| no lifecycle record | named volume with immutable layout id | master lifecycle create mints the id once; a lost directory-sync reply settles the same record on retry. Lookup resolves the durable name/id without creating one; workload launch carries both and selects a local directory keyed by id | `core/lifecycle/store.go` `CreateVolume`; master `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient` `ResolveVolume`; launcher `blockVolumeArgs`; blockvolume `parseFlags` | `INV-SNAPK-VOLUME-DIR-001` |
|
||||
| pending ordinary create with a proved id8 collision | pending create with a fresh durable layout id | rejected exclusive VOLUME create, valid foreign full identity belongs to the selected name/id8 directory; not ready, not attached, not a restore; persist replacement before retry, settle unknown rename on replay; never modify the colliding volume | `LayoutStore.CreateVolumeRecord`; `FileStore.RedrawPendingLayoutID`; master `createLifecycleVolume` | `INV-CREATE-DIR-COLLISION-001` |
|
||||
| idle | snap(s) | caller is the holder at HEAD's epoch (epoch, server and claim id); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` |
|
||||
| snap(s) | idle | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); over idle it succeeds without a write and means only that no activity remains; before resuming a failed stop, abort its still-open session and re-read HEAD: only matching live/idle resumes, detached goes Down, absent/unknown stays stopped | head.go `Head.Abort`; durable/provider_layout.go `settleLayoutStop` | `INV-SNAPK-ABORT-001` |
|
||||
| snap(s) | idle, current = root | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); the previous manifest builds to HEAD's current root; the new own chunks, every segment and the root are present; a new snapshot name records bounded retention facts once, while replay preserves them | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-COMMIT-REACH-001`, `INV-SNAPK-TXN-INTERRUPT-001`, `INV-SNAPK-SNAPSHOT-META-001` |
|
||||
@@ -785,6 +786,9 @@ Notes:
|
||||
| `INV-AUTH-ONE-REPLICATED-FACTOR-001` | CreateVolume admits a replicated volume only if the master can decide it: its replication factor equals the master's one slot count (--expected-slots-per-volume) and the lifecycle product loop runs (only that loop binds, mints and promotes it). | M2 none → Bound (a created replicated volume's first line) | `core/host/master/services.go` `CreateVolume`; `core/host/master/host.go` `Config.LifecycleProductLoop`; `core/authority/controller.go` `ExpectedSlotsPerVolume`, `validateVolumeTopology` | `TestAnRF2CreateOnAnRF3MasterIsRefusedAndFailoverContinues`, `TestAReplicatedCreateWithTheProductLoopOffIsRefused` (`core/host/master/create_rf_mismatch_test.go`) | — (an admission check). Limits: single-replica volumes are admitted at any slot count (they never reach the check); a static --topology file with a mismatched volume is not checked at start (a cluster spec is: `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001`) | ACTIVE |
|
||||
| `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001` | blockmaster refuses to start when its cluster spec holds a replicated volume it could never decide: one whose replication factor differs from --expected-slots-per-volume, or any while the lifecycle product loop is off (only that loop binds, mints and promotes it). | M2 none → Bound (a replicated cluster-spec volume's first line) | `cmd/blockmaster/product_loop_guard.go` `requireProductLoop`; `cmd/blockmaster/main.go` `run` | `TestReplicatedClusterSpecWithTheProductLoopOffIsRefused`, `TestTheProductLoopGuardPassesWhatItShould`, `TestAClusterSpecVolumeOfAnotherReplicationFactorIsRefused`, `TestAPlacementOnlyClusterSpecVolumeIsChecked` (`cmd/blockmaster/product_loop_guard_test.go`) | — (a startup configuration check). Limits: static `--topology` is not refused (its observation controller mints), and has no automatic failover in v1 | ACTIVE |
|
||||
| `INV-CREATE-ONE-IDENTITY-001` | One name, one layout identity; no directory but the record's holds a live HEAD (not none, not deleted). A served volume's deleted name is never created again. | M2 none → created (CreateVolume, restore target creation) | `core/host/master/services.go` `CreateVolume`, `createLifecycleVolume`; `core/frontend/chunkstore/layout/start.go` `Start` | `TestARefusedRestoreLeavesNoTargetRecord` (`core/host/master/restore_refusal_test.go`), `TestARealCatalogRestoreOfARestoreTargetLeavesNothing`, `TestAServedThenDeletedNameIsStillRefused` (`core/host/master/restore_refusal_catalog_test.go`), `TestCreateVolume` (`core/frontend/chunkstore/layout/create_test.go`), `TestDecodeHead_RefusesAnotherVolumesHead` (`core/frontend/chunkstore/layout/head_test.go`) | VolumeCreate OneIdentity (its second clause: a directory with a live HEAD is the record's). Scope: only a refused restore's record, which never left the creation phase (never assigned, never served), is removed, with no filer write. Limits: a served volume's deleted name stays refused until 1.1 | ACTIVE |
|
||||
| `INV-CREATE-DIR-COLLISION-001` | Only a rejected exclusive VOLUME create proving a valid foreign full id in the selected name/id8 directory permits an unready, unattached ordinary create to redraw. Ready, attached and restore records refuse redraw. | M2 pending create collision → pending create with fresh id | `core/frontend/chunkstore/layout_create.go` `CreateVolumeRecord`; `core/lifecycle/store.go` `RedrawPendingLayoutID`; `core/host/master/services.go` `createLifecycleVolume` | `TestCreateVolumeExclusiveCollisionRedraws`, `TestCollisionExistingVolumeSafety`, `TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal`, `TestRedrawPendingLayoutID` | MasterCreate3 MUST-VIOLATE rows 220-224; no-proof redraw, use-before-persist and remint-on-replay mutants violate OneIdentity; no change to HEAD ownership/lease rules | ACTIVE |
|
||||
| `INV-CREATE-DIR-COLLISION-SETTLE-001` | A collision replacement is persisted before use. A lost synchronization reply settles the identity already on disk; a retry never remints it. | M2 pending create collision → pending create with fresh id | `core/frontend/chunkstore/layout_create.go` `CreateVolumeRecord`; `core/lifecycle/store.go` `RedrawPendingLayoutID`; `core/host/master/services.go` `createLifecycleVolume` | `TestCreateVolumeExclusiveCollisionRedraws`, `TestCollisionExistingVolumeSafety`, `TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal`, `TestRedrawPendingLayoutID` | MasterCreate3 MUST-VIOLATE rows 220-224; no-proof redraw, use-before-persist and remint-on-replay mutants violate OneIdentity; no change to HEAD ownership/lease rules | ACTIVE |
|
||||
| `INV-CREATE-DIR-COLLISION-FOREIGN-001` | A rejected exclusive create leaves the colliding volume metadata and payload byte-identical, with no new activity or lock; that volume remains attachable and serves its data. | M2 pending create collision → pending create with fresh id | `core/frontend/chunkstore/layout_create.go` `CreateVolumeRecord`; `core/lifecycle/store.go` `RedrawPendingLayoutID`; `core/host/master/services.go` `createLifecycleVolume` | `TestCreateVolumeExclusiveCollisionRedraws`, `TestCollisionExistingVolumeSafety`, `TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal`, `TestRedrawPendingLayoutID` | MasterCreate3 MUST-VIOLATE rows 220-224; no-proof redraw, use-before-persist and remint-on-replay mutants violate OneIdentity; no change to HEAD ownership/lease rules | ACTIVE |
|
||||
| `INV-CLI-TYPED-REFUSAL-001` | The chunk CLI reports a restore the master refused for a foreign source as `restore_source_not_own` (from the master's typed reason, never its text) and a volume the master does not know as `volume_not_found`. | M2 none → created (restore refusal); CLI volume resolve | `core/host/master/services.go` `CreateVolume`; `core/rpc/lifecycleclient/reason.go` `WithReason`, `Reason`; `cmd/sw-block/chunk_b.go` `chunkRestore`, `run` | `TestOpsChunkTypedRefusalCodes` (`cmd/sw-block/chunk_typed_codes_test.go`), `TestReasonRoundTrip` (`core/rpc/lifecycleclient/reason_test.go`), `TestARealCatalogRestoreOfARestoreTargetLeavesNothing` (`core/host/master/restore_refusal_catalog_test.go`) | — (reporting only; the refusal is `INV-CREATE-ONE-IDENTITY-001`'s). Limits: other FailedPrecondition refusals stay the generic `not_admitted` | ACTIVE |
|
||||
| `INV-CLI-RESTORE-VERB-001` | `volume restore --abort` changes nothing unless the master records this command's source, snapshot and request id for the target and this host's settings name exactly it (volume, master, `--layout-id` alone in the extra arguments); a re-run counts only this replica's published line as placed. | client (no state machine): the CLI side of M2 restore create, placement and delete | `cmd/sw-block/volume_backup.go` `volumeRestoreAbort`, `volumeRestore`, `restorePlaced`; `core/host/master/services.go` `lifecycleVolumeResponse` | `TestVolumeRestoreAbortRefusesAForeignTarget`, `TestVolumeRestoreAbortRefusesAnotherLocalInstallation`, `TestVolumeRestoreAbortInterruptedAtEveryStepCompletes`, `TestVolumeRestoreCrashTableBothWays`, `TestVolumeRestorePublicationDuringThePlacement`, `TestVolumeRestorePlacementOfAnotherLineRefuses`, `TestVolumeRestoreCreatesPlacesAndStarts`, `TestVolumeBackupTakesOneSnapshotAndRerunReplays`, `TestVolumeBackupRefusals`, `TestVolumeBackupIncompleteAnswerIsUnknown` (`cmd/sw-block/volume_backup_test.go`), `TestGetVolumeAnswersTheRecordedRestoreTuple` (`core/host/master/volume_restore_tuple_test.go`) | — (the command's model is checked outside the repository; its trace is on the pull request) | ACTIVE |
|
||||
| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`); also in `core/authority/layout_granted_epoch_guard_test.go` | `ControlPlane` `UniqueEpoch` | ACTIVE |
|
||||
@@ -1210,7 +1214,7 @@ Notes:
|
||||
| `INV-WS-DELETE-WITHOUT-ACK-001` | A delete without the holder's acknowledgement is admitted only while the master's record still awaits a replica store (stage 1), marked durably first; the mark freezes the wait, so the primary never serves. Past stage 1 the live-lease refusal stays. | M2 any authority line, stores still awaited → DeleteReserved without the holder's acknowledgement | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited` | `TestANeverCreatedVolumeIsDeletedWithoutItsHolder`, `TestAnEstablishedVolumeIsNotDeletedUnderALiveLease` (`core/host/master/workspace_delete_never_created_test.go`); `TestAStage2VolumeKeepsTheLiveLeaseRefusal`, `TestTheDeleteMarkFreezesTheStoreWait`, `TestAStage2VolumeIsNotMarkedForADeleteWithoutAck` (`core/host/master/workspace_delete_proof_test.go`); `TestDeleteMarkWriterCensus`, `TestDeleteMarkWriterCensusControls` (`core/host/master/store_attestation_census_test.go`) | CreateEvid2 model rows `mut_delete_on_flag_only`, `mut_no_horizon` | ACTIVE |
|
||||
| `INV-CLI-DELETE-PROGRESS-001` | Volume deletion bounds each sweep, continues across transient filer failures while objects are removed, and returns a retryable unavailable answer with progress after a no-progress window. | M9 deleting → deleted | `cmd/sw-block/chunk_volume_delete.go` `deleteVolumeWithProgress` | `TestVolumeDeleteContinuesAcrossTransientObjectFailures` | Existing ordered delete; no new persisted state. | ACTIVE |
|
||||
| `INV-SNAPK-DELETE-GUARD-001` | A source scan requires DeleteVolume to run no-holder check, deleting, release, object deletes and deleted in that order, and allows it as the only remover besides RemoveUnreachable. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-SNAPK-VOLUME-DIR-001` | A volume's master-minted layout identity is immutable; its directory is <name>-<first 8 hex of that id>, created exclusively and never reused. A foreign chunk's owning directory is checked against its full VOLUME id. | Content-named layout and lifecycle create/lookup/launch | `core/frontend/chunkstore/layout` `VolumeDir`; `core/lifecycle/store.go` `CreateVolume`; `core/host/master/services.go` `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient`; `core/launcher/k8s_renderer.go`; `cmd/blockvolume/main.go` `parseFlags`; `core/host/volume/chunk_control.go` `catalogVolume`, `ListSnapshots`, `DeleteSnapshot`, `Usage`; `cmd/blockvolume/chunk_remote.go` `chunkAttachCheck`; `core/frontend/chunkstore/layout/read.go` `Image.Chunk`; `core/rpc/lifecycleclient/identity.go` `ResolveVolume` | `TestRead_ForeignChunkFromSourcePool`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`; `TestLifecycleLayoutIdentity`, `TestLayoutIdentityWriterAndReaders`; `TestGetLifecycleVolumeResolvesOnlyTheDurableIdentity`; `TestResolveVolumeNeverInventsAnIdentity`; `TestLauncherCarriesTheMasterLayoutIdentity`; `TestBlockvolumeLayoutIdentitySelectsTheLocalRoot`; `TestChunkControlUsesTheBoundLayoutIdentity`, `TestChunkControlCatalogLookupErrorIsNotAbsence`, `TestChunkAttachCheckAppliesVolumeRules`; `TestHeadReaders_Enumeration`, `TestDeleteAndDirectorySites_Enumeration` | Lifecycle ids are durable record fields, not assignment epochs. Old records without the field are refused by the new-layout lookup; host metadata is bound to the full name/id and does not fall back to a previous incarnation. Data-path, scheduled snapshot and cleaning callers plus Linux crash qualification remain cutover work. | ACTIVE |
|
||||
| `INV-SNAPK-VOLUME-DIR-001` | A ready volume keeps its master-minted layout identity. Its <name>-<id8> directory is created exclusively and never reused. Foreign chunk owners are checked against their full VOLUME identity. | Content-named layout and lifecycle create/lookup/launch | `core/frontend/chunkstore/layout` `VolumeDir`; `core/lifecycle/store.go` `CreateVolume`; `core/host/master/services.go` `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient`; `core/launcher/k8s_renderer.go`; `cmd/blockvolume/main.go` `parseFlags`; `core/host/volume/chunk_control.go` `catalogVolume`, `ListSnapshots`, `DeleteSnapshot`, `Usage`; `cmd/blockvolume/chunk_remote.go` `chunkAttachCheck`; `core/frontend/chunkstore/layout/read.go` `Image.Chunk`; `core/rpc/lifecycleclient/identity.go` `ResolveVolume` | `TestRead_ForeignChunkFromSourcePool`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`; `TestLifecycleLayoutIdentity`, `TestLayoutIdentityWriterAndReaders`; `TestGetLifecycleVolumeResolvesOnlyTheDurableIdentity`; `TestResolveVolumeNeverInventsAnIdentity`; `TestLauncherCarriesTheMasterLayoutIdentity`; `TestBlockvolumeLayoutIdentitySelectsTheLocalRoot`; `TestChunkControlUsesTheBoundLayoutIdentity`, `TestChunkControlCatalogLookupErrorIsNotAbsence`, `TestChunkAttachCheckAppliesVolumeRules`; `TestHeadReaders_Enumeration`, `TestDeleteAndDirectorySites_Enumeration` | Lifecycle ids are durable record fields, not assignment epochs. Old records without the field are refused by the new-layout lookup; host metadata is bound to the full name/id and does not fall back to a previous incarnation. Data-path, scheduled snapshot and cleaning callers plus Linux crash qualification remain cutover work. | ACTIVE |
|
||||
| `INV-SNAPK-TOMBSTONE-001` | For a restore target without HEAD (never created, or a restore died between its two creates) the operator writes a deleted HEAD exclusively in its directory before releasing, so the restore cannot create it later. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent`, `TargetStore.CreateDeletedHead` | `TestOperatorReleaseDependent`, `TestOperatorReleaseDependent_TombstoneLosesToTheRestore`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-SNAPK-KEEP-HEAD-001` | Nothing removes a HEAD, a VOLUME or a volume directory: a volume delete removes only pool, segment and root objects; a source scan lists every delete and every directory-naming site in core/ and cmd/. | M9 deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`; (source scan) | `TestDeleteVolume_RemovesOnlyObjects`, `TestDeleteAndDirectorySites_Enumeration` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-SNAPK-CREATE-001` | A new volume or restore target gets VOLUME then an unclaimed HEAD (epoch 0, no holder, no claim id, idle), each created exclusively; only createVolume and the operator's tombstone create a HEAD; the first Start claims it from a fresh root. | M9 absent → idle | `core/frontend/chunkstore/layout` `create.go` `CreateVolume`, `CreateTarget` | `TestCreateVolume`, `TestCreateVolume_InterruptAtEveryStep`, `TestUnclaimedHead_Shape`, `TestStart_ClaimsAnUnclaimedHeadFromAFreshRoot`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# Volume directory collisions
|
||||
|
||||
A directory uses the volume name and the first eight hexadecimal digits of
|
||||
its full layout identity. Two different full identities can select the same
|
||||
directory. The exclusive VOLUME create refuses that collision without writing
|
||||
VOLUME, HEAD, objects or payloads in the existing volume.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
pending --> pending: ordinary storage error; retry same identity
|
||||
pending --> replacementPending: exclusive create proves a valid foreign id8 collision
|
||||
replacementPending --> pending: persist fresh full identity, retry in fresh directory
|
||||
pending --> ready: matching VOLUME and HEAD created
|
||||
ready --> ready: identical create replay
|
||||
```
|
||||
|
||||
Only an ordinary, not-ready, unattached lifecycle record can redraw. A restore
|
||||
keeps its source/request binding and is not handled by this transition. A corrupt
|
||||
VOLUME, an unrelated identity mismatch, or an unknown store outcome never proves
|
||||
a collision. Ordinary reads and attach still reject every full-ID mismatch.
|
||||
|
||||
One RPC performs at most one redraw. It returns a retry response after recording
|
||||
the replacement; the next RPC creates the new directory. A replacement first
|
||||
lands through the lifecycle store's file-sync, rename and directory-sync path.
|
||||
If its synchronization result is unknown, a retry settles that on-disk identity
|
||||
before publishing it, rather than generating another. No ready identity changes.
|
||||
|
||||
The master serializes create and placement under workspaceMu. This is a change
|
||||
to pending creation only, not an assignment, lease, epoch or serving decision.
|
||||
MasterCreate3 checks the collision transition and OneIdentity (MUST-VIOLATE
|
||||
rows 220-224): redraw without proof, use before persistence and remint on
|
||||
replay each violate the invariant. Linux focused regression controls pass;
|
||||
the full master package's qualification remains open.
|
||||
Reference in new issue
Block a user