From 67b5f0184f965dea3b1ecf4566419e98ba72138f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 12:27:56 -0800 Subject: [PATCH 1/8] layout: HEAD record and the Begin transition HEAD is the volume's one mutable entry: epoch and holder, the open transaction (activity idle, snap(session) or clean(session)), the current root and position, and the named snapshots with their dependents (at most 100). Its encoding is canonical JSON; decoding refuses unknown fields and any bytes Encode would not write. Begin moves activity idle -> snap(session) for the holder at HEAD's epoch, by one conditional update on HEAD's generation. Begin of the session already open is a replay and writes nothing; another open session, a cleaning, another epoch or another holder is refused; an absent HEAD is refused and never created. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/head.go | 242 ++++++++++++++++++ .../frontend/chunkstore/layout/head_test.go | 237 +++++++++++++++++ 2 files changed, 479 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/head.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/head_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go new file mode 100644 index 0000000000..e8962acc69 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -0,0 +1,242 @@ +package layout + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" +) + +// HEAD is the one mutable entry of a volume: who holds it (epoch, holder), +// the open transaction (activity), the current image and the named +// snapshots. Every change to it is one conditional update on its +// generation; nothing else is atomic. + +// Activity kinds: no transaction, a snapshot session, a cleaning session. +const ( + ActIdle = "idle" + ActSnap = "snap" + ActClean = "clean" +) + +// MaxSnapshots bounds the named snapshots one HEAD holds. +const MaxSnapshots = 100 + +// Activity is HEAD's open transaction. Session names it; a session id is +// never reused. +type Activity struct { + Kind string `json:"kind"` + Session string `json:"session,omitempty"` +} + +// Snapshot is one named snapshot: its root and the restore targets that +// still name its chunks. +type Snapshot struct { + Root RootName + Dependents []string +} + +// Head is the decoded HEAD. Gen is the generation the store holds it at; +// it is not part of the encoding. +type Head struct { + Gen uint64 + Epoch uint64 + Holder string + Activity Activity + Current *RootName // nil: no image committed yet + Position uint64 + Snapshots map[string]Snapshot +} + +type headDoc struct { + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + Activity Activity `json:"activity"` + Current string `json:"current,omitempty"` + Position uint64 `json:"position"` + Snapshots map[string]snapDoc `json:"snapshots,omitempty"` +} + +type snapDoc struct { + Root string `json:"root"` + Dependents []string `json:"dependents,omitempty"` +} + +func (h Head) check() error { + switch h.Activity.Kind { + case ActIdle: + if h.Activity.Session != "" { + return fmt.Errorf("%w: idle activity names session %q", ErrMalformed, h.Activity.Session) + } + case ActSnap, ActClean: + if h.Activity.Session == "" { + return fmt.Errorf("%w: %s activity without a session", ErrMalformed, h.Activity.Kind) + } + default: + return fmt.Errorf("%w: activity %q", ErrMalformed, h.Activity.Kind) + } + if h.Epoch == 0 || h.Holder == "" { + return fmt.Errorf("%w: HEAD without epoch or holder", ErrMalformed) + } + if len(h.Snapshots) > MaxSnapshots { + return fmt.Errorf("%w: %d snapshots, at most %d", ErrMalformed, len(h.Snapshots), MaxSnapshots) + } + for n, s := range h.Snapshots { + if n == "" { + return fmt.Errorf("%w: unnamed snapshot", ErrMalformed) + } + for i, d := range s.Dependents { + if err := checkOwner(d); err != nil { + return err + } + if i > 0 && s.Dependents[i-1] >= d { + return fmt.Errorf("%w: snapshot %q dependents not sorted and unique", ErrMalformed, n) + } + } + } + return nil +} + +// Encode returns HEAD's canonical bytes (JSON, keys in a fixed order). +func (h Head) Encode() ([]byte, error) { + if err := h.check(); err != nil { + return nil, err + } + d := headDoc{Epoch: h.Epoch, Holder: h.Holder, Activity: h.Activity, Position: h.Position} + 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 { + d.Snapshots[n] = snapDoc{Root: s.Root.String(), Dependents: s.Dependents} + } + } + return json.Marshal(d) +} + +// DecodeHead parses canonical HEAD bytes; unknown fields and non-canonical +// bytes are refused. +func DecodeHead(b []byte, gen uint64) (Head, error) { + 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) + } + h := Head{Gen: gen, Epoch: d.Epoch, Holder: d.Holder, Activity: d.Activity, Position: d.Position} + if d.Current != "" { + rn, err := ParseRootName(d.Current) + if err != nil { + return Head{}, err + } + h.Current = &rn + } + if len(d.Snapshots) > 0 { + h.Snapshots = map[string]Snapshot{} + for n, s := range d.Snapshots { + rn, err := ParseRootName(s.Root) + if err != nil { + return Head{}, err + } + h.Snapshots[n] = Snapshot{Root: rn, Dependents: s.Dependents} + } + } + again, err := h.Encode() + if err != nil { + return Head{}, err + } + if !bytes.Equal(again, b) { + return Head{}, fmt.Errorf("%w: HEAD bytes are not canonical", ErrMalformed) + } + return h, nil +} + +// Refusals of a transition's guard. A refusal changes nothing. +var ( + ErrHeadAbsent = errors.New("layout: HEAD absent") + ErrNotHolder = errors.New("layout: not the holder at HEAD's epoch") + ErrBusy = errors.New("layout: another transaction is open") + ErrNoSession = errors.New("layout: the session is not open") +) + +// HolderID is the identity a transition acts as: the epoch of the line it was +// granted and its server. +type HolderID struct { + Epoch uint64 + Holder string +} + +func (h Head) heldBy(me HolderID) bool { return h.Epoch == me.Epoch && h.Holder == me.Holder } + +// Begin is transition 2: activity idle -> snap(session), by the holder at +// HEAD's epoch. Begin of the session already open is a replay: it returns +// HEAD unchanged and changed=false. Any other open activity is ErrBusy. +func (h Head) Begin(me HolderID, session string) (next Head, changed bool, err error) { + if session == "" { + return Head{}, false, errors.New("layout: Begin needs a session id") + } + if !h.heldBy(me) { + return Head{}, false, fmt.Errorf("%w: HEAD epoch %d holder %q, caller epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder, me.Epoch, me.Holder) + } + switch { + case h.Activity == Activity{Kind: ActSnap, Session: session}: + return h, false, nil + case h.Activity.Kind != ActIdle: + return Head{}, false, fmt.Errorf("%w: %s(%s)", ErrBusy, h.Activity.Kind, h.Activity.Session) + } + next = h.clone() + next.Activity = Activity{Kind: ActSnap, Session: session} + return next, true, nil +} + +func (h Head) clone() Head { + c := h + if h.Current != nil { + rn := *h.Current + c.Current = &rn + } + 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, Dependents: append([]string(nil), s.Dependents...)} + } + } + return c +} + +// ErrPrecondition is returned by HeadStore.Update when HEAD is not at the +// expected generation. +var ErrPrecondition = errors.New("layout: HEAD generation moved") + +// HeadStore is the one entry a volume's transitions write: a read, and a +// conditional update on the generation (the store's only all-or-nothing +// unit). An absent HEAD reads as found=false. +type HeadStore interface { + ReadHead(ctx context.Context) (h Head, found bool, err error) + UpdateHead(ctx context.Context, expectedGen uint64, next Head) error +} + +// RunBegin reads HEAD, applies Begin and commits it by one conditional +// update. A lost reply is resolved by a re-run with the same session: it +// finds snap(session) and returns without writing. An absent HEAD refuses +// (no path creates a HEAD here). +func RunBegin(ctx context.Context, st HeadStore, me HolderID, session string) (Head, error) { + h, found, err := st.ReadHead(ctx) + if err != nil { + return Head{}, err + } + if !found { + return Head{}, ErrHeadAbsent + } + next, changed, err := h.Begin(me, session) + if err != nil || !changed { + return next, err + } + if err := st.UpdateHead(ctx, h.Gen, next); err != nil { + return Head{}, err + } + next.Gen = h.Gen + 1 + return next, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_test.go new file mode 100644 index 0000000000..3e03960115 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/head_test.go @@ -0,0 +1,237 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "testing" +) + +var me = HolderID{Epoch: 3, Holder: "srv-a"} + +func idleHead() Head { + return Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActIdle}} +} + +func TestHead_GoldenEncodingRoundTrip(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + h := Head{Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}, Current: &rn, Position: 42, + Snapshots: map[string]Snapshot{"daily": {Root: rn, Dependents: []string{"t1", "t2"}}}} + b, err := h.Encode() + if err != nil { + t.Fatal(err) + } + want := `{"epoch":3,"holder":"srv-a","activity":{"kind":"snap","session":"s1"},"current":"` + rn.String() + + `","position":42,"snapshots":{"daily":{"root":"` + rn.String() + `","dependents":["t1","t2"]}}}` + if string(b) != want { + t.Fatalf("encoding\n got %s\nwant %s", b, want) + } + back, err := DecodeHead(b, 9) + if err != nil { + t.Fatal(err) + } + if back.Gen != 9 || back.Current == nil || *back.Current != rn || back.Snapshots["daily"].Root != rn { + t.Fatalf("decoded %+v", back) + } + if b2, _ := back.Encode(); string(b2) != want { + t.Fatal("re-encoding differs") + } +} + +func TestHead_Refusals(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + many := map[string]Snapshot{} + for i := 0; i <= MaxSnapshots; i++ { + many[fmt.Sprintf("s%03d", i)] = Snapshot{Root: rn} + } + for name, h := range map[string]Head{ + "idle with a session": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle, Session: "s"}}, + "snap without a session": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActSnap}}, + "unknown activity": {Epoch: 1, Holder: "a", Activity: Activity{Kind: "open"}}, + "epoch zero": {Holder: "a", Activity: Activity{Kind: ActIdle}}, + "no holder": {Epoch: 1, Activity: Activity{Kind: ActIdle}}, + "dependents unsorted": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []string{"b", "a"}}}}, + "dependent twice": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []string{"a", "a"}}}}, + "bad dependent": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []string{"a/b"}}}}, + "too many snapshots": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: many}, + } { + if _, err := h.Encode(); !errors.Is(err, ErrMalformed) { + t.Errorf("%s: %v; want ErrMalformed", name, err) + } + } + good, _ := idleHead().Encode() + for name, b := range map[string]string{ + "unknown field": strings.Replace(string(good), `"position"`, `"extra":1,"position"`, 1), + "whitespace": strings.Replace(string(good), `,`, `, `, 1), + "bad root": strings.Replace(string(good), `"position"`, `"current":"xyz","position"`, 1), + "not json": "HEAD", + } { + if _, err := DecodeHead([]byte(b), 1); !errors.Is(err, ErrMalformed) { + t.Errorf("decode %s: %v; want ErrMalformed", name, err) + } + } +} + +// Begin's closure row: idle -> snap(s); snap(s) again is a replay; any +// other open activity, another epoch or another holder is refused and +// changes nothing. +func TestBegin_Closure(t *testing.T) { + h := idleHead() + next, changed, err := h.Begin(me, "s1") + if err != nil || !changed || next.Activity != (Activity{Kind: ActSnap, Session: "s1"}) { + t.Fatalf("Begin from idle: %+v %t %v", next, changed, err) + } + if h.Activity.Kind != ActIdle { + t.Fatal("Begin changed its receiver") + } + if again, changed, err := next.Begin(me, "s1"); err != nil || changed || again.Activity != next.Activity { + t.Fatalf("Begin of the open session: %+v %t %v; want a replay", again, changed, err) + } + for name, tc := range map[string]struct { + h Head + me HolderID + want error + }{ + "other session open": {next, me, ErrBusy}, + "cleaning": {Head{Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "c1"}}, me, ErrBusy}, + "older caller epoch": {h, HolderID{Epoch: 2, Holder: "srv-a"}, ErrNotHolder}, + "newer caller epoch": {h, HolderID{Epoch: 4, Holder: "srv-a"}, ErrNotHolder}, + "other holder": {h, HolderID{Epoch: 3, Holder: "srv-b"}, ErrNotHolder}, + } { + session := "s2" + if _, _, err := tc.h.Begin(tc.me, session); !errors.Is(err, tc.want) { + t.Errorf("%s: %v; want %v", name, err, tc.want) + } + } + if _, _, err := h.Begin(me, ""); err == nil { + t.Error("Begin without a session id accepted") + } +} + +// memHead is a HEAD entry with a generation, and optional kill points: the +// n-th update dies before it applies, or applies and loses its reply. +type memHead struct { + mu sync.Mutex + h *Head + updates int + killAt int + after bool + dead bool + hook func() // runs between a read and the next update +} + +var errKilled = errors.New("process killed") + +func (m *memHead) ReadHead(context.Context) (Head, bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.dead { + return Head{}, false, errKilled + } + if m.h == nil { + return Head{}, false, nil + } + b, _ := m.h.Encode() + h, err := DecodeHead(b, m.h.Gen) + return h, true, err +} + +func (m *memHead) UpdateHead(_ context.Context, gen uint64, next Head) error { + if m.hook != nil { + hk := m.hook + m.hook = nil + hk() + } + m.mu.Lock() + defer m.mu.Unlock() + if m.dead { + return errKilled + } + m.updates++ + kill := m.updates == m.killAt + if kill && !m.after { + m.dead = true + return errKilled + } + if m.h == nil || m.h.Gen != gen { + return ErrPrecondition + } + if _, err := next.Encode(); err != nil { + return err + } + n := next.clone() + n.Gen = gen + 1 + m.h = &n + if kill { + m.dead = true + return errKilled + } + return nil +} + +func (m *memHead) restart() { m.mu.Lock(); m.dead = false; m.killAt = 0; m.mu.Unlock() } + +func TestRunBegin(t *testing.T) { + ctx := context.Background() + h := idleHead() + st := &memHead{h: &h} + got, err := RunBegin(ctx, st, me, "s1") + if err != nil || got.Activity.Session != "s1" || got.Gen != 8 || st.h.Gen != 8 { + t.Fatalf("RunBegin: %+v %v (store gen %d)", got, err, st.h.Gen) + } + if _, err := RunBegin(ctx, &memHead{}, me, "s1"); !errors.Is(err, ErrHeadAbsent) { + t.Fatalf("RunBegin over an absent HEAD: %v; want ErrHeadAbsent", err) + } + // Another writer moves HEAD between the read and the update: refused, + // nothing written by this Begin. + h2 := idleHead() + st2 := &memHead{h: &h2} + st2.hook = func() { st2.h.Gen++ } + if _, err := RunBegin(ctx, st2, me, "s1"); !errors.Is(err, ErrPrecondition) { + t.Fatalf("RunBegin racing another writer: %v; want ErrPrecondition", err) + } + if st2.h.Activity.Kind != ActIdle { + t.Fatalf("HEAD after the refused Begin: %+v", st2.h.Activity) + } +} + +// Interrupt at every step: RunBegin killed at each of its HEAD writes +// (before it applies, and applied with its reply lost), then re-run with +// the same session, ends in snap(session) with exactly one generation +// step; a further re-run writes nothing. +func TestRunBegin_InterruptAtEveryStep(t *testing.T) { + ctx := context.Background() + count := &memHead{h: func() *Head { h := idleHead(); return &h }()} + if _, err := RunBegin(ctx, count, me, "s1"); err != nil { + t.Fatal(err) + } + steps := count.updates + if steps != 1 { + t.Fatalf("Begin made %d HEAD writes; want 1", steps) + } + for k := 1; k <= steps; k++ { + for _, after := range []bool{false, true} { + t.Run(fmt.Sprintf("write%d/after=%t", k, after), func(t *testing.T) { + h := idleHead() + st := &memHead{h: &h, killAt: k, after: after} + if _, err := RunBegin(ctx, st, me, "s1"); !errors.Is(err, errKilled) { + t.Fatalf("killed run: %v", err) + } + st.restart() + got, err := RunBegin(ctx, st, me, "s1") + if err != nil || got.Activity != (Activity{Kind: ActSnap, Session: "s1"}) { + t.Fatalf("re-run: %+v %v", got, err) + } + if st.h.Gen != 8 { + t.Fatalf("HEAD gen %d after the re-run; want 8 (one step)", st.h.Gen) + } + before := st.updates + if _, err := RunBegin(ctx, st, me, "s1"); err != nil || st.updates != before { + t.Fatalf("second re-run: %v, wrote %d times", err, st.updates-before) + } + }) + } + } +} From b3c7ae2b0b369e5b081204cabfe710dfd4a8f873 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 12:41:40 -0800 Subject: [PATCH 2/8] layout: one HEAD write path and its guard Begin now writes through runTransition, the one read-apply-update path every transition will use. A source-scan guard holds for the whole series without edits: only runTransition calls UpdateHead and the store cannot create a HEAD; every Run transition must have its closure and interrupt tests; only a claim waits for the old lease; and no function removes a store object until removal brings its own lease re-check. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/layout/guard_test.go | 136 ++++++++++++++++++ .../core/frontend/chunkstore/layout/head.go | 8 +- 2 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/guard_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go new file mode 100644 index 0000000000..d8e2868c1d --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -0,0 +1,136 @@ +package layout + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "reflect" + "sort" + "strings" + "testing" +) + +// funcCalls maps each function of the package's files (tests or not) to +// the names it calls. +func funcCalls(t *testing.T, tests bool) map[string]map[string]bool { + t.Helper() + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + out := map[string]map[string]bool{} + for _, f := range files { + if strings.HasSuffix(f, "_test.go") != tests { + continue + } + src, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + file, err := parser.ParseFile(token.NewFileSet(), f, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range file.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + name := fn.Name.Name + if fn.Recv != nil && len(fn.Recv.List) == 1 { + switch x := fn.Recv.List[0].Type.(type) { + case *ast.Ident: + name = x.Name + "." + name + case *ast.StarExpr: + name = x.X.(*ast.Ident).Name + "." + name + } + } + calls := map[string]bool{} + ast.Inspect(fn.Body, func(n ast.Node) bool { + if c, ok := n.(*ast.CallExpr); ok { + switch x := c.Fun.(type) { + case *ast.SelectorExpr: + calls[x.Sel.Name] = true + case *ast.Ident: + calls[x.Name] = true + } + } + return true + }) + out[name] = calls + } + } + return out +} + +// Guard enumeration for the facts this package writes. It holds at every +// step of the series without edits: a new writer, transition or remover +// fails it until it brings the tests named here. +// +// - HEAD: the only UpdateHead call is in runTransition (read, one pure +// step, one conditional update); the store has no way to create a HEAD. +// - Transitions: every Run through runTransition has a closure test +// (Test_Closure) and an interrupt test (TestRun_InterruptAtEveryStep). +// - Lease, claim half: only RunClaim calls OldLeaseEnded, and RunClaim, +// where it exists, calls it. +// - Pool: no function removes a store object yet; the removal that comes +// with cleaning must update this guard and bring its lease re-check. +func TestGuard_WritersTransitionsAndRemovers(t *testing.T) { + code := funcCalls(t, false) + tests := funcCalls(t, true) + var writers []string + for fn, cs := range code { + if cs["UpdateHead"] { + writers = append(writers, fn) + } + } + sort.Strings(writers) + if !reflect.DeepEqual(writers, []string{"runTransition"}) { + t.Errorf("functions calling UpdateHead: %v; want only runTransition", writers) + } + st := reflect.TypeOf((*HeadStore)(nil)).Elem() + var methods []string + for i := 0; i < st.NumMethod(); i++ { + methods = append(methods, st.Method(i).Name) + } + if !reflect.DeepEqual(methods, []string{"ReadHead", "UpdateHead"}) { + t.Errorf("HeadStore methods %v; want ReadHead and UpdateHead only (no path creates a HEAD)", methods) + } + var runs []string + for fn, cs := range code { + if !cs["runTransition"] { + continue + } + runs = append(runs, fn) + x, ok := strings.CutPrefix(fn, "Run") + if !ok { + t.Errorf("%s calls runTransition; transitions are exported Run functions", fn) + continue + } + for _, want := range []string{"Test" + x + "_Closure", "TestRun" + x + "_InterruptAtEveryStep"} { + if _, ok := tests[want]; !ok { + t.Errorf("transition %s has no %s", fn, want) + } + } + } + if len(runs) == 0 { + t.Fatal("no transition found: the scan is broken") + } + for fn, cs := range code { + if cs["OldLeaseEnded"] && fn != "RunClaim" { + t.Errorf("%s calls OldLeaseEnded; only RunClaim claims", fn) + } + } + if cs, ok := code["RunClaim"]; ok && !cs["OldLeaseEnded"] { + t.Error("RunClaim does not wait for the old lease") + } + for fn, cs := range code { + for c := range cs { + if strings.HasPrefix(c, "Delete") || strings.HasPrefix(c, "Remove") { + t.Errorf("%s calls %s: a store remover needs its lease re-check and its own guard row", fn, c) + } + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index e8962acc69..d93c76a41d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -223,6 +223,12 @@ type HeadStore interface { // finds snap(session) and returns without writing. An absent HEAD refuses // (no path creates a HEAD here). func RunBegin(ctx context.Context, st HeadStore, me HolderID, session string) (Head, error) { + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h.Begin(me, session) }) +} + +// runTransition is read HEAD, apply t, and one conditional update when t +// changed it. An absent HEAD is refused: no transition creates one. +func runTransition(ctx context.Context, st HeadStore, t func(Head) (Head, bool, error)) (Head, error) { h, found, err := st.ReadHead(ctx) if err != nil { return Head{}, err @@ -230,7 +236,7 @@ func RunBegin(ctx context.Context, st HeadStore, me HolderID, session string) (H if !found { return Head{}, ErrHeadAbsent } - next, changed, err := h.Begin(me, session) + next, changed, err := t(h) if err != nil || !changed { return next, err } From 84746790e9770ee6249e57c4a90dcb5dd81f1ca7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 12:47:56 -0800 Subject: [PATCH 3/8] layout: refuse HEAD names that are not valid UTF-8 The JSON encoding turns invalid UTF-8 into U+FFFD and still re-encodes the same, so HEAD would store another holder, session, snapshot or dependent name than the caller gave and a later lookup by that name would find nothing. check() refuses such names, and runTransition checks the next HEAD before writing it. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/head.go | 24 +++++++++++++++++++ .../frontend/chunkstore/layout/head_test.go | 23 ++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index d93c76a41d..77e1b82158 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "unicode/utf8" ) // HEAD is the one mutable entry of a volume: who holds it (epoch, holder), @@ -63,7 +64,21 @@ type snapDoc struct { Dependents []string `json:"dependents,omitempty"` } +// validName refuses a string the JSON encoding would not keep byte for +// byte (invalid UTF-8 becomes U+FFFD). +func validName(field, v string) error { + if !utf8.ValidString(v) { + return fmt.Errorf("%w: %s %q is not valid UTF-8", ErrMalformed, field, v) + } + return nil +} + func (h Head) check() error { + for field, v := range map[string]string{"holder": h.Holder, "session": h.Activity.Session} { + if err := validName(field, v); err != nil { + return err + } + } switch h.Activity.Kind { case ActIdle: if h.Activity.Session != "" { @@ -86,7 +101,13 @@ func (h Head) check() error { if n == "" { return fmt.Errorf("%w: unnamed snapshot", ErrMalformed) } + if err := validName("snapshot", n); err != nil { + return err + } for i, d := range s.Dependents { + if err := validName("dependent", d); err != nil { + return err + } if err := checkOwner(d); err != nil { return err } @@ -240,6 +261,9 @@ func runTransition(ctx context.Context, st HeadStore, t func(Head) (Head, bool, if err != nil || !changed { return next, err } + if err := next.check(); err != nil { + return Head{}, err + } if err := st.UpdateHead(ctx, h.Gen, next); err != nil { return Head{}, err } diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_test.go index 3e03960115..7440bcc3d9 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_test.go @@ -235,3 +235,26 @@ func TestRunBegin_InterruptAtEveryStep(t *testing.T) { } } } + +// A name that is not valid UTF-8 would be stored as U+FFFD by the JSON +// encoding (and still re-encode the same), so HEAD would hold another name +// than the caller gave: refused on every string field. +func TestHead_RefusesInvalidUTF8(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + bad := "a\xff" + for name, h := range map[string]Head{ + "holder": {Epoch: 1, Holder: bad, Activity: Activity{Kind: ActIdle}}, + "session": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActSnap, Session: bad}}, + "snapshot": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{bad: {Root: rn}}}, + "dependent": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []string{bad}}}}, + } { + if _, err := h.Encode(); !errors.Is(err, ErrMalformed) { + t.Errorf("%s %q: %v; want ErrMalformed", name, bad, err) + } + } + h := idleHead() + st := &memHead{h: &h} + if _, err := RunBegin(context.Background(), st, me, bad); err == nil || st.h.Activity.Kind != ActIdle { + t.Fatalf("Begin with an invalid UTF-8 session: %v, HEAD %+v; want refused, nothing written", err, st.h.Activity) + } +} From a842778c590fda2790b5edb901274bfa80e23e45 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 12:54:44 -0800 Subject: [PATCH 4/8] test: the HEAD guard sees every use of a writer name, not only calls The guard now records every use of UpdateHead, runTransition, OldLeaseEnded and Delete/Remove names, in function bodies and in package-level initializers: a call, a method value or alias, a method expression and an inline interface all count. Negative controls add each form to the package's real sources and must be refused. The comments on invalid UTF-8 now state what the old encoding did: it wrote an escaped U+FFFD that its own canonical decode refused. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/layout/guard_test.go | 282 ++++++++++++------ .../core/frontend/chunkstore/layout/head.go | 3 +- .../frontend/chunkstore/layout/head_test.go | 7 +- 3 files changed, 196 insertions(+), 96 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index d8e2868c1d..403a5defcb 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -12,83 +12,185 @@ import ( "testing" ) -// funcCalls maps each function of the package's files (tests or not) to -// the names it calls. -func funcCalls(t *testing.T, tests bool) map[string]map[string]bool { +// pkgLevel is the owner of a reference outside any function body: a +// package-level var or const initializer. +const pkgLevel = "" + +// refs maps every name used in the given sources (a selector's name, as in +// st.UpdateHead, called or not, or a plain identifier, as in runTransition) +// to the functions that use it: a method value, an alias, a call and a +// package-level initializer all count. Declarations are not uses: function +// and type names, interface method names and struct field names. +func refs(t *testing.T, srcs map[string]string) map[string]map[string]bool { t.Helper() - files, err := filepath.Glob("*.go") - if err != nil { - t.Fatal(err) - } out := map[string]map[string]bool{} - for _, f := range files { - if strings.HasSuffix(f, "_test.go") != tests { - continue + add := func(name, owner string) { + if out[name] == nil { + out[name] = map[string]bool{} } - src, err := os.ReadFile(f) - if err != nil { - t.Fatal(err) - } - file, err := parser.ParseFile(token.NewFileSet(), f, src, 0) + out[name][owner] = true + } + visit := func(n ast.Node, owner string) { + ast.Inspect(n, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.SelectorExpr: + add(x.Sel.Name, owner) + ast.Inspect(x.X, func(n ast.Node) bool { + if id, ok := n.(*ast.Ident); ok { + add(id.Name, owner) + } + return true + }) + return false + case *ast.Ident: + add(x.Name, owner) + } + return true + }) + } + for name, src := range srcs { + file, err := parser.ParseFile(token.NewFileSet(), name, src, 0) if err != nil { t.Fatal(err) } for _, d := range file.Decls { - fn, ok := d.(*ast.FuncDecl) - if !ok || fn.Body == nil { - continue - } - name := fn.Name.Name - if fn.Recv != nil && len(fn.Recv.List) == 1 { - switch x := fn.Recv.List[0].Type.(type) { - case *ast.Ident: - name = x.Name + "." + name - case *ast.StarExpr: - name = x.X.(*ast.Ident).Name + "." + name + switch d := d.(type) { + case *ast.FuncDecl: + if d.Body == nil { + continue } - } - calls := map[string]bool{} - ast.Inspect(fn.Body, func(n ast.Node) bool { - if c, ok := n.(*ast.CallExpr); ok { - switch x := c.Fun.(type) { - case *ast.SelectorExpr: - calls[x.Sel.Name] = true + owner := d.Name.Name + if d.Recv != nil && len(d.Recv.List) == 1 { + switch x := d.Recv.List[0].Type.(type) { case *ast.Ident: - calls[x.Name] = true + owner = x.Name + "." + owner + case *ast.StarExpr: + owner = x.X.(*ast.Ident).Name + "." + owner } } - return true - }) - out[name] = calls + visit(d.Body, owner) + case *ast.GenDecl: + for _, s := range d.Specs { + if v, ok := s.(*ast.ValueSpec); ok { + for _, e := range v.Values { + visit(e, pkgLevel) + } + } + } + } } } return out } -// Guard enumeration for the facts this package writes. It holds at every -// step of the series without edits: a new writer, transition or remover -// fails it until it brings the tests named here. +func packageSources(t *testing.T, tests bool) map[string]string { + t.Helper() + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + out := map[string]string{} + for _, f := range files { + if strings.HasSuffix(f, "_test.go") != tests { + continue + } + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + out[f] = string(b) + } + return out +} + +func owners(m map[string]bool) []string { + var out []string + for o := range m { + out = append(out, o) + } + sort.Strings(out) + return out +} + +// guardFindings checks the package sources against the guard and returns +// every violation. // -// - HEAD: the only UpdateHead call is in runTransition (read, one pure -// step, one conditional update); the store has no way to create a HEAD. -// - Transitions: every Run through runTransition has a closure test -// (Test_Closure) and an interrupt test (TestRun_InterruptAtEveryStep). -// - Lease, claim half: only RunClaim calls OldLeaseEnded, and RunClaim, -// where it exists, calls it. -// - Pool: no function removes a store object yet; the removal that comes -// with cleaning must update this guard and bring its lease re-check. -func TestGuard_WritersTransitionsAndRemovers(t *testing.T) { - code := funcCalls(t, false) - tests := funcCalls(t, true) - var writers []string - for fn, cs := range code { - if cs["UpdateHead"] { - writers = append(writers, fn) +// - HEAD: UpdateHead is used only in runTransition (read, one pure step, +// one conditional update): no other call, method value, alias or +// package-level use. The store has no way to create a HEAD. +// - Transitions: runTransition is used only by exported Run functions, +// each with Test_Closure and TestRun_InterruptAtEveryStep. +// - Lease, claim half: OldLeaseEnded is used only in RunClaim, and +// RunClaim, where it exists, uses it. +// - Pool: no name starting with Delete or Remove is used yet; the +// removal that comes with cleaning must bring its lease re-check and +// its own row here. +// +// These are syntactic checks of this package's own files: they see any +// use of these names, but not a store effect reached through a name they +// do not list (for example reflection or another package's helper). +func guardFindings(code map[string]map[string]bool, tests map[string]bool) []string { + var bad []string + if got := owners(code["UpdateHead"]); !reflect.DeepEqual(got, []string{"runTransition"}) { + bad = append(bad, "UpdateHead used by "+strings.Join(got, ", ")+"; want only runTransition") + } + var runs []string + for _, fn := range owners(code["runTransition"]) { + x, ok := strings.CutPrefix(fn, "Run") + if !ok { + bad = append(bad, fn+" uses runTransition; transitions are exported Run functions") + continue + } + runs = append(runs, fn) + for _, want := range []string{"Test" + x + "_Closure", "TestRun" + x + "_InterruptAtEveryStep"} { + if !tests[want] { + bad = append(bad, "transition "+fn+" has no "+want) + } } } - sort.Strings(writers) - if !reflect.DeepEqual(writers, []string{"runTransition"}) { - t.Errorf("functions calling UpdateHead: %v; want only runTransition", writers) + if len(runs) == 0 { + bad = append(bad, "no transition uses runTransition: the scan is broken") + } + for _, fn := range owners(code["OldLeaseEnded"]) { + if fn != "RunClaim" { + bad = append(bad, fn+" uses OldLeaseEnded; only RunClaim claims") + } + } + if _, ok := code["RunClaim"]; ok && !code["OldLeaseEnded"]["RunClaim"] { + bad = append(bad, "RunClaim does not wait for the old lease") + } + for name, by := range code { + if strings.HasPrefix(name, "Delete") || strings.HasPrefix(name, "Remove") { + bad = append(bad, strings.Join(owners(by), ", ")+" uses "+name+": a store remover needs its lease re-check and its own guard row") + } + } + sort.Strings(bad) + return bad +} + +// declared returns the names of the functions the sources declare. +func declared(t *testing.T, srcs map[string]string) map[string]bool { + t.Helper() + out := map[string]bool{} + for name, src := range srcs { + file, err := parser.ParseFile(token.NewFileSet(), name, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range file.Decls { + if fn, ok := d.(*ast.FuncDecl); ok && fn.Recv == nil { + out[fn.Name.Name] = true + } + } + } + return out +} + +func TestGuard_WritersTransitionsAndRemovers(t *testing.T) { + code := refs(t, packageSources(t, false)) + tests := declared(t, packageSources(t, true)) + if bad := guardFindings(code, tests); len(bad) != 0 { + t.Fatalf("guard: %s", strings.Join(bad, "\n")) } st := reflect.TypeOf((*HeadStore)(nil)).Elem() var methods []string @@ -96,41 +198,37 @@ func TestGuard_WritersTransitionsAndRemovers(t *testing.T) { methods = append(methods, st.Method(i).Name) } if !reflect.DeepEqual(methods, []string{"ReadHead", "UpdateHead"}) { - t.Errorf("HeadStore methods %v; want ReadHead and UpdateHead only (no path creates a HEAD)", methods) + t.Fatalf("HeadStore methods %v; want ReadHead and UpdateHead only (no path creates a HEAD)", methods) } - var runs []string - for fn, cs := range code { - if !cs["runTransition"] { - continue - } - runs = append(runs, fn) - x, ok := strings.CutPrefix(fn, "Run") - if !ok { - t.Errorf("%s calls runTransition; transitions are exported Run functions", fn) - continue - } - for _, want := range []string{"Test" + x + "_Closure", "TestRun" + x + "_InterruptAtEveryStep"} { - if _, ok := tests[want]; !ok { - t.Errorf("transition %s has no %s", fn, want) - } - } - } - if len(runs) == 0 { - t.Fatal("no transition found: the scan is broken") - } - for fn, cs := range code { - if cs["OldLeaseEnded"] && fn != "RunClaim" { - t.Errorf("%s calls OldLeaseEnded; only RunClaim claims", fn) - } - } - if cs, ok := code["RunClaim"]; ok && !cs["OldLeaseEnded"] { - t.Error("RunClaim does not wait for the old lease") - } - for fn, cs := range code { - for c := range cs { - if strings.HasPrefix(c, "Delete") || strings.HasPrefix(c, "Remove") { - t.Errorf("%s calls %s: a store remover needs its lease re-check and its own guard row", fn, c) - } +} + +// Negative controls: each form of an extra HEAD writer, transition or +// remover, added to the package's real sources, is refused; the real +// sources alone pass (the test above). +func TestGuard_Controls(t *testing.T) { + tests := declared(t, packageSources(t, true)) + for name, src := range map[string]string{ + "direct call": `func w(ctx context.Context, st HeadStore, h Head) error { return st.UpdateHead(ctx, h.Gen, h) }`, + "method value alias": `func w(ctx context.Context, st HeadStore, h Head) error { + update := st.UpdateHead + return update(ctx, h.Gen, h) +}`, + "method expression": `func w(ctx context.Context, st HeadStore, h Head) error { return HeadStore.UpdateHead(st, ctx, h.Gen, h) }`, + "package-level var": `var w = HeadStore.UpdateHead`, + "package-level func lit": `var w = func(ctx context.Context, st HeadStore, h Head) error { return st.UpdateHead(ctx, h.Gen, h) }`, + "inline interface": `func w(st HeadStore) { var u interface{ UpdateHead(context.Context, uint64, Head) error } = st; _ = u }`, + "runTransition alias": `func w(ctx context.Context, st HeadStore) { f := runTransition; _, _ = f(ctx, st, nil) }`, + "untested transition": `func RunZz(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) }`, + "lease wait outside claim": `func w(ctx context.Context, l LeaseWait) error { return l.OldLeaseEnded(ctx, 1) }`, + "remover": `type p interface{ DeleteObject(context.Context, string) error } +func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, + "remover method value": `type p interface{ RemoveName(string) } +func w(x p) { f := x.RemoveName; f("o") }`, + } { + srcs := packageSources(t, false) + srcs["zz_control.go"] = "package layout\n\nimport \"context\"\n\nvar _ context.Context\n\n" + src + "\n" + if bad := guardFindings(refs(t, srcs), tests); len(bad) == 0 { + t.Errorf("control %q passed the guard", name) } } } diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index 77e1b82158..4788836b86 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -65,7 +65,8 @@ type snapDoc struct { } // validName refuses a string the JSON encoding would not keep byte for -// byte (invalid UTF-8 becomes U+FFFD). +// byte: invalid UTF-8 is written as an escaped U+FFFD, which DecodeHead's +// canonical check then refuses. func validName(field, v string) error { if !utf8.ValidString(v) { return fmt.Errorf("%w: %s %q is not valid UTF-8", ErrMalformed, field, v) diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_test.go index 7440bcc3d9..e1b8725788 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_test.go @@ -236,9 +236,10 @@ func TestRunBegin_InterruptAtEveryStep(t *testing.T) { } } -// A name that is not valid UTF-8 would be stored as U+FFFD by the JSON -// encoding (and still re-encode the same), so HEAD would hold another name -// than the caller gave: refused on every string field. +// A name that is not valid UTF-8 is written by the JSON encoding as an +// escaped U+FFFD, and DecodeHead's canonical check then refuses those +// bytes: Encode would succeed with a HEAD its own decoder cannot read. +// Refused at Encode on every string field. func TestHead_RefusesInvalidUTF8(t *testing.T) { rn := RootName{Hash: Sum([]byte("r"))} bad := "a\xff" From 928e6a75aa7e474623e29ca7dd7b127f24e86488 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 13:07:35 -0800 Subject: [PATCH 5/8] test: the guard requires a declared claim to wait for the old lease The lease rule checked whether the name RunClaim was used, not whether the function was declared, so a declared RunClaim with no wait passed. The guard now checks the package's declared functions: a declared RunClaim must use OldLeaseEnded, and every declared exported Run function must go through runTransition. Each negative control now asserts the finding it is meant to cause. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/layout/guard_test.go | 62 ++++++++++++------- 1 file changed, 38 insertions(+), 24 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index 403a5defcb..264d96dd7b 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -121,7 +121,8 @@ func owners(m map[string]bool) []string { // - Transitions: runTransition is used only by exported Run functions, // each with Test_Closure and TestRun_InterruptAtEveryStep. // - Lease, claim half: OldLeaseEnded is used only in RunClaim, and -// RunClaim, where it exists, uses it. +// RunClaim, when it is declared, uses it. +// - Every declared exported Run function goes through runTransition. // - Pool: no name starting with Delete or Remove is used yet; the // removal that comes with cleaning must bring its lease re-check and // its own row here. @@ -129,7 +130,7 @@ func owners(m map[string]bool) []string { // These are syntactic checks of this package's own files: they see any // use of these names, but not a store effect reached through a name they // do not list (for example reflection or another package's helper). -func guardFindings(code map[string]map[string]bool, tests map[string]bool) []string { +func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) []string { var bad []string if got := owners(code["UpdateHead"]); !reflect.DeepEqual(got, []string{"runTransition"}) { bad = append(bad, "UpdateHead used by "+strings.Join(got, ", ")+"; want only runTransition") @@ -156,8 +157,13 @@ func guardFindings(code map[string]map[string]bool, tests map[string]bool) []str bad = append(bad, fn+" uses OldLeaseEnded; only RunClaim claims") } } - if _, ok := code["RunClaim"]; ok && !code["OldLeaseEnded"]["RunClaim"] { - bad = append(bad, "RunClaim does not wait for the old lease") + if decl["RunClaim"] && !code["OldLeaseEnded"]["RunClaim"] { + bad = append(bad, "RunClaim is declared and does not wait for the old lease") + } + for fn := range decl { + if strings.HasPrefix(fn, "Run") && !code["runTransition"][fn] { + bad = append(bad, fn+" is declared and does not go through runTransition") + } } for name, by := range code { if strings.HasPrefix(name, "Delete") || strings.HasPrefix(name, "Remove") { @@ -187,9 +193,10 @@ func declared(t *testing.T, srcs map[string]string) map[string]bool { } func TestGuard_WritersTransitionsAndRemovers(t *testing.T) { - code := refs(t, packageSources(t, false)) + src := packageSources(t, false) + code := refs(t, src) tests := declared(t, packageSources(t, true)) - if bad := guardFindings(code, tests); len(bad) != 0 { + if bad := guardFindings(code, declared(t, src), tests); len(bad) != 0 { t.Fatalf("guard: %s", strings.Join(bad, "\n")) } st := reflect.TypeOf((*HeadStore)(nil)).Elem() @@ -207,28 +214,35 @@ func TestGuard_WritersTransitionsAndRemovers(t *testing.T) { // sources alone pass (the test above). func TestGuard_Controls(t *testing.T) { tests := declared(t, packageSources(t, true)) - for name, src := range map[string]string{ - "direct call": `func w(ctx context.Context, st HeadStore, h Head) error { return st.UpdateHead(ctx, h.Gen, h) }`, - "method value alias": `func w(ctx context.Context, st HeadStore, h Head) error { + for name, c := range map[string]struct{ src, want string }{ + "direct call": {`func w(ctx context.Context, st HeadStore, h Head) error { return st.UpdateHead(ctx, h.Gen, h) }`, "UpdateHead used by"}, + "method value alias": {`func w(ctx context.Context, st HeadStore, h Head) error { update := st.UpdateHead return update(ctx, h.Gen, h) -}`, - "method expression": `func w(ctx context.Context, st HeadStore, h Head) error { return HeadStore.UpdateHead(st, ctx, h.Gen, h) }`, - "package-level var": `var w = HeadStore.UpdateHead`, - "package-level func lit": `var w = func(ctx context.Context, st HeadStore, h Head) error { return st.UpdateHead(ctx, h.Gen, h) }`, - "inline interface": `func w(st HeadStore) { var u interface{ UpdateHead(context.Context, uint64, Head) error } = st; _ = u }`, - "runTransition alias": `func w(ctx context.Context, st HeadStore) { f := runTransition; _, _ = f(ctx, st, nil) }`, - "untested transition": `func RunZz(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) }`, - "lease wait outside claim": `func w(ctx context.Context, l LeaseWait) error { return l.OldLeaseEnded(ctx, 1) }`, - "remover": `type p interface{ DeleteObject(context.Context, string) error } -func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, - "remover method value": `type p interface{ RemoveName(string) } -func w(x p) { f := x.RemoveName; f("o") }`, +}`, "UpdateHead used by"}, + "method expression": {`func w(ctx context.Context, st HeadStore, h Head) error { return HeadStore.UpdateHead(st, ctx, h.Gen, h) }`, "UpdateHead used by"}, + "package-level var": {`var w = HeadStore.UpdateHead`, "UpdateHead used by"}, + "package-level func lit": {`var w = func(ctx context.Context, st HeadStore, h Head) error { return st.UpdateHead(ctx, h.Gen, h) }`, "UpdateHead used by"}, + "inline interface": {`func w(st HeadStore) { var u interface{ UpdateHead(context.Context, uint64, Head) error } = st; _ = u }`, "UpdateHead used by"}, + "runTransition alias": {`func w(ctx context.Context, st HeadStore) { f := runTransition; _, _ = f(ctx, st, nil) }`, "uses runTransition; transitions are exported"}, + "untested transition": {`func RunZz(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) }`, "has no TestZz_Closure"}, + "lease wait outside claim": {`func w(ctx context.Context, l LeaseWait) error { return l.OldLeaseEnded(ctx, 1) }`, "only RunClaim claims"}, + "remover": {`type p interface{ DeleteObject(context.Context, string) error } +func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, "a store remover"}, + "claim without lease wait": {`func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID) (Head, error) { + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h, false, nil }) +} +func TestClaim_Closure() {} +func TestRunClaim_InterruptAtEveryStep() {}`, "does not wait for the old lease"}, + "transition not through runTransition": {`func RunZz(ctx context.Context, st HeadStore) (Head, error) { h, _, err := st.ReadHead(ctx); return h, err }`, "does not go through runTransition"}, + "remover method value": {`type p interface{ RemoveName(string) } +func w(x p) { f := x.RemoveName; f("o") }`, "a store remover"}, } { srcs := packageSources(t, false) - srcs["zz_control.go"] = "package layout\n\nimport \"context\"\n\nvar _ context.Context\n\n" + src + "\n" - if bad := guardFindings(refs(t, srcs), tests); len(bad) == 0 { - t.Errorf("control %q passed the guard", name) + srcs["zz_control.go"] = "package layout\n\nimport \"context\"\n\nvar _ context.Context\n\n" + c.src + "\n" + bad := guardFindings(refs(t, srcs), declared(t, srcs), tests) + if !strings.Contains(strings.Join(bad, "\n"), c.want) { + t.Errorf("control %q: findings %q; want one containing %q", name, bad, c.want) } } } From 3f682470138c516c8182cbdd0c27a50b8e11f065 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 13:11:16 -0800 Subject: [PATCH 6/8] test: the missing-lease control replaces claim.go Added beside the real claim.go, the control's RunClaim was hidden by the real one's lease wait once claim.go exists; it now replaces the file, as a changed claim would. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/layout/guard_test.go | 46 ++++++++++--------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index 264d96dd7b..c80a292896 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -214,32 +214,36 @@ func TestGuard_WritersTransitionsAndRemovers(t *testing.T) { // sources alone pass (the test above). func TestGuard_Controls(t *testing.T) { tests := declared(t, packageSources(t, true)) - for name, c := range map[string]struct{ src, want string }{ - "direct call": {`func w(ctx context.Context, st HeadStore, h Head) error { return st.UpdateHead(ctx, h.Gen, h) }`, "UpdateHead used by"}, - "method value alias": {`func w(ctx context.Context, st HeadStore, h Head) error { + // A control with a file name replaces that real file (a changed + // claim.go); otherwise it is added beside the real sources. + for name, c := range map[string]struct{ src, want, file string }{ + "direct call": {src: `func w(ctx context.Context, st HeadStore, h Head) error { return st.UpdateHead(ctx, h.Gen, h) }`, want: "UpdateHead used by"}, + "method value alias": {src: `func w(ctx context.Context, st HeadStore, h Head) error { update := st.UpdateHead return update(ctx, h.Gen, h) -}`, "UpdateHead used by"}, - "method expression": {`func w(ctx context.Context, st HeadStore, h Head) error { return HeadStore.UpdateHead(st, ctx, h.Gen, h) }`, "UpdateHead used by"}, - "package-level var": {`var w = HeadStore.UpdateHead`, "UpdateHead used by"}, - "package-level func lit": {`var w = func(ctx context.Context, st HeadStore, h Head) error { return st.UpdateHead(ctx, h.Gen, h) }`, "UpdateHead used by"}, - "inline interface": {`func w(st HeadStore) { var u interface{ UpdateHead(context.Context, uint64, Head) error } = st; _ = u }`, "UpdateHead used by"}, - "runTransition alias": {`func w(ctx context.Context, st HeadStore) { f := runTransition; _, _ = f(ctx, st, nil) }`, "uses runTransition; transitions are exported"}, - "untested transition": {`func RunZz(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) }`, "has no TestZz_Closure"}, - "lease wait outside claim": {`func w(ctx context.Context, l LeaseWait) error { return l.OldLeaseEnded(ctx, 1) }`, "only RunClaim claims"}, - "remover": {`type p interface{ DeleteObject(context.Context, string) error } -func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, "a store remover"}, - "claim without lease wait": {`func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID) (Head, error) { +}`, want: "UpdateHead used by"}, + "method expression": {src: `func w(ctx context.Context, st HeadStore, h Head) error { return HeadStore.UpdateHead(st, ctx, h.Gen, h) }`, want: "UpdateHead used by"}, + "package-level var": {src: `var w = HeadStore.UpdateHead`, want: "UpdateHead used by"}, + "package-level func lit": {src: `var w = func(ctx context.Context, st HeadStore, h Head) error { return st.UpdateHead(ctx, h.Gen, h) }`, want: "UpdateHead used by"}, + "inline interface": {src: `func w(st HeadStore) { var u interface{ UpdateHead(context.Context, uint64, Head) error } = st; _ = u }`, want: "UpdateHead used by"}, + "runTransition alias": {src: `func w(ctx context.Context, st HeadStore) { f := runTransition; _, _ = f(ctx, st, nil) }`, want: "uses runTransition; transitions are exported"}, + "untested transition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) }`, want: "has no TestZz_Closure"}, + "lease wait outside claim": {src: `func w(ctx context.Context, l LeaseWait) error { return l.OldLeaseEnded(ctx, 1) }`, want: "only RunClaim claims"}, + "remover": {src: `type p interface{ DeleteObject(context.Context, string) error } +func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, want: "a store remover"}, + "claim without lease wait": {src: `func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID) (Head, error) { return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h, false, nil }) -} -func TestClaim_Closure() {} -func TestRunClaim_InterruptAtEveryStep() {}`, "does not wait for the old lease"}, - "transition not through runTransition": {`func RunZz(ctx context.Context, st HeadStore) (Head, error) { h, _, err := st.ReadHead(ctx); return h, err }`, "does not go through runTransition"}, - "remover method value": {`type p interface{ RemoveName(string) } -func w(x p) { f := x.RemoveName; f("o") }`, "a store remover"}, +}`, want: "does not wait for the old lease", file: "claim.go"}, + "transition not through runTransition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { h, _, err := st.ReadHead(ctx); return h, err }`, want: "does not go through runTransition"}, + "remover method value": {src: `type p interface{ RemoveName(string) } +func w(x p) { f := x.RemoveName; f("o") }`, want: "a store remover"}, } { srcs := packageSources(t, false) - srcs["zz_control.go"] = "package layout\n\nimport \"context\"\n\nvar _ context.Context\n\n" + c.src + "\n" + file := c.file + if file == "" { + file = "zz_control.go" + } + srcs[file] = "package layout\n\nimport \"context\"\n\nvar _ context.Context\n\n" + c.src + "\n" bad := guardFindings(refs(t, srcs), declared(t, srcs), tests) if !strings.Contains(strings.Join(bad, "\n"), c.want) { t.Errorf("control %q: findings %q; want one containing %q", name, bad, c.want) From 613556ad5ac558214830317c51c5ee2a0fcd20a9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 13:15:17 -0800 Subject: [PATCH 7/8] docs: the snapshot kernel machine and its first ledger rows Part A gains M9, the HEAD transactions of the content-named layout library (diagram and transition table, Begin so far), and Part B gains B.10 with the rows its tests enforce: canonical names and encodings, the one HEAD write path, the HEAD encoding, and Begin. The library has no production caller; the notes say so. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 30 ++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d964c89af6..8459c31115 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -26,6 +26,7 @@ The design is described in three documents, and this one collects their machines - [M5 The cut pipeline](#m5-the-cut-pipeline) - [M6 Chunk lifecycle](#m6-chunk-lifecycle) - [M7. Host background-cut admission](#m7-host-background-cut-admission) + - [M9 Snapshot kernel: HEAD transactions over the content-named layout](#m9-snapshot-kernel-head-transactions-over-the-content-named-layout) - [Part B. Invariant ledger](#part-b-invariant-ledger) - [Part C. Change rules](#part-c-change-rules) - [Part D. Wait ownership](#part-d-wait-ownership) @@ -495,9 +496,23 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO `_RestoringIsSkippedAndCounted`, `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, `_RearmKeepsTheSchedule`. +### M9 Snapshot kernel: HEAD transactions over the content-named layout + +A library, `core/frontend/chunkstore/layout`, with no production caller yet. A volume's HEAD holds its epoch and holder, one activity (`idle`, `snap(s)` or `clean(c)`), the current root and position, and the named snapshots with their dependents. Every transition is one conditional update of HEAD through `runTransition`; no transition creates a HEAD, and an absent HEAD is refused. Objects (chunks, segments, roots) are written first under content names; the commit is the only step that makes them reachable. + +```mermaid +stateDiagram-v2 + [*] --> idle: HEAD created outside this package + idle --> snap: Begin(s) +``` + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| idle | snap(s) | caller is the holder at HEAD's epoch (epoch and server); 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` | + ## Part B. Invariant ledger -325 rows: 255 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 310 new. +329 rows: 259 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 314 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -1029,6 +1044,19 @@ Notes: - `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`: the one-file, one-descriptor, no-range-sync clause is enforced by reading; `TestFlusherCheckpointOverASupersededSyncedRecord` shows why it is load-bearing (a checkpoint over a superseded synced record is safe only if the flusher's sync made the newer record durable; its control, an extent-only sync, loses the older record). `TestSyncCoversWALGuard` checks in the source that the WAL sync and the flusher's extent sync are the one data sync the store opener binds for its file. +### B.10 Snapshot kernel: content-named layout and HEAD transitions + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-SNAPK-NAME-CANONICAL-001` | A chunk is named by its index and the SHA-256 of its bytes under `pool//`; a segment and a root are named by the SHA-256 of their canonical encoding, and decoding refuses any bytes the encoder would not write, so an object has one encoding and one name. | Content-named layout (no state transition) | `core/frontend/chunkstore/layout` `layout.go` `ParseChunkName`, `DecodeSegment`, `DecodeRoot` | `TestParseChunkName_RoundTripAndRefusals`, `TestDecodeSegment_RefusesNonCanonical`, `TestRoot_Refusals`, `TestBuild_ShardsAndIncrementalReuse` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 100 snapshots and sorted unique dependents; unknown fields, non-canonical bytes and names that are not valid UTF-8 are refused at encode and decode, and the next HEAD is checked before it is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `Head.check`, `Head.Encode`, `DecodeHead` | `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestHead_RefusesInvalidUTF8` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | + +Notes: + +- B.10 rows are enforced in a library with no production caller; they say nothing about a running volume until a caller is added and its own rows name these. + ## Part C. Change rules How a fix or a feature is calibrated against this model: From 1506cc5a7a06f77cb9325b01da53432bb663fa1c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 13:58:26 -0800 Subject: [PATCH 8/8] test: classify the layout transitions' HEAD read The HEAD reader enumeration finds the layout package's one read path, runTransition. Over an absent HEAD it refuses with ErrHeadAbsent and writes nothing; a probe pins it with a store whose HEAD is absent. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/head_readers_test.go | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 3af952a2e1..6ebce13b42 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -2,6 +2,7 @@ package chunkstore import ( "context" + "errors" "go/ast" "go/parser" "go/token" @@ -12,6 +13,7 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -38,6 +40,7 @@ var headReaders = map[string]string{ "core/frontend/chunkstore/share_guard.go beginShare -> ReadHead": "refuses outcome_unknown: the HEAD to share is no longer current", "core/frontend/chunkstore/usage.go Usage -> ReadHead": "GAP: reports an empty image, no error (probe Usage)", "core/frontend/chunkstore/verify.go readHead -> LookupEntry": "finding ROOT_INVALID (probe Verify)", + "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", "core/frontend/chunkstore/verify.go run -> LookupEntry": "finding ROOT_INVALID (probe Verify)", "core/frontend/chunkstore/volume_delete.go DeleteVolume -> ReadHead": "operator delete writes a deleting HEAD from nothing and completes (probe DeleteVolume)", "core/frontend/chunkstore/volume_delete.go markHeadDeleting -> ReadHead": "zero HEAD: creates the deleting HEAD (probe DeleteVolume)", @@ -252,6 +255,15 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { t.Fatalf("AbortFork over an absent HEAD: %t %v; today it creates an aborted HEAD", claimed, err) } }) + t.Run("LayoutTransition", func(t *testing.T) { + st := &absentLayoutHead{} + if _, err := layout.RunBegin(ctx, st, layout.HolderID{Epoch: 1, Holder: "h"}, "s"); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("layout transition over an absent HEAD: %v; want ErrHeadAbsent", err) + } + if st.updates != 0 { + t.Fatalf("layout transition over an absent HEAD wrote %d times", st.updates) + } + }) t.Run("ForkReplay", func(t *testing.T) { f, b := headReaderForkFixture(t) c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) @@ -273,3 +285,15 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { } }) } + +// absentLayoutHead is a layout HEAD store whose HEAD is absent. +type absentLayoutHead struct{ updates int } + +func (a *absentLayoutHead) ReadHead(context.Context) (layout.Head, bool, error) { + return layout.Head{}, false, nil +} + +func (a *absentLayoutHead) UpdateHead(context.Context, uint64, layout.Head) error { + a.updates++ + return nil +}