mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Merge pull request #558 from seaweedfs/feat/oss-snap-begin
layout: HEAD record and the Begin transition
This commit is contained in:
commit
71a58d5f97
5 files changed
+839
-1
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// pkgLevel is the owner of a reference outside any function body: a
|
||||
// package-level var or const initializer.
|
||||
const pkgLevel = "<package>"
|
||||
|
||||
// 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()
|
||||
out := map[string]map[string]bool{}
|
||||
add := func(name, owner string) {
|
||||
if out[name] == nil {
|
||||
out[name] = map[string]bool{}
|
||||
}
|
||||
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 {
|
||||
switch d := d.(type) {
|
||||
case *ast.FuncDecl:
|
||||
if d.Body == nil {
|
||||
continue
|
||||
}
|
||||
owner := d.Name.Name
|
||||
if d.Recv != nil && len(d.Recv.List) == 1 {
|
||||
switch x := d.Recv.List[0].Type.(type) {
|
||||
case *ast.Ident:
|
||||
owner = x.Name + "." + owner
|
||||
case *ast.StarExpr:
|
||||
owner = x.X.(*ast.Ident).Name + "." + owner
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
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: 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<X>_Closure and TestRun<X>_InterruptAtEveryStep.
|
||||
// - Lease, claim half: OldLeaseEnded is used only in RunClaim, and
|
||||
// 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.
|
||||
//
|
||||
// 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, 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")
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
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 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") {
|
||||
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) {
|
||||
src := packageSources(t, false)
|
||||
code := refs(t, src)
|
||||
tests := declared(t, packageSources(t, true))
|
||||
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()
|
||||
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.Fatalf("HeadStore methods %v; want ReadHead and UpdateHead only (no path creates a HEAD)", methods)
|
||||
}
|
||||
}
|
||||
|
||||
// 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))
|
||||
// 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)
|
||||
}`, 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 })
|
||||
}`, 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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// validName refuses a string the JSON encoding would not keep byte for
|
||||
// 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)
|
||||
}
|
||||
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 != "" {
|
||||
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)
|
||||
}
|
||||
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
|
||||
}
|
||||
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) {
|
||||
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
|
||||
}
|
||||
if !found {
|
||||
return Head{}, ErrHeadAbsent
|
||||
}
|
||||
next, changed, err := t(h)
|
||||
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
|
||||
}
|
||||
next.Gen = h.Gen + 1
|
||||
return next, nil
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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"
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
@@ -514,9 +515,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
|
||||
|
||||
327 rows: 256 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 312 new.
|
||||
331 rows: 260 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 316 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.
|
||||
|
||||
@@ -1051,6 +1066,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/<index/10000>/`; 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:
|
||||
|
||||
Reference in new issue
Block a user