Add snapshot incarnation codecs and target-qualified delete helpers

This commit is contained in:
pingqiu committed 2026-12-01 12:57:02 -08:00
1 parent 4063be8def
commit 69cd920b13
7 files changed
+330 -6

No files matched your search

@@ -211,7 +211,7 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool)
bad = append(bad, "OperatorReleaseDependent does not read the target's HEAD before releasing")
}
for name, by := range code {
if name == "DeleteSnapshot" {
if name == "DeleteSnapshot" || name == "DeleteSnapshotAt" {
continue // a HEAD transition (a snapshot's name leaves HEAD), not a store remover
}
if strings.HasPrefix(name, "Delete") || strings.HasPrefix(name, "Remove") {
@@ -45,8 +45,12 @@ type Dependent struct {
// that named it (the cut LSN of its image), and the restore targets that
// still name its chunks, ordered by target id.
type Snapshot struct {
Root RootName
Position uint64
Root RootName
Position uint64
// Gen identifies this incarnation of the name: its publishing HEAD
// generation, immutable after publication. Zero means legacy, not yet
// stamped by a v1.1 writer; it is never a valid delete target.
Gen uint64
Meta SnapshotMeta
Dependents []Dependent
// ManifestBytes is the size of the snapshot's manifest (its root and
@@ -205,6 +209,7 @@ type headDoc struct {
type snapDoc struct {
Root string `json:"root"`
Position uint64 `json:"position,omitempty"`
Gen *uint64 `json:"gen,omitempty"`
CreatedNs int64 `json:"created_ns,omitempty"`
Class string `json:"class,omitempty"`
ExpiresNs int64 `json:"expires_ns,omitempty"`
@@ -309,6 +314,9 @@ func (h Head) check() error {
return fmt.Errorf("%w: %d dependents in HEAD, at most %d", ErrMalformed, n, MaxDependentsPerHead)
}
for n, s := range h.Snapshots {
if s.Gen != 0 && h.Version == 0 {
return fmt.Errorf("%w: v1.0 snapshot %q carries a publishing generation", ErrMalformed, n)
}
if n == "" {
return fmt.Errorf("%w: unnamed snapshot", ErrMalformed)
}
@@ -363,6 +371,10 @@ func (h Head) Encode() ([]byte, error) {
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, ManifestBytes: s.ManifestBytes}
if s.Gen != 0 {
gen := s.Gen
sd.Gen = &gen
}
if len(s.Meta.Labels) > 0 {
sd.Labels = s.Meta.Labels
}
@@ -428,11 +440,17 @@ func DecodeHead(b []byte, gen uint64, volume VolumeID) (Head, error) {
if len(d.Snapshots) > 0 {
h.Snapshots = map[string]Snapshot{}
for n, s := range d.Snapshots {
if s.Gen != nil && *s.Gen == 0 {
return Head{}, fmt.Errorf("%w: snapshot %q explicitly carries generation zero", ErrMalformed, n)
}
rn, err := ParseRootName(s.Root)
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}, ManifestBytes: s.ManifestBytes}
if s.Gen != nil {
snap.Gen = *s.Gen
}
for _, dep := range s.Dependents {
tid, err := ParseVolumeID(dep.TargetID)
if err != nil {
@@ -540,7 +558,7 @@ func (h Head) clone() Head {
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...), ManifestBytes: cloneSize(s.ManifestBytes)}
c.Snapshots[n] = Snapshot{Root: s.Root, Position: s.Position, Gen: s.Gen, Meta: s.Meta.clone(), Dependents: append([]Dependent(nil), s.Dependents...), ManifestBytes: cloneSize(s.ManifestBytes)}
}
}
return c
@@ -29,7 +29,7 @@ var kernelStates = []string{"absent", "unclaimed", "idle", "snap", "clean", "det
var kernelEntries = []string{
"CreateVolume", "CreateTarget", "StartHigher", "StartHigherCannotStart", "StartOwn", "StartOwnOtherFresh", "StartOwnOtherFreshCannotStart", "StartOwnOtherOld",
"Claim", "Begin", "Commit", "CommitNew", "CommitLower", "Abort", "BeginClean", "EndClean",
"RemoveUnreachable", "DeleteSnapshot", "RetireSnapshot", "AddDependent", "ReleaseDependent",
"RemoveUnreachable", "DeleteSnapshot", "DeleteSnapshotAt", "RetireSnapshot", "AddDependent", "ReleaseDependent",
"MarkDeleting", "MarkDeleted", "DeletedHeadCreate",
}
@@ -102,6 +102,13 @@ func kernelCell(t *testing.T, state, entry string) string {
d.Dependents = []Dependent{{Target: "t", TargetID: idFor("t"), Root: d.Root}}
h.Snapshots["daily"] = d
}
if entry == "DeleteSnapshotAt" {
h.Version = HeadVersion1
if s, ok := h.Snapshots["daily"]; ok {
s.Gen = 7
h.Snapshots["daily"] = s
}
}
nv := newMemNewVolume()
vol := Volume{ID: idFor("v1"), Name: "v1", Geometry: tableGeometry, Format: VolumeFormat}
if state != "absent" {
@@ -217,6 +224,8 @@ func kernelCell(t *testing.T, state, entry string) string {
_, err = RemoveUnreachable(ctx, nv, r, o, me, "c1", 0, orphans)
case "DeleteSnapshot":
_, err = RunDeleteSnapshot(ctx, nv, "daily")
case "DeleteSnapshotAt":
_, err = RunDeleteSnapshotAt(ctx, nv, "daily", 7)
case "RetireSnapshot":
_, err = RunRetireSnapshot(ctx, nv, "daily", 1)
case "AddDependent":
@@ -265,6 +274,7 @@ var kernelExpected = map[string]map[string]string{
"EndClean": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "noop", "snap": "NoSession", "clean": "write", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"},
"RemoveUnreachable": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "NoSession", "snap": "NoSession", "clean": "write", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"},
"DeleteSnapshot": {"absent": "HeadAbsent", "unclaimed": "noop", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"},
"DeleteSnapshotAt": {"absent": "HeadAbsent", "unclaimed": "noop", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"},
"RetireSnapshot": {"absent": "HeadAbsent", "unclaimed": "noop", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"},
"AddDependent": {"absent": "HeadAbsent", "unclaimed": "NoSnapshot", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"},
"ReleaseDependent": {"absent": "HeadAbsent", "unclaimed": "noop", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "unreachable", "deleted": "unreachable"},
@@ -304,7 +314,7 @@ var kernelEntryFuncs = map[string]string{
"CreateVolume": "CreateVolume", "CreateTarget": "CreateTarget", "StartHigher": "Start", "StartOwn": "Start",
"StartOwnOtherFresh": "Start", "StartOwnOtherOld": "Start", "StartHigherCannotStart": "Start", "StartOwnOtherFreshCannotStart": "Start", "Claim": "RunClaim",
"Begin": "RunBegin", "Commit": "RunCommit", "CommitNew": "RunCommit", "CommitLower": "RunCommit", "Abort": "RunAbort", "BeginClean": "RunBeginClean", "EndClean": "RunEndClean",
"RemoveUnreachable": "RemoveUnreachable", "DeleteSnapshot": "RunDeleteSnapshot", "RetireSnapshot": "RunRetireSnapshot",
"RemoveUnreachable": "RemoveUnreachable", "DeleteSnapshot": "RunDeleteSnapshot", "DeleteSnapshotAt": "RunDeleteSnapshotAt", "RetireSnapshot": "RunRetireSnapshot",
"AddDependent": "RunAddDependent", "ReleaseDependent": "RunReleaseDependent", "MarkDeleting": "RunMarkDeleting",
"MarkDeleted": "RunMarkDeleted", "DeletedHeadCreate": "OperatorReleaseDependent",
}
@@ -0,0 +1,77 @@
package layout
import (
"context"
"errors"
"fmt"
)
// ErrSnapshotGenerationMissing refuses admission against an unstamped legacy
// snapshot. Zero is not an incarnation and cannot be a delete target.
var ErrSnapshotGenerationMissing = errors.New("layout: snapshot needs its v1.1 publishing generation: start a v1.1 holder to upgrade HEAD")
// ErrHeadGenerationExhausted refuses publication instead of wrapping an
// incarnation to zero.
var ErrHeadGenerationExhausted = errors.New("layout: HEAD generation exhausted")
// StampSnapshotGenerations prepares the first v1.1 write of legacy snapshots.
// The caller must publish the returned HEAD conditional on h.Gen, under the
// normal transition's authority checks. This pure step grants no authority
// and writes nothing. A lost CAS must reread and recompute; a lost reply keeps
// every identity already persisted by that CAS.
func (h Head) StampSnapshotGenerations() (Head, bool, error) {
if err := h.check(); err != nil {
return Head{}, false, err
}
changed := h.Version == 0
for _, s := range h.Snapshots {
changed = changed || s.Gen == 0
}
if !changed {
return h, false, nil
}
if h.Gen == ^uint64(0) {
return Head{}, false, ErrHeadGenerationExhausted
}
next := h.clone()
next.Version = HeadVersion1
for name, s := range next.Snapshots {
if s.Gen == 0 {
s.Gen = h.Gen + 1
next.Snapshots[name] = s
}
}
return next, true, nil
}
// DeleteSnapshotAt removes only an already admitted incarnation. Admission
// resolves initial absence separately; a retained target that has since gone
// or been replaced succeeds without removing anything. Existing dependent
// and volume-state checks still apply to an actual removal.
func (h Head) DeleteSnapshotAt(name string, gen uint64) (Head, bool, error) {
if gen == 0 {
return Head{}, false, ErrSnapshotGenerationMissing
}
if h.State != StateLive && h.State != StateDetached {
return Head{}, false, fmt.Errorf("%w: HEAD is %s", ErrVolumeDeleting, h.State)
}
s, found := h.Snapshots[name]
if !found {
return h, false, nil
}
if s.Gen == 0 {
return Head{}, false, ErrSnapshotGenerationMissing
}
if s.Gen != gen {
return h, false, nil
}
return h.DeleteSnapshot(name)
}
// RunDeleteSnapshotAt preserves the captured target across the conditional
// update; the caller never resolves the current name to a replacement target.
func RunDeleteSnapshotAt(ctx context.Context, st HeadStore, name string, gen uint64) (Head, error) {
return runTransition(ctx, st, CauseSnapshotDelete, func(h Head) (Head, bool, error) {
return h.DeleteSnapshotAt(name, gen)
})
}
@@ -0,0 +1,182 @@
package layout
import (
"bytes"
"testing"
)
// Fixed bytes cover an unbound snapshot: its identity does not depend on
// request-id metadata, the current image, a timestamp, or the current HEAD gen.
func TestSnapshotPublishingGenerationGolden(t *testing.T) {
raw := []byte(`{"version":1,"volume_id":"00000000000000000000000000000001","epoch":0,"holder":"","activity":{"kind":"idle"},"position":0,"snapshots":{"daily":{"root":"0000000000000000000000000000000000000000000000000000000000000000","gen":42}}}`)
id, err := ParseVolumeID("00000000000000000000000000000001")
if err != nil {
t.Fatal(err)
}
h, err := DecodeHead(raw, 50, id)
if err != nil {
t.Fatal(err)
}
got, err := h.Encode()
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, raw) {
t.Fatalf("publishing identity lost: %s", got)
}
}
func TestLegacySnapshotStampKeepsOneIdentityAcrossRetry(t *testing.T) {
h := idleHead()
h.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}}, "scheduled": {Root: RootName{}}}
next, changed, err := h.StampSnapshotGenerations()
if err != nil || !changed {
t.Fatalf("stamp: changed=%v err=%v", changed, err)
}
if next.Version != HeadVersion1 || next.Snapshots["daily"].Gen != 8 || next.Snapshots["scheduled"].Gen != 8 {
t.Fatalf("stamp: %+v", next)
}
if h.Snapshots["daily"].Gen != 0 || h.Version != 0 {
t.Fatal("input mutated before CAS")
}
raw, err := next.Encode()
if err != nil {
t.Fatal(err)
}
persisted, err := DecodeHead(raw, 8, h.VolumeID)
if err != nil {
t.Fatal(err)
}
again, changed, err := persisted.StampSnapshotGenerations()
if err != nil || changed || again.Snapshots["daily"].Gen != 8 {
t.Fatalf("lost answer reminted identity: %+v changed=%v err=%v", again, changed, err)
}
// An unrelated HEAD write changes the CAS generation, never snapshot identity.
persisted.Gen = 19
again, changed, err = persisted.StampSnapshotGenerations()
if err != nil || changed || again.Snapshots["daily"].Gen != 8 {
t.Fatal("unrelated HEAD update changed incarnation")
}
}
func TestSnapshotDeleteTargetSparesAnUnchangedImageRecreation(t *testing.T) {
h := idleHead()
h.Version = HeadVersion1
h.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}, Gen: 8}}
// The image and position are unchanged, only the publication is new.
recreated := h.clone()
s := recreated.Snapshots["daily"]
s.Gen = 12
recreated.Snapshots["daily"] = s
next, changed, err := recreated.DeleteSnapshotAt("daily", 8)
if err != nil || changed || next.Snapshots["daily"].Gen != 12 {
t.Fatalf("stale target removed replacement: %+v %v %v", next, changed, err)
}
next, changed, err = h.DeleteSnapshotAt("daily", 8)
if err != nil || !changed || len(next.Snapshots) != 0 {
t.Fatalf("exact target not removed: %+v %v %v", next, changed, err)
}
_, changed, err = next.DeleteSnapshotAt("daily", 8)
if err != nil || changed {
t.Fatal("admitted target already gone must succeed without removal")
}
legacy := idleHead()
legacy.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}}}
if _, _, err = legacy.DeleteSnapshotAt("daily", 8); err != ErrSnapshotGenerationMissing {
t.Fatalf("legacy admission must require stamp: %v", err)
}
if _, _, err = h.DeleteSnapshotAt("daily", 0); err != ErrSnapshotGenerationMissing {
t.Fatalf("zero became an identity: %v", err)
}
}
func TestSnapshotGenerationRefusesInvalidBytesAndKeepsLegacyBytes(t *testing.T) {
h := idleHead()
h.Snapshots = map[string]Snapshot{"legacy": {Root: RootName{}}}
raw, err := h.Encode()
if err != nil {
t.Fatal(err)
}
decoded, err := DecodeHead(raw, h.Gen, h.VolumeID)
if err != nil || decoded.Snapshots["legacy"].Gen != 0 {
t.Fatalf("legacy: %v", err)
}
again, err := decoded.Encode()
if err != nil || !bytes.Equal(again, raw) {
t.Fatal("legacy bytes changed")
}
h.Version = HeadVersion1
s := h.Snapshots["legacy"]
s.Gen = 8
h.Snapshots["legacy"] = s
raw, err = h.Encode()
if err != nil {
t.Fatal(err)
}
zero := bytes.Replace(raw, []byte(`"gen":8`), []byte(`"gen":0`), 1)
if _, err = DecodeHead(zero, 8, h.VolumeID); err == nil {
t.Fatal("explicit zero accepted")
}
oldVersion := bytes.Replace(raw, []byte(`"version":1,`), nil, 1)
if _, err = DecodeHead(oldVersion, 8, h.VolumeID); err == nil {
t.Fatal("v1.0 accepted publishing generation")
}
exhausted := idleHead()
exhausted.Gen = ^uint64(0)
exhausted.Snapshots = map[string]Snapshot{"legacy": {Root: RootName{}}}
if _, _, err = exhausted.StampSnapshotGenerations(); err != ErrHeadGenerationExhausted {
t.Fatalf("exhaustion: %v", err)
}
}
func TestSnapshotDeleteTargetKeepsDependentAndStateGuards(t *testing.T) {
h := idleHead()
h.Version = HeadVersion1
h.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}, Gen: 8, Dependents: deps(RootName{}, "target")}}
if _, _, err := h.DeleteSnapshotAt("daily", 8); err == nil {
t.Fatal("dependent bypassed")
}
h.State = StateDeleting
if _, _, err := h.DeleteSnapshotAt("daily", 8); err == nil {
t.Fatal("volume deleting bypassed")
}
}
func TestSnapshotDeleteCASConflictKeepsCapturedIncarnation(t *testing.T) {
h := idleHead()
h.Version = HeadVersion1
h.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}, Gen: 7}}
st := &memHead{h: &h}
st.hook = func() { s := st.h.Snapshots["daily"]; s.Gen = 9; st.h.Snapshots["daily"] = s; st.h.Gen = 9 }
if _, err := RunDeleteSnapshotAt(t.Context(), st, "daily", 7); err != ErrPrecondition {
t.Fatalf("CAS race: %v", err)
}
next, err := RunDeleteSnapshotAt(t.Context(), st, "daily", 7)
if err != nil || next.Snapshots["daily"].Gen != 9 {
t.Fatalf("retry removed replacement: %+v %v", next, err)
}
}
func TestDeleteSnapshotAt_Closure(t *testing.T) {
h := idleHead()
h.Version = HeadVersion1
h.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}, Gen: 7}}
next, changed, err := h.DeleteSnapshotAt("daily", 7)
if err != nil || !changed {
t.Fatalf("removal: %v %v", changed, err)
}
if _, err := next.Encode(); err != nil {
t.Fatalf("result cannot encode: %v", err)
}
}
func TestRunDeleteSnapshotAt_InterruptAtEveryStep(t *testing.T) {
h := idleHead()
h.Version = HeadVersion1
h.Snapshots = map[string]Snapshot{"daily": {Root: RootName{}, Gen: 7}}
interruptHead(t, h, func(st HeadStore) error { _, err := RunDeleteSnapshotAt(t.Context(), st, "daily", 7); return err }, func(t *testing.T, next Head) {
if _, found := next.Snapshots["daily"]; found {
t.Fatal("target still present")
}
})
}
+6
View File
@@ -1395,3 +1395,9 @@ same-process retries; a repeated or earlier frontier is not progress. Late
progress cannot clear an already elapsed inactivity window. The existing
same-epoch promotion-ready fact alone clears the timeout latch. C.L's start
rows remain STUB until recovery and attach controls are qualified together.
### Snapshot incarnation format integration
| ID | Statement | Transition | Enforced in | Guard | Model | Status |
|---|---|---|---|---|---|---|
| `INV-SNAPSHOT-INCARNATION-001` | A snapshot identity is its name and immutable publishing HEAD generation within the volume ID. A resumed delete removes only its admitted incarnation; a recreated name is preserved. Zero requires legacy stamping. | M9 snapshot publication and target-qualified removal | `layout/head.go`, `layout/snapshot_generation.go`; producer integration pending | `TestSnapshotPublishingGenerationGolden`, `TestLegacySnapshotStampKeepsOneIdentityAcrossRetry`, `TestSnapshotDeleteTargetSparesAnUnchangedImageRecreation`, `TestSnapshotDeleteCASConflictKeepsCapturedIncarnation` | SnapDelete rows 241-245 | STUB until production stamping and receipt integration |
@@ -0,0 +1,31 @@
# Snapshot incarnation identities
A v1.1 snapshot entry carries `gen`, its publishing HEAD generation. The
identity is the enclosing volume's full ID, the snapshot name and this
immutable generation. Name, root, position and wall-clock creation time
alone cannot distinguish recreation on an unchanged image.
An absent field is a legacy, unstamped snapshot. Zero is not a delete target;
an explicit zero is refused. The first v1.1 write stamps every legacy entry
with that write's generation. Different names may receive the same stamp.
An older binary refuses the new known field, preventing a gen-less replacement.
`Head.StampSnapshotGenerations` prepares this conversion without changing its
input or writing anything. Its caller must retain the ordinary holder and
transition guards and publish conditional on the observed HEAD generation.
After a CAS conflict it rereads and recomputes; after a lost reply it keeps
already persisted identities. Generation exhaustion refuses rather than wraps.
`Head.DeleteSnapshotAt` and `RunDeleteSnapshotAt` act on a previously admitted
`(name, gen)`. They remove only that incarnation, retain dependent and volume
state guards, and succeed without removal if the target has disappeared or
been replaced. An unstamped current entry refuses. New admission is separate:
an initially absent target is not found, and a retained receipt supplies its
original target on every retry without resolving the current name again.
This first slice supplies the format reader/encoder and kernel helpers. It
does not enable the production stamp writer or asynchronous delete executor.
The v1.1 writer integration must stamp every newly published scheduled,
unbound and operation-bound snapshot and preserve all existing nonzero gens.
Any duplicate operation-binding generation must match the entry. These remain
requirements for the producer integration before format declaration.