From 4c903210885038e456ff75cfaf6dc3ca83145991 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 05:01:06 -0800 Subject: [PATCH 1/8] Reserve bounded producer list cursors in the v1.1 HEAD format --- .../chunkstore/layout/head-write-census.json | 1 + .../core/frontend/chunkstore/layout/head.go | 33 +++- .../layout/head_census_export_test.go | 26 ++- .../chunkstore/layout/head_lists_test.go | 151 ++++++++++++++++++ .../chunkstore/layout/list_chain_test.go | 3 + .../core/frontend/chunkstore/layout/remove.go | 9 ++ .../docs/design/immutable-list-pages.md | 25 ++- seaweed-block/docs/design/invariants.md | 2 + 8 files changed, 240 insertions(+), 10 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/head_lists_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json b/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json index 790905b08f..c54de7b0cc 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json +++ b/seaweed-block/core/frontend/chunkstore/layout/head-write-census.json @@ -7,6 +7,7 @@ }, "semantics": "Allowed field-group changes, not proof that a transition occurred. Compare whole decoded HEAD observations. Every update advances Gen separately. No row permits VolumeID change on an existing HEAD.", "field_groups": { + "lists": "Head.Lists: at most three reserved ProducerSeam cursors; every v1.1 update preserves them; no v1.1 producer or consumer", "volume_id": "Head.VolumeID identity", "epoch": "Head.Epoch", "holder": "Head.Holder", diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index 9345f2121e..7d6a1b324e 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -153,6 +153,9 @@ type Head struct { // List is the single admitted list continuation. A producer must finish // or settle it before publishing another; HEAD stays bounded. List *ListCursor `json:",omitempty"` + // Lists reserves three further ProducerSeam slots. This binary preserves + // them but never publishes or consumes them. Empty is omitted on write. + Lists []ListCursor `json:",omitempty"` Gen uint64 VolumeID VolumeID @@ -207,6 +210,7 @@ type headDoc struct { State string `json:"state,omitempty"` CurrentBytes *uint64 `json:"current_bytes,omitempty"` List *ListCursor `json:"list,omitempty"` + Lists []ListCursor `json:"lists,omitempty"` Ext json.RawMessage `json:"ext,omitempty"` } @@ -279,6 +283,23 @@ func (h Head) carriesManifestSizes() bool { var ErrNoNextPosition = fmt.Errorf("%w: HEAD position leaves no room for a next LSN", ErrMalformed) func (h Head) check() error { + if len(h.Lists) > 3 || len(h.Lists) != 0 && h.Version != HeadVersion1 { + return fmt.Errorf("%w: reserved lists require version 1 and at most three entries", ErrMalformed) + } + refs := make(map[ListRef]bool, len(h.Lists)+1) + if h.List != nil { + refs[h.List.Ref] = true + } + for _, c := range h.Lists { + if err := c.check(); err != nil { + return err + } + if refs[c.Ref] { + return fmt.Errorf("%w: repeated list reference", ErrMalformed) + } + refs[c.Ref] = true + } + if h.List != nil { if h.Version != HeadVersion1 { return fmt.Errorf("%w: legacy HEAD carries a list", ErrMalformed) @@ -393,7 +414,7 @@ func (h Head) Encode() ([]byte, error) { if err := h.check(); err != nil { return nil, err } - d := headDoc{List: h.List, Version: h.Version, VolumeID: h.VolumeID.String(), Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID, Activity: h.Activity, Position: h.Position, State: h.State, CurrentBytes: h.CurrentBytes, Ext: h.Ext} + d := headDoc{Lists: h.Lists, List: h.List, Version: h.Version, VolumeID: h.VolumeID.String(), Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID, Activity: h.Activity, Position: h.Position, State: h.State, CurrentBytes: h.CurrentBytes, Ext: h.Ext} if h.Current != nil { d.Current = h.Current.String() } @@ -452,14 +473,14 @@ func DecodeHead(b []byte, gen uint64, volume VolumeID) (Head, error) { if err := dec.Decode(&d); err != nil { return Head{}, fmt.Errorf("%w: HEAD: %v", ErrMalformed, err) } - if d.Version == 0 && (d.List != nil || d.CurrentBytes != nil || d.Ext != nil || snapshotsSized(d.Snapshots)) { + if d.Version == 0 && (d.Lists != nil || d.List != nil || d.CurrentBytes != nil || d.Ext != nil || snapshotsSized(d.Snapshots)) { return Head{}, fmt.Errorf("%w: HEAD of the v1.0 format carries v1.1 fields", ErrMalformed) } vid, err := ParseVolumeID(d.VolumeID) if err != nil { return Head{}, err } - h := Head{List: d.List, Gen: gen, VolumeID: vid, Epoch: d.Epoch, Holder: d.Holder, ClaimID: d.ClaimID, Activity: d.Activity, Position: d.Position, State: d.State, CurrentBytes: d.CurrentBytes, Version: d.Version, Ext: d.Ext} + h := Head{Lists: d.Lists, List: d.List, Gen: gen, VolumeID: vid, Epoch: d.Epoch, Holder: d.Holder, ClaimID: d.ClaimID, Activity: d.Activity, Position: d.Position, State: d.State, CurrentBytes: d.CurrentBytes, Version: d.Version, Ext: d.Ext} if d.Current != "" { rn, err := ParseRootName(d.Current) if err != nil { @@ -580,6 +601,12 @@ func (h Head) clone() Head { if h.List != nil { c.List = h.List.clone() } + if h.Lists != nil { + c.Lists = make([]ListCursor, len(h.Lists)) + for i, cursor := range h.Lists { + c.Lists[i] = *cursor.clone() + } + } if h.Current != nil { rn := *h.Current c.Current = &rn diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_census_export_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_census_export_test.go index 97a431abc6..2e6fc2e340 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_census_export_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_census_export_test.go @@ -31,13 +31,13 @@ func TestMachineReadableHeadCensusNamesExactlyTheTypedCauses(t *testing.T) { if census.SchemaVersion != 1 { t.Fatalf("schema=%d", census.SchemaVersion) } - observable := map[string]bool{"list": true, "volume_id": true, "epoch": true, "holder": true, "claim_id": true, "activity": true, "current": true, "position": true, "state": true, "snapshots": true, "snapshots[].Dependents": true, "version": true, "current_bytes": true, "ext": true} + observable := map[string]bool{"list": true, "lists": true, "volume_id": true, "epoch": true, "holder": true, "claim_id": true, "activity": true, "current": true, "position": true, "state": true, "snapshots": true, "snapshots[].Dependents": true, "version": true, "current_bytes": true, "ext": true} for field := range census.FieldGroups { if !observable[field] { t.Fatalf("unobservable census field %s", field) } } - headFields := map[string]bool{"List": true, "Gen": true, "VolumeID": true, "Epoch": true, "Holder": true, "ClaimID": true, "Activity": true, "Current": true, "Position": true, "Snapshots": true, "State": true, "Version": true, "CurrentBytes": true, "Ext": true} + headFields := map[string]bool{"List": true, "Lists": true, "Gen": true, "VolumeID": true, "Epoch": true, "Holder": true, "ClaimID": true, "Activity": true, "Current": true, "Position": true, "Snapshots": true, "State": true, "Version": true, "CurrentBytes": true, "Ext": true} typ := reflect.TypeOf(Head{}) for n := 0; n < typ.NumField(); n++ { if !headFields[typ.Field(n).Name] { @@ -83,8 +83,8 @@ func TestMachineReadableHeadCensusNamesExactlyTheTypedCauses(t *testing.T) { func changedCensusGroups(before, after Head) []string { var out []string a, b := reflect.ValueOf(before), reflect.ValueOf(after) - jsonKeys := map[string]string{"List": "list", "VolumeID": "volume_id", "Epoch": "epoch", "Holder": "holder", "ClaimID": "claim_id", "Activity": "activity", "Current": "current", "Position": "position", "State": "state", "Version": "version", "CurrentBytes": "current_bytes", "Ext": "ext"} - for _, name := range []string{"List", "VolumeID", "Epoch", "Holder", "ClaimID", "Activity", "Current", "Position", "State", "Version", "CurrentBytes", "Ext"} { + jsonKeys := map[string]string{"List": "list", "Lists": "lists", "VolumeID": "volume_id", "Epoch": "epoch", "Holder": "holder", "ClaimID": "claim_id", "Activity": "activity", "Current": "current", "Position": "position", "State": "state", "Version": "version", "CurrentBytes": "current_bytes", "Ext": "ext"} + for _, name := range []string{"List", "Lists", "VolumeID", "Epoch", "Holder", "ClaimID", "Activity", "Current", "Position", "State", "Version", "CurrentBytes", "Ext"} { if !reflect.DeepEqual(a.FieldByName(name).Interface(), b.FieldByName(name).Interface()) { out = append(out, jsonKeys[name]) } @@ -115,6 +115,11 @@ func changedCensusGroups(before, after Head) []string { return out } func TestMachineReadableHeadCensusCoversRealTransitionFieldSets(t *testing.T) { + t.Run("legacy", func(t *testing.T) { checkRealTransitionFieldSets(t, false) }) + t.Run("reserved", func(t *testing.T) { checkRealTransitionFieldSets(t, true) }) +} + +func checkRealTransitionFieldSets(t *testing.T, reserved bool) { raw, err := os.ReadFile("head-write-census.json") if err != nil { t.Fatal(err) @@ -135,10 +140,19 @@ func TestMachineReadableHeadCensusCoversRealTransitionFieldSets(t *testing.T) { newRoot := RootName{Hash: Sum([]byte("new-image"))} base := func() Head { h := idleHead() + if reserved { + h.Version = HeadVersion1 + h.Lists = reservedListsFixture(t) + } h.State = StateLive h.Current = &root h.Position = 5 h.Snapshots = map[string]Snapshot{"daily": {Root: root, Position: 5}} + if reserved { + sn := h.Snapshots["daily"] + sn.Gen = h.Gen + h.Snapshots["daily"] = sn + } return h } snap := func() Head { h := base(); h.Activity = Activity{Kind: ActSnap, Session: "s"}; return h } @@ -189,6 +203,7 @@ func TestMachineReadableHeadCensusCoversRealTransitionFieldSets(t *testing.T) { t.Fatalf("transition did not write exactly once: writes=%d err=%v", store.updates, err) } after := *store.h + assertReservedLists(t, before, after) if after.Gen != before.Gen+1 { t.Fatalf("generation did not advance: %d -> %d", before.Gen, after.Gen) } @@ -231,6 +246,9 @@ func TestMachineReadableHeadCensusCoversExclusiveCreateWriters(t *testing.T) { } check := func(cause HeadWriteCause, h Head) { t.Helper() + if len(h.Lists) != 0 { + t.Fatal("exclusive create populated reserved lists") + } if h.Gen != 1 { t.Fatalf("create generation=%d", h.Gen) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_lists_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_lists_test.go new file mode 100644 index 0000000000..d80e870964 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/head_lists_test.go @@ -0,0 +1,151 @@ +package layout + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "strings" + "testing" +) + +// These bytes are independent of headDoc: changing the codec cannot silently +// change the reserved ProducerSeam representation. +const reservedHeadPrefix = `{"version":1,"volume_id":"00112233445566778899aabbccddeeff","epoch":1,"holder":"a","claim_id":"k","activity":{"kind":"idle"},"position":0` + +func reservedListsGolden() string { + return reservedHeadPrefix + `,"lists":[{"ref":{"hash":"` + strings.Repeat("1", 64) + `","pages":1},"kind":"upload-intent","producer":"upload","generation":1},{"ref":{"hash":"` + strings.Repeat("2", 64) + `","pages":2},"kind":"drop","producer":"cut","generation":2},{"ref":{"hash":"` + strings.Repeat("3", 64) + `","pages":1},"kind":"snapshot-delete-intent","producer":"delete","generation":3,"target":{"name":"daily","gen":1}}]}` +} + +func TestReservedListsDoNotBecomeCompatibilitySweepCandidates(t *testing.T) { + ctx := context.Background() + s, c, p := chainFixture(t) + if _, err := StageListPage(ctx, s, me, "s1", p); err != nil { + t.Fatal(err) + } + if _, err := RunAbort(ctx, s, me, "s1", CauseSessionRollback); err != nil { + t.Fatal(err) + } + if _, err := RunBeginClean(ctx, s, me, "clean"); err != nil { + t.Fatal(err) + } + // Deliberately no active List: this binary must not infer that the page + // is abandoned, nor read/consume the future producer's reserved chains. + s.h.Lists = []ListCursor{c} + before := s.h.clone() + out, err := NewCleaner(s, nil, s, me, "clean").Page(ctx, ListDir, 0, []string{c.Ref.Hash}) + path, _ := c.Ref.Path() + if err != nil || len(out.Names) != 0 || out.After != path { + t.Fatalf("reserved retirement: %+v %v", out, err) + } + assertReservedLists(t, before, *s.h) + if meta, found, err := s.Stat(ctx, path); err != nil || !found || meta.Mark != "" { + t.Fatalf("reserved page changed: %+v %v %v", meta, found, err) + } +} + +func reservedListsFixture(t *testing.T) []ListCursor { + t.Helper() + id, _ := ParseVolumeID("00112233445566778899aabbccddeeff") + h, err := DecodeHead([]byte(reservedListsGolden()), 9, id) + if err != nil { + t.Fatal(err) + } + return h.Lists +} + +func assertReservedLists(t *testing.T, before, after Head) { + t.Helper() + a, _ := json.Marshal(before.Lists) + b, _ := json.Marshal(after.Lists) + if !bytes.Equal(a, b) { + t.Fatalf("reserved lists changed: %s -> %s", a, b) + } +} + +func TestReservedListsValidationAndClone(t *testing.T) { + h := idleHead() + h.Version = HeadVersion1 + h.Lists = reservedListsFixture(t) + // A cursor pins its chain's first generation, not the latest HEAD write. + h.Gen = 99 + h.List = (&ListCursor{Ref: ListRef{Hash: strings.Repeat("4", 64), Pages: 1}, Kind: ListDrop, Producer: "primary", Generation: 1}).clone() + raw, err := h.Encode() + if err != nil { + t.Fatal(err) + } + if _, err := DecodeHead(raw, h.Gen, h.VolumeID); err != nil { + t.Fatal(err) + } + tests := map[string]func(*Head){ + "four additional": func(h *Head) { + extra := *h.List.clone() + extra.Ref.Hash = strings.Repeat("5", 64) + h.Lists = append(h.Lists, extra) + }, + "repeated additional ref": func(h *Head) { h.Lists[1].Ref = h.Lists[0].Ref }, + "repeated primary ref": func(h *Head) { h.Lists[1].Ref = h.List.Ref }, + "legacy": func(h *Head) { h.Version = 0; h.List = nil }, + "hash": func(h *Head) { h.Lists[0].Ref.Hash = "bad" }, + "pages": func(h *Head) { h.Lists[0].Ref.Pages = 0 }, + "kind": func(h *Head) { h.Lists[0].Kind = "unknown" }, + "producer": func(h *Head) { h.Lists[0].Producer = "" }, + "generation": func(h *Head) { h.Lists[0].Generation = 0 }, + "target": func(h *Head) { h.Lists[2].Target.Gen = 0 }, + } + for name, mutate := range tests { + t.Run(name, func(t *testing.T) { + bad := h.clone() + mutate(&bad) + if _, err := bad.Encode(); !errors.Is(err, ErrMalformed) { + t.Fatalf("encode: %v", err) + } + // Marshal headDoc directly to test decoder validation independently of Encode. + d := headDoc{Version: bad.Version, VolumeID: bad.VolumeID.String(), Epoch: bad.Epoch, Holder: bad.Holder, ClaimID: bad.ClaimID, Activity: bad.Activity, List: bad.List, Lists: bad.Lists} + b, err := json.Marshal(d) + if err != nil { + t.Fatal(err) + } + if _, err := DecodeHead(b, bad.Gen, bad.VolumeID); !errors.Is(err, ErrMalformed) { + t.Fatalf("decode: %v", err) + } + }) + } + legacyEmpty := strings.Replace(reservedHeadPrefix, `"version":1,`, "", 1) + `,"lists":[]}` + if _, err := DecodeHead([]byte(legacyEmpty), 9, h.VolumeID); !errors.Is(err, ErrMalformed) { + t.Fatalf("legacy empty lists: %v", err) + } +} + +func TestReservedListsCloneDoesNotAlias(t *testing.T) { + h := idleHead() + h.Version, h.Lists = HeadVersion1, reservedListsFixture(t) + raw, err := h.Encode() + if err != nil { + t.Fatal(err) + } + cloned := h.clone() + cloned.Lists[0].Producer = "changed" + cloned.Lists[2].Target.Name = "changed" + after, err := h.Encode() + if err != nil || !bytes.Equal(raw, after) { + t.Fatalf("clone aliases original: %s, %v", after, err) + } +} + +func TestReservedListsGoldenBytes(t *testing.T) { + id, err := ParseVolumeID("00112233445566778899aabbccddeeff") + if err != nil { + t.Fatal(err) + } + for _, raw := range []string{reservedHeadPrefix + `}`, reservedListsGolden()} { + h, err := DecodeHead([]byte(raw), 9, id) + if err != nil { + t.Fatal(err) + } + encoded, err := h.Encode() + if err != nil || !bytes.Equal(encoded, []byte(raw)) { + t.Fatalf("round trip: %s, %v", encoded, err) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go b/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go index 12823bcfa8..2dc29c1f0f 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/list_chain_test.go @@ -430,6 +430,7 @@ func TestListWritesMatchExportedCensus(t *testing.T) { } check := func(cause HeadWriteCause, before, after Head) { t.Helper() + assertReservedLists(t, before, after) if after.Gen != before.Gen+1 { t.Fatal("missing generation step") } @@ -441,6 +442,7 @@ func TestListWritesMatchExportedCensus(t *testing.T) { } ctx := context.Background() s, c, p := chainFixture(t) + s.h.Lists = reservedListsFixture(t) if _, err := StageListPage(ctx, s, me, "s1", p); err != nil { t.Fatal(err) } @@ -463,6 +465,7 @@ func TestListWritesMatchExportedCensus(t *testing.T) { } check(CauseListAdvance, before, after) s, c, p = deleteIntentFixture(t) + s.h.Lists = reservedListsFixture(t) r := deleteIntentReader(t, s) before = s.h.clone() if _, err := StageSnapshotDeletePage(ctx, s, before.Gen, p); err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go index 6814dfeb6d..ddc0224081 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -161,6 +161,15 @@ func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string, } live := map[string]bool{} if kind == ListDir { + // Reserved producer chains are opaque to this binary. Do not retire + // list metadata while any are present: absence from List is not proof + // of abandonment. Serving and the existing List consumer continue. + if len(h.Lists) != 0 { + if len(rels) != 0 { + out.After = rels[len(rels)-1] + } + return out, nil + } r, ok := c.os.(ListPageReader) if !ok { return out, errors.New("layout: list removal needs a bounded page reader") diff --git a/seaweed-block/docs/design/immutable-list-pages.md b/seaweed-block/docs/design/immutable-list-pages.md index 8c261af777..bc0f19ee91 100644 --- a/seaweed-block/docs/design/immutable-list-pages.md +++ b/seaweed-block/docs/design/immutable-list-pages.md @@ -5,6 +5,25 @@ HEAD CAS and cleaning exclusion. It is dormant: no cut/restore/delete driver calls the producer or consumer yet, and no automatic cleaner policy changes. This is not the final format declaration or the complete V8 producer wiring. +The ProducerSeam r1 encoding reserves four pending-chain slots in HEAD: +existing `list` plus `lists`, an optional array of at most three `ListCursor` +values. New v1.1 volumes leave `lists` empty (canonical JSON omits it). +Every additional cursor passes the existing context/reference checks; no Ref +may repeat within the array or across `list` and `lists`. Version 0 refuses +this field. Every existing HEAD transition preserves the array byte-for-byte, +including the target identities, without consuming it or refusing serving. +When reserved chains are present, the compatibility cleaner retains all list +pages rather than interpreting their future ownership. Ordinary `list` +continuation still works. No producer append, upload or handoff is enabled. + +The page format needs no additional field: a later chain extension prepends +one page with Next naming the old head, the same kind/producer/generation and +Pages increased by one. A cursor retains its first publishing generation, +which may be below the enclosing HEAD generation. The kept commit slot is +derived from the future producer protocol, not another durable field. +Fixed-byte empty/three-cursor vectors, invalid-slot/reference controls, deep +clone isolation and every existing HEAD-update cause pin this representation. + Version 1 is compact canonical JSON with keys in this order: `version, volume_id, kind, producer, generation, pages, next?, target?, entries`. Each reference is `{hash, pages}`. A snapshot target is `{name, gen}`. @@ -61,12 +80,12 @@ sequenceDiagram Consumer->>Store: tags -> current HEAD reachability -> conditional mark/delete ``` -HEAD has one optional `list` field, containing `ref`, `kind`, `producer`, +HEAD has an active optional `list` field, containing `ref`, `kind`, `producer`, `generation`, and optional captured `target`. It is a serialized admission slot: a second outstanding chain is refused, never overwrites unfinished work. The slot is bounded and admitted only in version 1; a legacy encoding -cannot carry it. This slot is for reviewing the chain integration, not an -approval of final multi-producer queue capacity. The version remains 1; +cannot carry it. The three reserved `lists` slots are not populated or consumed +by this binary; their presence does not change the active slot admission. The version remains 1; all v1.1 fields belong to the final schema, never to `ext`. Pages are staged by the already-open snap session. The original base diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9f01d4b4e6..4207e56f96 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -580,6 +580,7 @@ stateDiagram-v2 |---|---|---|---|---| | no lifecycle record | named volume with immutable layout id | master lifecycle create mints the id once; a lost directory-sync reply settles the same record on retry. Lookup resolves the durable name/id without creating one; workload launch carries both and selects a local directory keyed by id | `core/lifecycle/store.go` `CreateVolume`; master `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient` `ResolveVolume`; launcher `blockVolumeArgs`; blockvolume `parseFlags` | `INV-SNAPK-VOLUME-DIR-001` | | pending ordinary create with a proved id8 collision | pending create with a fresh durable layout id | rejected exclusive VOLUME create, valid foreign full identity belongs to the selected name/id8 directory; not ready, not attached, not a restore; persist replacement before retry, settle unknown rename on replay; never modify the colliding volume | `LayoutStore.CreateVolumeRecord`; `FileStore.RedrawPendingLayoutID`; master `createLifecycleVolume` | `INV-CREATE-DIR-COLLISION-001` | +| any version-1 HEAD with reserved lists | same reserved lists after any existing HEAD transition | at most three additional checked cursors, no repeated Ref across list/lists; deep clone and exact preservation; never consumed or a reason to refuse serving | `head.go` `check`, `clone`, `runTransition`; `remove.go` `Cleaner.Page` retains list metadata | `INV-LIST-RESERVED-001` | | snap(s), list slot empty | snap(s), list cursor published | same full holder, open session and original base generation; every referenced page durable and authenticated; unknown reply retains session and pages | `list_chain.go` `StageListPage`, `RunPublishList` | `INV-LIST-PUBLISH-001` | | clean(c), current list page | clean(c), next continuation or none | exact observed cursor CAS only after authenticated page effects succeed; failed reads and failed effects leave cursor unchanged | `list_chain.go` `RunAdvanceList` | `INV-LIST-CURSOR-001` | | clean(c), stored list page | clean(c), unreached page removed | tags before HEAD; current clean session; spare all current-chain pages; conditional mark then delete | `remove.go` `Cleaner.Page` | `INV-LIST-RETIRE-001` | @@ -1301,6 +1302,7 @@ Notes: | ID | Statement | Transition | Enforced in | Guard | Model | Status | |---|---|---|---|---|---|---| +| `INV-LIST-RESERVED-001` | Version-1 HEAD preserves at most three additional checked list cursors without consuming them or refusing serving; list-page retirement remains conservative while they are present. | M9 all existing HEAD updates | `core/frontend/chunkstore/layout/head.go` `check`, `clone`; `core/frontend/chunkstore/layout/remove.go` `Cleaner.Page` | `TestReservedListsGoldenBytes`, `TestReservedListsValidationAndClone`, `TestReservedListsCloneDoesNotAlias`, `TestReservedListsDoNotBecomeCompatibilitySweepCandidates`, `TestMachineReadableHeadCensusCoversRealTransitionFieldSets`, `TestListWritesMatchExportedCensus` | ProducerSeam r1 E1-E3: Bounded, NoLeak, NoDangling (encoding only; producer deferred) | DORMANT | | `INV-LIST-PUBLISH-001` | A list publication names only durable authenticated pages of its open session; an unknown reply never abandons their protection. | M9 snap -> snap | `list_chain.go` `StageListPage`, `RunPublishList` | `TestPublishList_Closure`, `TestRunPublishList_InterruptAtEveryStep`, `TestListSessionEndedDuringPageWriteCannotPublish` | PageChain 246-250; NoDangling | DORMANT | | `INV-LIST-CURSOR-001` | The persisted list cursor advances only after its authenticated page's idempotent effects finish; a missing page never completes work. | M9 clean -> clean | `list_chain.go` `RunAdvanceList` | `TestAdvanceList_Closure`, `TestRunAdvanceList_InterruptAtEveryStep`, `TestListMissingConsumerPageNeverCompletes` | PageChain 246,251-253; NoLostWork | DORMANT | | `INV-LIST-RETIRE-001` | List-page removal requires a clean session and the existing conditional mark/delete order; every page reached by HEAD is spared, including shared tails. | M9 clean removal | `remove.go` `Cleaner.removePlanned` | `TestListSweepSpareSessionAndReachableTail`, `TestListSharedTailSurvivesAbandonedChainAndResumes`, `TestLayoutStoreListPublishConsumeAndRetire` | PageChain 246,248-251; NoDangling | DORMANT | From 9a4fc847a6607d7c7d189fa3a14935c3dccbd77c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 05:20:35 -0800 Subject: [PATCH 2/8] Report newer pending work when list retirement is skipped --- .../cmd/blockvolume/chunk_maintenance.go | 2 +- .../blockvolume/maintenance_status_test.go | 25 ++++++++++++++++- .../core/frontend/chunkstore/layout/remove.go | 14 +++++++++- .../frontend/durable/maintenance_status.go | 27 ++++++++++--------- .../docs/design/immutable-list-pages.md | 4 ++- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/status-schema.md | 1 + 7 files changed, 58 insertions(+), 17 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance.go b/seaweed-block/cmd/blockvolume/chunk_maintenance.go index b1a926b80c..a42cdc86fd 100644 --- a/seaweed-block/cmd/blockvolume/chunk_maintenance.go +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance.go @@ -58,7 +58,7 @@ func newChunkMaintenance(cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, cle diagnostic = "HEAD generation not read: HEAD absent" } defer func() { - durable.ReportMaintenance(ctx, durable.MaintenancePassStatus{Planned: int64(res.Planned), Removed: int64(res.Removed), PlannedChunks: int64(res.PlannedChunks), PlannedRoots: int64(res.PlannedRoots), PlannedSegments: int64(res.PlannedSegments), RemovedChunks: int64(res.Removed - res.Roots - res.Segments), RemovedRoots: int64(res.Roots), RemovedSegments: int64(res.Segments), HeadGen: head.Gen, HeadGenError: diagnostic}) + durable.ReportMaintenance(ctx, durable.MaintenancePassStatus{SkipReason: head.ListRetirementSkipReason(), Planned: int64(res.Planned), Removed: int64(res.Removed), PlannedChunks: int64(res.PlannedChunks), PlannedRoots: int64(res.PlannedRoots), PlannedSegments: int64(res.PlannedSegments), RemovedChunks: int64(res.Removed - res.Roots - res.Segments), RemovedRoots: int64(res.Roots), RemovedSegments: int64(res.Segments), HeadGen: head.Gen, HeadGenError: diagnostic}) }() var rerr error res, rerr = cat.RemoveUnreachableAll(ctx, ref, me, s) diff --git a/seaweed-block/cmd/blockvolume/maintenance_status_test.go b/seaweed-block/cmd/blockvolume/maintenance_status_test.go index 7d7860a430..f20edbd6e6 100644 --- a/seaweed-block/cmd/blockvolume/maintenance_status_test.go +++ b/seaweed-block/cmd/blockvolume/maintenance_status_test.go @@ -67,7 +67,7 @@ func maintenanceJSON(t *testing.T, p *durable.DurableProvider) map[string]any { } func TestMaintenanceStatusRealPassAndTimeout(t *testing.T) { - for _, kind := range []string{"completed", "reachable", "metadata-only", "head-unread", "head-absent", "retention-only", "timeout"} { + for _, kind := range []string{"completed", "reachable", "metadata-only", "head-unread", "head-absent", "retention-only", "newer-pending-work", "timeout"} { t.Run(kind, func(t *testing.T) { timeout := kind == "timeout" ctx := context.Background() @@ -175,6 +175,22 @@ func TestMaintenanceStatusRealPassAndTimeout(t *testing.T) { if err != nil { t.Fatal(err) } + if kind == "newer-pending-work" { + // Simulate bytes persisted by a future producer, not a v1.1 producer path. + st, e := fixture.Catalog.Store(fixture.Ref) + if e != nil { + t.Fatal(e) + } + before.Version = layout.HeadVersion1 + before.Lists = []layout.ListCursor{{Ref: layout.ListRef{Hash: layout.Sum([]byte("future pending page")).String(), Pages: 1}, Kind: layout.ListUploadIntent, Producer: "future", Generation: 1}} + if e = st.UpdateHead(ctx, before.Gen, before, layout.CauseCommit); e != nil { + t.Fatal(e) + } + before, _, err = fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil { + t.Fatal(err) + } + } if !p.KickMaintenance("v1") { t.Fatal("kick refused") } @@ -245,6 +261,13 @@ func TestMaintenanceStatusRealPassAndTimeout(t *testing.T) { } return } + if kind == "newer-pending-work" { + if last["skipReason"] != "newer_pending_work" || !reflect.DeepEqual(before.Lists, after.Lists) { + t.Fatalf("reserved work silently skipped or consumed: status=%v lists=%v", last, after.Lists) + } + } else if _, present := last["skipReason"]; present { + t.Fatalf("unexpected skip reason: %v", last) + } expectedGen := before.Gen + 1 if kind == "head-unread" || kind == "head-absent" { expectedGen = 0 diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go index ddc0224081..fe3159d97d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -40,6 +40,18 @@ type RemovalResult struct { After string } +// ListRetirementSkipReason reports opaque work that this binary must preserve. +type ListRetirementSkipReason string + +const SkipNewerPendingWork ListRetirementSkipReason = "newer_pending_work" + +func (h Head) ListRetirementSkipReason() ListRetirementSkipReason { + if len(h.Lists) != 0 { + return SkipNewerPendingWork + } + return "" +} + // Page removes unreferenced metadata (RootDir or SegDir) or chunks (PoolDir, // with shard). Every name is validated before any store effect. Metadata pages // must be visited roots first, then segments, before chunk pages. @@ -164,7 +176,7 @@ func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string, // Reserved producer chains are opaque to this binary. Do not retire // list metadata while any are present: absence from List is not proof // of abandonment. Serving and the existing List consumer continue. - if len(h.Lists) != 0 { + if h.ListRetirementSkipReason() != "" { if len(rels) != 0 { out.After = rels[len(rels)-1] } diff --git a/seaweed-block/core/frontend/durable/maintenance_status.go b/seaweed-block/core/frontend/durable/maintenance_status.go index 8a33cec78b..6d377c6ed4 100644 --- a/seaweed-block/core/frontend/durable/maintenance_status.go +++ b/seaweed-block/core/frontend/durable/maintenance_status.go @@ -5,6 +5,8 @@ import ( "strings" "sync" "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" ) // MaintenanceStatus is process-local observation of the holder's maintenance loop. @@ -17,18 +19,19 @@ type MaintenanceStatus struct { // MaintenancePassStatus describes the last completed or failed pass. type MaintenancePassStatus struct { - AtNs int64 `json:"atNs"` // unix ns when the pass ended - Planned int64 `json:"planned"` // all objects considered for removal - Removed int64 `json:"removed"` // all objects removed - PlannedChunks int64 `json:"plannedChunks"` // chunk objects considered for removal - PlannedRoots int64 `json:"plannedRoots"` // root objects considered for removal - PlannedSegments int64 `json:"plannedSegments"` // segment objects considered for removal - RemovedChunks int64 `json:"removedChunks"` // chunk objects removed - RemovedRoots int64 `json:"removedRoots"` // root objects removed - RemovedSegments int64 `json:"removedSegments"` // segment objects removed - Error string `json:"error"` // one-line callback error; empty when the callback completed - HeadGenError string `json:"headGenError"` // diagnostic HEAD read error; empty when read - HeadGen uint64 `json:"headGen"` // observed cleaning HEAD generation; diagnostic only + SkipReason layout.ListRetirementSkipReason `json:"skipReason,omitempty"` // conservative list-page retirement skip; never changes serving or the pass outcome + AtNs int64 `json:"atNs"` // unix ns when the pass ended + Planned int64 `json:"planned"` // all objects considered for removal + Removed int64 `json:"removed"` // all objects removed + PlannedChunks int64 `json:"plannedChunks"` // chunk objects considered for removal + PlannedRoots int64 `json:"plannedRoots"` // root objects considered for removal + PlannedSegments int64 `json:"plannedSegments"` // segment objects considered for removal + RemovedChunks int64 `json:"removedChunks"` // chunk objects removed + RemovedRoots int64 `json:"removedRoots"` // root objects removed + RemovedSegments int64 `json:"removedSegments"` // segment objects removed + Error string `json:"error"` // one-line callback error; empty when the callback completed + HeadGenError string `json:"headGenError"` // diagnostic HEAD read error; empty when read + HeadGen uint64 `json:"headGen"` // observed cleaning HEAD generation; diagnostic only } type maintenanceSlot struct { diff --git a/seaweed-block/docs/design/immutable-list-pages.md b/seaweed-block/docs/design/immutable-list-pages.md index bc0f19ee91..3339f4a829 100644 --- a/seaweed-block/docs/design/immutable-list-pages.md +++ b/seaweed-block/docs/design/immutable-list-pages.md @@ -13,7 +13,9 @@ may repeat within the array or across `list` and `lists`. Version 0 refuses this field. Every existing HEAD transition preserves the array byte-for-byte, including the target identities, without consuming it or refusing serving. When reserved chains are present, the compatibility cleaner retains all list -pages rather than interpreting their future ownership. Ordinary `list` +pages rather than interpreting their future ownership. Maintenance status +reports typed `lastPass.skipReason = newer_pending_work` for that conservative +skip; the reason is omitted normally and does not change the pass outcome. Ordinary `list` continuation still works. No producer append, upload or handoff is enabled. The page format needs no additional field: a later chain extension prepends diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4207e56f96..33066fa829 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1302,7 +1302,7 @@ Notes: | ID | Statement | Transition | Enforced in | Guard | Model | Status | |---|---|---|---|---|---|---| -| `INV-LIST-RESERVED-001` | Version-1 HEAD preserves at most three additional checked list cursors without consuming them or refusing serving; list-page retirement remains conservative while they are present. | M9 all existing HEAD updates | `core/frontend/chunkstore/layout/head.go` `check`, `clone`; `core/frontend/chunkstore/layout/remove.go` `Cleaner.Page` | `TestReservedListsGoldenBytes`, `TestReservedListsValidationAndClone`, `TestReservedListsCloneDoesNotAlias`, `TestReservedListsDoNotBecomeCompatibilitySweepCandidates`, `TestMachineReadableHeadCensusCoversRealTransitionFieldSets`, `TestListWritesMatchExportedCensus` | ProducerSeam r1 E1-E3: Bounded, NoLeak, NoDangling (encoding only; producer deferred) | DORMANT | +| `INV-LIST-RESERVED-001` | Version-1 HEAD preserves at most three additional checked list cursors without consuming them or refusing serving; list-page retirement remains conservative while they are present and reports newer_pending_work. | M9 all existing HEAD updates | `core/frontend/chunkstore/layout/head.go` `check`, `clone`; `core/frontend/chunkstore/layout/remove.go` `Cleaner.Page` | `TestMaintenanceStatusRealPassAndTimeout/newer-pending-work`, `TestReservedListsGoldenBytes`, `TestReservedListsValidationAndClone`, `TestReservedListsCloneDoesNotAlias`, `TestReservedListsDoNotBecomeCompatibilitySweepCandidates`, `TestMachineReadableHeadCensusCoversRealTransitionFieldSets`, `TestListWritesMatchExportedCensus` | ProducerSeam r1 E1-E3: Bounded, NoLeak, NoDangling (encoding only; producer deferred) | DORMANT | | `INV-LIST-PUBLISH-001` | A list publication names only durable authenticated pages of its open session; an unknown reply never abandons their protection. | M9 snap -> snap | `list_chain.go` `StageListPage`, `RunPublishList` | `TestPublishList_Closure`, `TestRunPublishList_InterruptAtEveryStep`, `TestListSessionEndedDuringPageWriteCannotPublish` | PageChain 246-250; NoDangling | DORMANT | | `INV-LIST-CURSOR-001` | The persisted list cursor advances only after its authenticated page's idempotent effects finish; a missing page never completes work. | M9 clean -> clean | `list_chain.go` `RunAdvanceList` | `TestAdvanceList_Closure`, `TestRunAdvanceList_InterruptAtEveryStep`, `TestListMissingConsumerPageNeverCompletes` | PageChain 246,251-253; NoLostWork | DORMANT | | `INV-LIST-RETIRE-001` | List-page removal requires a clean session and the existing conditional mark/delete order; every page reached by HEAD is spared, including shared tails. | M9 clean removal | `remove.go` `Cleaner.removePlanned` | `TestListSweepSpareSessionAndReachableTail`, `TestListSharedTailSurvivesAbandonedChainAndResumes`, `TestLayoutStoreListPublishConsumeAndRetire` | PageChain 246,248-251; NoDangling | DORMANT | diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 54efd05c1b..a811e5245b 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -240,6 +240,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Maintenance.inProgress` | bool | a maintenance callback is running | | `Volumes[].Chunk.Maintenance.currentStartNs` | int64 | unix ns start of the running pass; zero when idle | | `Volumes[].Chunk.Maintenance.lastPass` | object | absent until a pass ends (omitted when empty) | +| `Volumes[].Chunk.Maintenance.lastPass.skipReason` | string | omitted normally; `newer_pending_work` means list-page retirement is conservatively skipped while reserved `lists` remain; serving and the pass outcome are unchanged | | `Volumes[].Chunk.Maintenance.lastPass.atNs` | int64 | unix ns when the pass ended | | `Volumes[].Chunk.Maintenance.lastPass.planned` | int64 | all objects considered for removal | | `Volumes[].Chunk.Maintenance.lastPass.removed` | int64 | all objects removed | From fbcf09fcb995fc6663048124d5cb6cb04cf197c7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 02:52:44 -0800 Subject: [PATCH 3/8] master: a late grant on an unreported host is a warning naming the volume (r2.877) An idle unreported host stays info. A host holding a placed volume that has waited for its grant past the startup window (the freshness window, from when this master first saw it waiting) is a warning naming each such volume and its wait. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/format_gate.go | 33 +++++++++++++++ .../master/format_level_new_cluster_test.go | 40 +++++++++++++++++++ seaweed-block/core/host/master/host.go | 1 + .../core/host/master/observation_snapshot.go | 21 +++++++--- 4 files changed, 90 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/host/master/format_gate.go b/seaweed-block/core/host/master/format_gate.go index 432a4d2a50..a5cf4df884 100644 --- a/seaweed-block/core/host/master/format_gate.go +++ b/seaweed-block/core/host/master/format_gate.go @@ -10,6 +10,7 @@ import ( "sync/atomic" "time" + "github.com/seaweedfs/seaweed-block/core/lifecycle" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" "google.golang.org/grpc/codes" @@ -170,6 +171,38 @@ func (h *Host) awaitingFirstReport(server string) bool { return !ok } +// grantStartupWindow is how long a placed volume may wait for its grant on a +// host that has not reported before the status calls it late: the master's +// freshness window (a started holder reports within it). +func (h *Host) grantStartupWindow() time.Duration { + return h.cfg.Freshness.EffectiveFreshnessWindow() +} + +// grantsWaitingPastStartup names the volumes placed on server that have no +// authority line yet and have waited past the startup window since this +// master first saw them waiting, each with its wait. A volume that has its +// line, or that no longer names server, leaves the record. +func (h *Host) grantsWaitingPastStartup(server string, placements []lifecycle.PlacementIntent, now time.Time) []string { + window := h.grantStartupWindow() + var late []string + for _, p := range placements { + onServer := false + for _, s := range p.Slots { + onServer = onServer || s.ServerID == server + } + if _, granted := h.Publisher().VolumeAuthorityLine(p.VolumeID); granted || !onServer { + h.grantWait.Delete(p.VolumeID) + continue + } + v, _ := h.grantWait.LoadOrStore(p.VolumeID, now) + if waited := now.Sub(v.(time.Time)); waited > window { + late = append(late, fmt.Sprintf("%s (waiting %s, window %s)", p.VolumeID, waited.Round(time.Second), window)) + } + } + sort.Strings(late) + return late +} + // placementTooOld names why server may not be chosen as a placement target // (create, move, restore target, a failover candidate), or "" when it may: // only a KNOWN-old report refuses (r2.875). An unknown server is placeable, diff --git a/seaweed-block/core/host/master/format_level_new_cluster_test.go b/seaweed-block/core/host/master/format_level_new_cluster_test.go index 3f5497ab1e..b12a9826d6 100644 --- a/seaweed-block/core/host/master/format_level_new_cluster_test.go +++ b/seaweed-block/core/host/master/format_level_new_cluster_test.go @@ -4,11 +4,13 @@ import ( "bytes" "os" "path/filepath" + "strings" "testing" "time" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/ops" control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) @@ -199,3 +201,41 @@ func TestTheGrantReadsTheHoldersOwnReportNotASiblings(t *testing.T) { t.Fatalf("v's grant after v's own report: err %v, published %v; want granted", err, published) } } + +// On a new cluster an idle unreported host is info: the cluster stays ok. A +// host that holds a placed volume waiting for its grant past the startup +// window is a warning: the nodes degrade the cluster and the condition names +// the volume and its wait (r2.877). Before the window it is still info. +func TestAnIdleUnreportedHostLeavesTheClusterOKALateGrantDegradesIt(t *testing.T) { + r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) + if _, err := r.m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}); err != nil { + t.Fatal(err) + } + condition := func(now time.Time) (ops.ObservationCondition, []ops.NodeEvidence, string) { + snap := r.m.ObservationSnapshot(now) + for _, n := range snap.Nodes { + for _, c := range n.Conditions { + if n.NodeName == "node-b" && c.Reason == "awaiting_first_report" { + return c, snap.Nodes, snap.Status + } + } + } + t.Fatal("node-b has no awaiting_first_report condition") + return ops.ObservationCondition{}, nil, "" + } + c, _, status := condition(time.Now()) + if c.Severity != "info" || status != ops.ObservationStatusOK { + t.Fatalf("an idle unreported host: severity %q, cluster %q; want info and ok", c.Severity, status) + } + r.createVolume(t, "waiting") + r.place(t, "waiting", "node-b") + now := time.Now() + c, nodes, _ := condition(now) // first seen waiting now + if c.Severity != "info" || clusterStatus(nil, nodes) != ops.ObservationStatusOK { + t.Fatalf("a placed volume within its startup window: severity %q; want info", c.Severity) + } + c, nodes, _ = condition(now.Add(r.m.grantStartupWindow() + time.Second)) + if c.Severity != "warning" || clusterStatus(nil, nodes) != ops.ObservationStatusDegraded || !strings.Contains(c.Message, "waiting (waiting") { + t.Fatalf("a placed volume past its startup window: severity %q, nodes status %q, message %q; want a warning naming the volume", c.Severity, clusterStatus(nil, nodes), c.Message) + } +} diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 10028bd32a..eb20fe93ee 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -153,6 +153,7 @@ type Host struct { statusHTTP *http.Server journal *journalIsolation reads *readsLevels // each server's reported format read level (format_gate.go) + grantWait sync.Map // volume -> time.Time: first seen placed on an unreported host without its grant (format_gate.go) format formatLevelState // the cluster's format level (format_gate.go) finalizeMu sync.Mutex // serializes the format finalize and host retires (format_gate.go) // testPublicationAdmission, when a test sets it before Start, wraps each diff --git a/seaweed-block/core/host/master/observation_snapshot.go b/seaweed-block/core/host/master/observation_snapshot.go index b282fed674..d21d877748 100644 --- a/seaweed-block/core/host/master/observation_snapshot.go +++ b/seaweed-block/core/host/master/observation_snapshot.go @@ -5,6 +5,7 @@ import ( "fmt" "net" "sort" + "strings" "time" "github.com/seaweedfs/seaweed-block/core/authority" @@ -28,12 +29,22 @@ func (h *Host) ObservationSnapshot(now time.Time) ops.ClusterEvidence { cluster.Nodes = observationNodes(snapshot.Nodes, snapshot.Placements) cluster.Volumes = h.observationVolumes(snapshot) for i := range cluster.Nodes { - if h.awaitingFirstReport(cluster.Nodes[i].NodeName) { - cluster.Nodes[i].Conditions = append(cluster.Nodes[i].Conditions, ops.ObservationCondition{ - Type: "FormatLevel", Status: "AwaitingReport", Reason: "awaiting_first_report", Severity: "info", // the grant gate keeps it from serving: nothing is degraded by a spare host - Message: fmt.Sprintf("awaiting report: no format read level reported since the master started; no new work until its first heartbeat (cluster format level %d)", h.formatLevel()), - }) + node := cluster.Nodes[i].NodeName + if !h.awaitingFirstReport(node) { + continue } + // An idle unreported host is info (the grant gate keeps it from + // serving: nothing is degraded); a host holding a placed volume that + // has waited for its grant past its startup window is a warning, + // naming each such volume and its wait (r2.877). + severity, message := "info", fmt.Sprintf("awaiting report: no format read level reported since the master started; no grant until its first heartbeat (cluster format level %d)", h.formatLevel()) + if late := h.grantsWaitingPastStartup(node, snapshot.Placements, now); len(late) > 0 { + severity = "warning" + message += "; placed volumes waiting for their grant past the startup window: " + strings.Join(late, ", ") + } + cluster.Nodes[i].Conditions = append(cluster.Nodes[i].Conditions, ops.ObservationCondition{ + Type: "FormatLevel", Status: "AwaitingReport", Reason: "awaiting_first_report", Severity: severity, Message: message, + }) } cluster.Events = h.events.list("") cluster.Status = clusterStatus(cluster.Volumes, cluster.Nodes) From 9f5988d03f45897ff801b017e153ba265e7275d7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 03:02:58 -0800 Subject: [PATCH 4/8] master: grant waits as one reconciled set per server and volume Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/format_gate.go | 68 +- .../master/format_level_new_cluster_test.go | 57 + seaweed-block/core/host/master/host.go | 1392 ++++++++--------- .../core/host/master/observation_snapshot.go | 29 +- 4 files changed, 820 insertions(+), 726 deletions(-) diff --git a/seaweed-block/core/host/master/format_gate.go b/seaweed-block/core/host/master/format_gate.go index a5cf4df884..e7c318652c 100644 --- a/seaweed-block/core/host/master/format_gate.go +++ b/seaweed-block/core/host/master/format_gate.go @@ -178,29 +178,55 @@ func (h *Host) grantStartupWindow() time.Duration { return h.cfg.Freshness.EffectiveFreshnessWindow() } -// grantsWaitingPastStartup names the volumes placed on server that have no -// authority line yet and have waited past the startup window since this -// master first saw them waiting, each with its wait. A volume that has its -// line, or that no longer names server, leaves the record. -func (h *Host) grantsWaitingPastStartup(server string, placements []lifecycle.PlacementIntent, now time.Time) []string { - window := h.grantStartupWindow() - var late []string - for _, p := range placements { - onServer := false - for _, s := range p.Slots { - onServer = onServer || s.ServerID == server - } - if _, granted := h.Publisher().VolumeAuthorityLine(p.VolumeID); granted || !onServer { - h.grantWait.Delete(p.VolumeID) - continue - } - v, _ := h.grantWait.LoadOrStore(p.VolumeID, now) - if waited := now.Sub(v.(time.Time)); waited > window { - late = append(late, fmt.Sprintf("%s (waiting %s, window %s)", p.VolumeID, waited.Round(time.Second), window)) +// grantWaitEntry is a placed volume whose holder process on a server has +// not reported (no grant before its report) and that has no line yet. +type grantWaitEntry struct { + volume string + waited time.Duration + late bool // waited past the startup window +} + +// grantWaits computes, once per status snapshot, the complete set of +// (server, volume) grant waits at a level above 0: every placed slot without +// an authority line whose own process on its server has not reported. The +// first-seen times are reconciled against that one set: an entry that left +// it (granted, reported, unplaced, removed) is dropped, a new one starts +// now. The key is server and volume, so waits on different servers never +// reset each other. +func (h *Host) grantWaits(placements []lifecycle.PlacementIntent, now time.Time) map[string][]grantWaitEntry { + out := map[string][]grantWaitEntry{} + live := map[string]bool{} + if h.formatLevel() > 0 { + window := h.grantStartupWindow() + for _, p := range placements { + if _, granted := h.Publisher().VolumeAuthorityLine(p.VolumeID); granted { + continue + } + for _, slot := range p.Slots { + if slot.ServerID == "" { + continue + } + if _, reported := h.reads.entry(slot.ServerID, p.VolumeID, h.servedBy(slot.ServerID)); reported { + continue + } + key := slot.ServerID + "\x00" + p.VolumeID + live[key] = true + v, _ := h.grantWait.LoadOrStore(key, now) + waited := now.Sub(v.(time.Time)) + out[slot.ServerID] = append(out[slot.ServerID], grantWaitEntry{volume: p.VolumeID, waited: waited, late: waited > window}) + } } } - sort.Strings(late) - return late + h.grantWait.Range(func(k, _ any) bool { + if !live[k.(string)] { + h.grantWait.Delete(k) + } + return true + }) + for server := range out { + sort.Slice(out[server], func(i, j int) bool { return out[server][i].volume < out[server][j].volume }) + } + return out } // placementTooOld names why server may not be chosen as a placement target diff --git a/seaweed-block/core/host/master/format_level_new_cluster_test.go b/seaweed-block/core/host/master/format_level_new_cluster_test.go index b12a9826d6..98db73caad 100644 --- a/seaweed-block/core/host/master/format_level_new_cluster_test.go +++ b/seaweed-block/core/host/master/format_level_new_cluster_test.go @@ -239,3 +239,60 @@ func TestAnIdleUnreportedHostLeavesTheClusterOKALateGrantDegradesIt(t *testing.T t.Fatalf("a placed volume past its startup window: severity %q, nodes status %q, message %q; want a warning naming the volume", c.Severity, clusterStatus(nil, nodes), c.Message) } } + +// The grant waits are one reconciled set keyed by server and volume: two +// unreported nodes holding waiting volumes do not reset each other's clocks +// (both turn late together); a node whose process for u reported still shows +// its silent process for v waiting; once v's process reports, v's wait and +// its timer are gone. +func TestGrantWaitsAreReconciledPerServerAndVolume(t *testing.T) { + r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) + for _, n := range []string{"node-b", "node-c"} { + if _, err := r.m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: n, DataAddr: "127.0.0.1:19341", CtrlAddr: "127.0.0.1:19342"}); err != nil { + t.Fatal(err) + } + } + for vol, node := range map[string]string{"vb": "node-b", "vc": "node-c", "u": "node-c"} { + r.createVolume(t, vol) + r.place(t, vol, node) + } + if err := r.fgProcessHeartbeat("node-c", "proc-u", "u", 1); err != nil { + t.Fatal(err) + } + cond := func(now time.Time, node string) (ops.ObservationCondition, bool) { + for _, n := range r.m.ObservationSnapshot(now).Nodes { + for _, c := range n.Conditions { + if n.NodeName == node && c.Reason == "awaiting_first_report" { + return c, true + } + } + } + return ops.ObservationCondition{}, false + } + start := time.Now() + for _, node := range []string{"node-b", "node-c"} { + c, ok := cond(start, node) + if !ok || c.Severity != "info" { + t.Fatalf("%s at first sight: %+v %v; want an info wait", node, c, ok) + } + } + late := start.Add(r.m.grantStartupWindow() + time.Second) + for node, vol := range map[string]string{"node-b": "vb", "node-c": "vc"} { + c, ok := cond(late, node) + if !ok || c.Severity != "warning" || !strings.Contains(c.Message, vol+" (waiting") || strings.Contains(c.Message, "u (waiting") { + t.Fatalf("%s past the window: %+v %v; want a warning naming %s only (u's process reported)", node, c, ok, vol) + } + } + if err := r.fgProcessHeartbeat("node-c", "proc-vc", "vc", 1); err != nil { + t.Fatal(err) + } + if c, ok := cond(late, "node-c"); ok { + t.Fatalf("node-c after vc's process reported: %+v; want no wait", c) + } + if _, kept := r.m.grantWait.Load("node-c\x00vc"); kept { + t.Fatal("vc's wait timer outlived its process's report") + } + if _, kept := r.m.grantWait.Load("node-b\x00vb"); !kept { + t.Fatal("vb's wait timer was dropped by another node's reconcile") + } +} diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index eb20fe93ee..13ee8ed0b2 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -1,696 +1,696 @@ -// Package master implements the block master host: the product-side -// composition of P14 authority components (ObservationHost, -// TopologyController, Publisher, durable authority store) plus -// the gRPC server that exposes ObservationService / AssignmentService -// / EvidenceService to block volume daemons and operator tools. -// -// T0 scope (v3-phase-15-t0-sketch.md §1): this package is the -// master-side hosting layer only. It does NOT implement frontend, -// data path, CSI, security, or operator workflows beyond the -// read-only status surface. -// -// Boundary (sketch §3): gRPC messages carry observation facts -// (volume -> master) and minted assignment facts (master -> -// volume). No RPC endpoint accepts an AssignmentAsk or a -// mutation input. -package master - -import ( - "context" - "errors" - "fmt" - "log" - "net" - "net/http" - "path/filepath" - "sync" - "sync/atomic" - "time" - - "github.com/seaweedfs/seaweed-block/core/auth" - "github.com/seaweedfs/seaweed-block/core/authority" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" - "github.com/seaweedfs/seaweed-block/core/host/bootstrap" - "github.com/seaweedfs/seaweed-block/core/lifecycle" - control "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/rpc/link" - "github.com/seaweedfs/seaweed-block/core/storeident" - "google.golang.org/grpc" -) - -// Config holds the master host construction inputs. Flag parsing -// lives in cmd/blockmaster; this type is the testable seam. -type Config struct { - // Auth authenticates and authorizes every gRPC call (phase 0): nil is - // development mode (plaintext; every call is marked so, and the node - // checks admit it). - Auth *auth.Authenticator - // ServerOptions are added to the gRPC server (transport credentials, - // connection age). - ServerOptions []grpc.ServerOption - - // AuthorityStoreDir is the directory passed to - // authority.AcquireStoreLock + NewFileAuthorityStore. Must be - // non-empty. - AuthorityStoreDir string - - // Listen is the TCP address for the gRPC server, e.g. - // "127.0.0.1:0" or ":9180". - Listen string - - // Topology is the accepted topology the observation host - // uses to decide supportability. - Topology authority.AcceptedTopology - - // Freshness configures observation expiry semantics. - Freshness authority.FreshnessConfig - - // ControllerConfig tunes controller knobs (retry window etc). - ControllerConfig authority.TopologyControllerConfig - - // LifecycleProductLoop reports that the host's lifecycle product loop - // runs (blockmaster --lifecycle-product-loop-interval above 0). A volume - // absent from the static topology requires it at CreateVolume and - // PlaceWorkspace; replicated creates also require it in static topology. - LifecycleProductLoop bool - - // LifecycleStoreDir, when non-empty, opens product lifecycle - // registration stores (desired volumes, node inventory, placement - // intents). This is read-only composition for G9D: these stores do - // NOT drive assignment publication. - LifecycleStoreDir string - - // FailbackRuntimeRPC enables the authority failback RPC surface. It is - // disabled by default; callers must still provide expected-current and - // terminal evidence when enabled. - FailbackRuntimeRPC bool - - // WorkspaceRPC enables the RF1 lease/revoke/move surface. HEAD must be - // obtained from the configured remote source, never from operator flags. - WorkspaceMaxClockSkew time.Duration - WorkspaceRPC bool - WorkspaceHeadReader func(context.Context, string) (authority.WorkspaceHead, error) - // LayoutCreateVolume writes VOLUME then the unclaimed HEAD using the - // immutable identity and geometry in the persisted lifecycle record. - LayoutCreateVolume func(context.Context, lifecycle.VolumeSpec) error - // Restore creation reads the source VOLUME's immutable geometry before - // persisting the target, then replays CreateTarget using that record. - LayoutReadVolume func(context.Context, lifecycle.VolumeSpec) (layout.Volume, error) - LayoutReadHead func(context.Context, lifecycle.VolumeSpec) (layout.Head, error) - LayoutCreateTarget func(context.Context, lifecycle.VolumeSpec, lifecycle.VolumeSpec, string) error - - // FrontendPublicationRuntimeHTTP enables the frontend publication runtime - // HTTP surface. It is disabled by default and only confirms a post-failback - // authority line that has already been minted by the failback owner. - FrontendPublicationRuntimeHTTP bool - FrontendPublicationRuntimeListen string - - // StrictJournalIsolation refuses nodes whose durable root shares the - // authority store's file system (one journal): a co-located node that - // serves no volume yet gets its heartbeats refused, and no new placement - // or move targets a co-located node. A co-located node that already - // serves volumes is only alarmed (refusing it would stop its lease - // renewals). Off: alarm only. - StrictJournalIsolation bool - - // StatusListen, when non-empty, serves the read-only status endpoint - // GET /status/workspace-lease on this loopback address. - StatusListen string - - // Logger is used for structured startup and error logging. If - // nil, the default log package logger is used. - Logger *log.Logger -} - -// LifecycleStores groups the product registration stores hosted by -// blockmaster. The stores are controller input only; assignment -// publication remains owned by authority.Controller/Publisher. -type LifecycleStores struct { - Volumes *lifecycle.FileStore - Nodes *lifecycle.NodeInventoryStore - Placements *lifecycle.PlacementIntentStore - WorkspaceBindings workspaceBindingStore - // Deletions holds the chunk-volume deletion reservations. - Deletions *lifecycle.DeletionReservationStore -} - -// Host is the composed master-side block product daemon. Lifecycle -// is: New -> Start -> (serve requests) -> Close. -type Host struct { - probeHub *probeHub // the promotion probe round (probe_round.go) - probeSlots slotServers // replica -> server, for the round - cfg Config - attest *storeAttestations // primaries' attested write-ACK stores - healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6) - log *log.Logger - boot *bootstrap.DurableAuthorityBootstrap - ctrl *authority.TopologyController - obs *authority.ObservationHost - ln net.Listener - frontendRuntimeLn net.Listener - frontendRuntimeHTTP *http.Server - statusLn net.Listener - statusHTTP *http.Server - journal *journalIsolation - reads *readsLevels // each server's reported format read level (format_gate.go) - grantWait sync.Map // volume -> time.Time: first seen placed on an unreported host without its grant (format_gate.go) - format formatLevelState // the cluster's format level (format_gate.go) - finalizeMu sync.Mutex // serializes the format finalize and host retires (format_gate.go) - // testPublicationAdmission, when a test sets it before Start, wraps each - // publication admission: next runs the admission itself. - testPublicationAdmission func(ask authority.AssignmentAsk, next func() error) error - grpc *grpc.Server - topo authority.AcceptedTopology - lifecycle *LifecycleStores - // RPC registration/place/move/ACK/delete and product ticks serialize here. - // Order: workspaceMu -> publisher or lifecycle store locks (not reversed). - workspaceMu sync.Mutex - // bindingRetry: volumes whose binding reconcile failed, retried with the - // next call's own volume (workspaceMu held). - bindingRetry map[string]bool - events *eventRing - promotionMu sync.RWMutex - promotionProber PromotionEvidenceProvider - // fencePending: volume -> the epoch a fencing round fenced survivors at - // without a line being published there. Until the line reaches it, those - // survivors refuse the primary, so the gate keeps trying to heal it. - fencePending map[string]uint64 - cancel context.CancelFunc - wg sync.WaitGroup - - started atomic.Bool -} - -// publisherHolder resolves the chicken-and-egg between the -// controller (which needs the publisher as its reader) and the -// publisher (which needs the controller as its directive). -// Construction order: create holder, create controller(holder), -// Bootstrap(dir, controller) builds publisher, set holder=publisher. -// The controller sees an empty reader until Bootstrap returns; -// that's fine because no rebuild runs until host.Start(). -type publisherHolder struct { - mu sync.Mutex - p *authority.Publisher -} - -func (h *publisherHolder) set(p *authority.Publisher) { - h.mu.Lock() - h.p = p - h.mu.Unlock() -} - -func (h *publisherHolder) LastAuthorityBasis(vid, rid string) (authority.AuthorityBasis, bool) { - h.mu.Lock() - p := h.p - h.mu.Unlock() - if p == nil { - return authority.AuthorityBasis{}, false - } - return p.LastAuthorityBasis(vid, rid) -} - -func (h *publisherHolder) VolumeAuthorityLine(vid string) (authority.AuthorityBasis, bool) { - h.mu.Lock() - p := h.p - h.mu.Unlock() - if p == nil { - return authority.AuthorityBasis{}, false - } - return p.VolumeAuthorityLine(vid) -} - -// New constructs a master host but does NOT start live loops. The -// caller composes it, then calls Start. -// -// Startup order matches T0 sketch §5 + S7 restart pin: -// 1. acquire durable store lock + open store (via sparrow.Bootstrap) -// 2. NewPublisher(WithStore) — synchronous reload (inside Bootstrap) -// 3. controller sees reloaded publisher (via holder back-fill) -// 4. NewObservationHost with reloaded publisher; controller as sink -// 5. bind gRPC listener, register services -// -// Live loops (publisher.Run, host.Start, grpc.Serve) run in Start. -func New(cfg Config) (*Host, error) { - if cfg.WorkspaceMaxClockSkew < 0 || cfg.WorkspaceMaxClockSkew >= 60*time.Second { - return nil, fmt.Errorf("master.New: workspace max clock skew must be positive and less than 60s (zero selects default)") - } - if cfg.WorkspaceRPC && (cfg.WorkspaceHeadReader == nil || cfg.LifecycleStoreDir == "") { - return nil, fmt.Errorf("master.New: workspace RPC requires HEAD reader and lifecycle store") - } - if cfg.AuthorityStoreDir == "" { - return nil, fmt.Errorf("master.New: AuthorityStoreDir is required") - } - if cfg.Listen == "" { - return nil, fmt.Errorf("master.New: Listen is required") - } - if err := ValidateStatusListen(cfg.StatusListen); err != nil { - return nil, fmt.Errorf("master.New: %w", err) - } - lg := cfg.Logger - if lg == nil { - lg = log.Default() - } - - holder := &publisherHolder{} - ctrlCfg := cfg.ControllerConfig - if w := cfg.Freshness.EffectiveFreshnessWindow(); ctrlCfg.PrimaryBootGrace <= 0 || ctrlCfg.PrimaryBootGrace > w { - // A restarted primary may stay not-ready for at most the - // window in which its observations are trusted (#128): the - // store's effective window, also when the config omits it. A - // larger configured grace is capped, never widened; an unset - // or nonpositive one takes the window. - if ctrlCfg.PrimaryBootGrace > w { - lg.Printf("blockmaster: primary boot grace %s capped at freshness window %s", ctrlCfg.PrimaryBootGrace, w) - } - ctrlCfg.PrimaryBootGrace = w - } - ctrl := authority.NewTopologyController(ctrlCfg, holder) - - h := &Host{ - probeHub: newProbeHub(), - cfg: cfg, - log: lg, - ctrl: ctrl, - topo: cfg.Topology, - events: newEventRing(1024), - journal: newJournalIsolation(storeident.Identity{}), // sampled once the store exists - reads: newReadsLevels(cfg.Freshness.EffectiveFreshnessWindow()), - } - - boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{ - WorkspaceMaxClockSkew: cfg.WorkspaceMaxClockSkew, - PublishObserver: h.recordAuthorityPublishedEvent, - PublicationAdmission: h.admitWorkspacePublication, - }) - if err != nil { - return nil, fmt.Errorf("master.New: Bootstrap: %w", err) - } - holder.set(boot.Publisher) - // Bootstrap creates a fresh store directory: sample its file system only - // now, or a first start would compare against an unknown device forever. - // An unknown identity (stat error, unsupported platform) never matches. - h.journal.setSelf(storeident.Of(cfg.AuthorityStoreDir)) - if h.attest, err = loadStoreAttestations(cfg.AuthorityStoreDir); err != nil { - _ = boot.Close() // release the store lock: this master never serves - return nil, fmt.Errorf("master.New: %w", err) - } - // The lifecycle stores open before the format decision: they are part of - // the master's state it reads. - lifecycleStores, err := openLifecycleStores(cfg.LifecycleStoreDir) - if err != nil { - _ = boot.Close() - return nil, fmt.Errorf("master.New: lifecycle stores: %w", err) - } - // A new cluster starts at the current level (r2.869): with no prior - // state in any master store (no authority record reloaded or skipped, no - // attestation file, no volume, node, placement or deletion in the - // lifecycle stores), the master writes the level-1 envelope durably now, - // before anything is served. A crash before that write leaves the same - // empty state, so the next start makes the same choice. Existing state - // without the envelope stays level 0: only a cluster that holds v1.0 data - // needs the finalize. - if newClusterAtStart(boot.ReloadedRecords, len(boot.ReloadSkips), h.attest.absent(), lifecycleStores.empty()) { - if _, err := h.attest.finalize(); err != nil { - _ = boot.Close() - return nil, fmt.Errorf("master.New: a new cluster's format level: %w", err) - } - lg.Printf("blockmaster: new cluster: format level 1 (no prior authority state; no finalize needed)") - } - // Under the authority store's lock and before anything is served: the - // cluster's format level is the attestation file's form (the envelope - // is level 1, re-fsynced here; v1.0.x's form is level 0, where this - // master keeps v1.0's semantics: store_attestation.go, format_gate.go). - if err := h.attest.ensureEnvelope(); err != nil { - _ = boot.Close() - return nil, fmt.Errorf("master.New: %w", err) - } - level := h.attest.level() - boot.Publisher.SetFormatLevelBeforeServing(level) - h.format.v.Store(level) - - var sink authority.ControllerSink = ctrl - if len(cfg.Topology.Volumes) == 0 { - // Dynamic lifecycle volumes derive their accepted topology from - // placement intents in RunLifecycleProductTick. With no static - // topology configured, the observation host should collect facts - // but must not submit "unknown volume" reports that would clear - // lifecycle-driven desired authority. - sink = nil - } - obs := authority.NewObservationHost(authority.ObservationHostConfig{ - Freshness: cfg.Freshness, - Topology: cfg.Topology, - Sink: sink, - Reader: boot.Publisher, - }) - // A published line changes what the observation build reads, and no - // heartbeat carries it: it wakes the build. - boot.Publisher.SetLineChangeHook(func(string) { obs.Wake() }) - // An ask built outside the controller (a heal, a planned or workspace - // move, an operator's request) is issued for the process its target - // reports now. - boot.Publisher.SetIncarnationSource(func(volumeID, replicaID, dataAddr, ctrlAddr string) string { - if f, ok := obs.Store().SlotFactAt(volumeID, replicaID, dataAddr, ctrlAddr); ok { - return f.Incarnation - } - return "" - }) - - ln, err := net.Listen("tcp", cfg.Listen) - if err != nil { - _ = boot.Close() - return nil, fmt.Errorf("master.New: listen %q: %w", cfg.Listen, err) - } - - h.boot = boot - h.obs = obs - h.ln = ln - h.lifecycle = lifecycleStores - if h.lifecycle != nil { - // Rebuild permanent grant exclusions before any request, publisher - // loop or lifecycle reconciliation can create positive validity. - for _, volume := range h.lifecycle.Deletions.CommittedVolumes() { - if err := h.Publisher().ReserveWorkspaceDeletion(context.Background(), volume, nil); err != nil { - _ = ln.Close() - _ = boot.Close() - return nil, fmt.Errorf("master.New: deletion reservation recovery: %w", err) - } - } - if err := h.reconcileWorkspaceBindings(); err != nil { - _ = ln.Close() - _ = boot.Close() - return nil, fmt.Errorf("master.New: workspace binding recovery: %w", err) - } - } - - if cfg.FrontendPublicationRuntimeHTTP { - addr := cfg.FrontendPublicationRuntimeListen - if addr == "" { - addr = "127.0.0.1:0" - } - frontendLn, err := net.Listen("tcp", addr) - if err != nil { - _ = ln.Close() - _ = boot.Close() - return nil, fmt.Errorf("master.New: frontend publication runtime listen %q: %w", addr, err) - } - h.frontendRuntimeLn = frontendLn - h.frontendRuntimeHTTP = &http.Server{Handler: h.frontendPublicationRuntimeHandler()} - } - - if cfg.StatusListen != "" { - statusLn, err := net.Listen("tcp", cfg.StatusListen) - if err != nil { - if h.frontendRuntimeLn != nil { - _ = h.frontendRuntimeLn.Close() - } - _ = ln.Close() - _ = boot.Close() - return nil, fmt.Errorf("master.New: status listen %q: %w", cfg.StatusListen, err) - } - h.statusLn = statusLn - // Every connection phase is bounded: a client that withholds a - // declared body or never reads the reply is cut off. - h.statusHTTP = &http.Server{Handler: h.statusHandler(), ReadHeaderTimeout: statusReadTimeout, ReadTimeout: statusReadTimeout, - WriteTimeout: statusWriteTimeout, IdleTimeout: statusIdleTimeout} - } - - grpcSrv := link.NewServer(serverAuth(cfg.Auth), cfg.ServerOptions...) - svc := newServices(h) - control.RegisterObservationServiceServer(grpcSrv, svc) - control.RegisterAssignmentServiceServer(grpcSrv, svc) - control.RegisterEvidenceServiceServer(grpcSrv, svc) - control.RegisterClusterEvidenceServiceServer(grpcSrv, svc) - control.RegisterLifecycleServiceServer(grpcSrv, svc) - control.RegisterFailbackServiceServer(grpcSrv, svc) - control.RegisterWorkspaceServiceServer(grpcSrv, svc) - h.grpc = grpcSrv - - lg.Printf("blockmaster: lock acquired, reloaded=%d, listen=%s", - boot.ReloadedRecords, ln.Addr().String()) - if h.frontendRuntimeLn != nil { - lg.Printf("blockmaster: frontend publication runtime listen=%s", h.frontendRuntimeLn.Addr().String()) - } - if h.statusLn != nil { - lg.Printf("blockmaster: status listen=%s", h.statusLn.Addr().String()) - } - if cfg.StrictJournalIsolation { - lg.Printf("blockmaster: strict journal isolation: nodes sharing the authority store's file system are refused new work") - } - for _, e := range boot.ReloadSkips { - lg.Printf("blockmaster: reload skip: %v", e) - } - return h, nil -} - -func openLifecycleStores(dir string) (*LifecycleStores, error) { - if dir == "" { - return nil, nil - } - volumes, err := lifecycle.OpenFileStore(filepath.Join(dir, "volumes")) - if err != nil { - return nil, err - } - nodes, err := lifecycle.OpenNodeInventoryStore(filepath.Join(dir, "nodes")) - if err != nil { - return nil, err - } - placements, err := lifecycle.OpenPlacementIntentStore(filepath.Join(dir, "placements")) - if err != nil { - return nil, err - } - bindings, err := lifecycle.OpenWorkspaceBindingStore(filepath.Join(dir, "workspace-bindings")) - if err != nil { - return nil, err - } - deletions, err := lifecycle.OpenDeletionReservationStore(filepath.Join(dir, "deletion-reservations")) - if err != nil { - return nil, err - } - return &LifecycleStores{ - Volumes: volumes, - Nodes: nodes, - Placements: placements, - WorkspaceBindings: bindings, - Deletions: deletions, - }, nil -} - -// Addr returns the bound listener address. Valid after New. -func (h *Host) Addr() string { return h.ln.Addr().String() } - -// FrontendPublicationRuntimeAddr returns the bound frontend publication -// runtime HTTP address, or empty when the runtime is disabled. -func (h *Host) FrontendPublicationRuntimeAddr() string { - if h.frontendRuntimeLn == nil { - return "" - } - return h.frontendRuntimeLn.Addr().String() -} - -// StatusAddr returns the bound status HTTP address, or empty when the status -// endpoint is disabled. -func (h *Host) StatusAddr() string { - if h.statusLn == nil { - return "" - } - return h.statusLn.Addr().String() -} - -// Publisher exposes the reloaded publisher for tests and for the -// evidence-query path. -func (h *Host) Publisher() *authority.Publisher { - if h == nil || h.boot == nil { - return nil - } - return h.boot.Publisher -} - -// FailbackAuthorityRuntime exposes the authority-owned failback seam backed by -// the live Publisher. Callers still need an explicit policy gate before using -// it; constructing the runtime does not execute failback. -func (h *Host) FailbackAuthorityRuntime() authority.FailbackAuthorityRuntime { - return authority.FailbackAuthorityRuntime{Publisher: h.Publisher(), Gate: h.plannedMoveEvidenceAt, TargetEndpoint: h.replicaEndpoint} -} - -// replicaEndpoint is the master's own record of a replica's addresses: its -// fresh heartbeat slot (what the automatic path publishes), else its -// placement slot when that names both. -func (h *Host) replicaEndpoint(volumeID, replicaID string) (string, string, bool) { - if s, ok := h.freshCurrentSlot(volumeID, replicaID); ok && s.DataAddr != "" && s.CtrlAddr != "" { - return s.DataAddr, s.CtrlAddr, true - } - if h.lifecycle != nil { - if p, ok := h.lifecycle.Placements.GetPlacement(volumeID); ok { - for _, s := range p.Slots { - if s.ReplicaID == replicaID && s.DataAddr != "" && s.CtrlAddr != "" { - return s.DataAddr, s.CtrlAddr, true - } - } - } - } - return "", "", false -} - -// Controller exposes the controller for tests. -func (h *Host) Controller() *authority.TopologyController { return h.ctrl } - -// ObservationHost exposes the observation host for tests. -func (h *Host) ObservationHost() *authority.ObservationHost { return h.obs } - -// Lifecycle returns product registration stores when configured. Nil means -// the daemon is running in static-topology-only mode. Reading these stores -// must not be treated as assignment authority. -func (h *Host) Lifecycle() *LifecycleStores { return h.lifecycle } - -// replicaSlotsFor returns replica IDs for a volume. Static topology -// remains the allow-list. Dynamic lifecycle volumes may not persist -// placement slots in the lifecycle record, so read-only status paths -// merge fresh observed slots from the observation store; assignment -// authority still comes from the publisher/controller, not this helper. -func (h *Host) replicaSlotsFor(volumeID string) []string { - for _, v := range h.topo.Volumes { - if v.VolumeID != volumeID { - continue - } - out := make([]string, 0, len(v.Slots)) - for _, s := range v.Slots { - out = append(out, s.ReplicaID) - } - return out - } - var out []string - if h.lifecycle != nil && h.lifecycle.Placements != nil { - if placement, ok := h.lifecycle.Placements.GetPlacement(volumeID); ok { - for _, slot := range placement.Slots { - if slot.ReplicaID != "" { - out = appendReplicaID(out, slot.ReplicaID) - } - } - } - } - if h.lifecycle != nil && h.obs != nil { - for _, replicaID := range h.obs.Store().ReplicaIDsForVolume(volumeID) { - out = appendReplicaID(out, replicaID) - } - } - if len(out) == 0 { - return nil - } - return out -} - -func appendReplicaID(in []string, replicaID string) []string { - for _, existing := range in { - if existing == replicaID { - return in - } - } - return append(in, replicaID) -} - -// Start runs the publisher, observation rebuild loop, and gRPC -// server. Returns a context that is cancelled on Close so callers -// can wait on it from their own goroutines. Idempotent — second -// Start() returns the prior ctx. -func (h *Host) Start() context.Context { - if !h.started.CompareAndSwap(false, true) { - return nil - } - ctx, cancel := context.WithCancel(context.Background()) - h.cancel = cancel - - h.wg.Add(1) - go func() { - defer h.wg.Done() - _ = h.boot.Publisher.Run(ctx) - }() - - h.obs.Start(ctx) - - h.wg.Add(1) - go func() { - defer h.wg.Done() - if err := h.grpc.Serve(h.ln); err != nil && err != grpc.ErrServerStopped { - h.log.Printf("blockmaster: grpc.Serve: %v", err) - } - }() - - if h.frontendRuntimeHTTP != nil && h.frontendRuntimeLn != nil { - h.wg.Add(1) - go func() { - defer h.wg.Done() - if err := h.frontendRuntimeHTTP.Serve(h.frontendRuntimeLn); err != nil && err != http.ErrServerClosed { - h.log.Printf("blockmaster: frontend publication runtime Serve: %v", err) - } - }() - } - - if h.statusHTTP != nil && h.statusLn != nil { - h.wg.Add(1) - go func() { - defer h.wg.Done() - if err := h.statusHTTP.Serve(h.statusLn); err != nil && err != http.ErrServerClosed { - h.log.Printf("blockmaster: status Serve: %v", err) - } - }() - } - - return ctx -} - -// Close stops the gRPC server, cancels live loops, and releases -// the durable store lock. Idempotent. -func (h *Host) Close(ctx context.Context) error { - if h.cancel != nil { - h.cancel() - } - if h.frontendRuntimeHTTP != nil { - _ = h.frontendRuntimeHTTP.Shutdown(ctx) - } - var statusErr error - if h.statusHTTP != nil { - statusErr = h.closeStatusHTTP(ctx) - } - h.obs.Stop() - - done := make(chan struct{}) - go func() { - h.grpc.GracefulStop() - close(done) - }() - select { - case <-done: - case <-ctx.Done(): - h.grpc.Stop() - } - - h.wg.Wait() - // Level 0's horizon extenders write through the store: join them first. - h.boot.Publisher.CloseWorkspaceExtenders() - return errors.Join(statusErr, h.boot.Close()) -} - -// Status endpoint connection bounds. -const ( - statusReadTimeout = 5 * time.Second - statusWriteTimeout = 5 * time.Second - statusIdleTimeout = 30 * time.Second -) - -// closeStatusHTTP shuts the status endpoint down gracefully until ctx ends, -// then force-closes the connections still open (Shutdown leaves them). It -// returns the force close's error, if any; an expired graceful shutdown that -// the force close completed is only logged. -func (h *Host) closeStatusHTTP(ctx context.Context) error { - defer h.statusLn.Close() // a listener Start never served is not Shutdown's - err := h.statusHTTP.Shutdown(ctx) - if err == nil { - return nil - } - h.log.Printf("blockmaster: status graceful shutdown: %v; closing its open connections", err) - if cerr := h.statusHTTP.Close(); cerr != nil && !errors.Is(cerr, net.ErrClosed) { - return fmt.Errorf("status endpoint close: %w", cerr) - } - return nil -} +// Package master implements the block master host: the product-side +// composition of P14 authority components (ObservationHost, +// TopologyController, Publisher, durable authority store) plus +// the gRPC server that exposes ObservationService / AssignmentService +// / EvidenceService to block volume daemons and operator tools. +// +// T0 scope (v3-phase-15-t0-sketch.md §1): this package is the +// master-side hosting layer only. It does NOT implement frontend, +// data path, CSI, security, or operator workflows beyond the +// read-only status surface. +// +// Boundary (sketch §3): gRPC messages carry observation facts +// (volume -> master) and minted assignment facts (master -> +// volume). No RPC endpoint accepts an AssignmentAsk or a +// mutation input. +package master + +import ( + "context" + "errors" + "fmt" + "log" + "net" + "net/http" + "path/filepath" + "sync" + "sync/atomic" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/bootstrap" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "github.com/seaweedfs/seaweed-block/core/storeident" + "google.golang.org/grpc" +) + +// Config holds the master host construction inputs. Flag parsing +// lives in cmd/blockmaster; this type is the testable seam. +type Config struct { + // Auth authenticates and authorizes every gRPC call (phase 0): nil is + // development mode (plaintext; every call is marked so, and the node + // checks admit it). + Auth *auth.Authenticator + // ServerOptions are added to the gRPC server (transport credentials, + // connection age). + ServerOptions []grpc.ServerOption + + // AuthorityStoreDir is the directory passed to + // authority.AcquireStoreLock + NewFileAuthorityStore. Must be + // non-empty. + AuthorityStoreDir string + + // Listen is the TCP address for the gRPC server, e.g. + // "127.0.0.1:0" or ":9180". + Listen string + + // Topology is the accepted topology the observation host + // uses to decide supportability. + Topology authority.AcceptedTopology + + // Freshness configures observation expiry semantics. + Freshness authority.FreshnessConfig + + // ControllerConfig tunes controller knobs (retry window etc). + ControllerConfig authority.TopologyControllerConfig + + // LifecycleProductLoop reports that the host's lifecycle product loop + // runs (blockmaster --lifecycle-product-loop-interval above 0). A volume + // absent from the static topology requires it at CreateVolume and + // PlaceWorkspace; replicated creates also require it in static topology. + LifecycleProductLoop bool + + // LifecycleStoreDir, when non-empty, opens product lifecycle + // registration stores (desired volumes, node inventory, placement + // intents). This is read-only composition for G9D: these stores do + // NOT drive assignment publication. + LifecycleStoreDir string + + // FailbackRuntimeRPC enables the authority failback RPC surface. It is + // disabled by default; callers must still provide expected-current and + // terminal evidence when enabled. + FailbackRuntimeRPC bool + + // WorkspaceRPC enables the RF1 lease/revoke/move surface. HEAD must be + // obtained from the configured remote source, never from operator flags. + WorkspaceMaxClockSkew time.Duration + WorkspaceRPC bool + WorkspaceHeadReader func(context.Context, string) (authority.WorkspaceHead, error) + // LayoutCreateVolume writes VOLUME then the unclaimed HEAD using the + // immutable identity and geometry in the persisted lifecycle record. + LayoutCreateVolume func(context.Context, lifecycle.VolumeSpec) error + // Restore creation reads the source VOLUME's immutable geometry before + // persisting the target, then replays CreateTarget using that record. + LayoutReadVolume func(context.Context, lifecycle.VolumeSpec) (layout.Volume, error) + LayoutReadHead func(context.Context, lifecycle.VolumeSpec) (layout.Head, error) + LayoutCreateTarget func(context.Context, lifecycle.VolumeSpec, lifecycle.VolumeSpec, string) error + + // FrontendPublicationRuntimeHTTP enables the frontend publication runtime + // HTTP surface. It is disabled by default and only confirms a post-failback + // authority line that has already been minted by the failback owner. + FrontendPublicationRuntimeHTTP bool + FrontendPublicationRuntimeListen string + + // StrictJournalIsolation refuses nodes whose durable root shares the + // authority store's file system (one journal): a co-located node that + // serves no volume yet gets its heartbeats refused, and no new placement + // or move targets a co-located node. A co-located node that already + // serves volumes is only alarmed (refusing it would stop its lease + // renewals). Off: alarm only. + StrictJournalIsolation bool + + // StatusListen, when non-empty, serves the read-only status endpoint + // GET /status/workspace-lease on this loopback address. + StatusListen string + + // Logger is used for structured startup and error logging. If + // nil, the default log package logger is used. + Logger *log.Logger +} + +// LifecycleStores groups the product registration stores hosted by +// blockmaster. The stores are controller input only; assignment +// publication remains owned by authority.Controller/Publisher. +type LifecycleStores struct { + Volumes *lifecycle.FileStore + Nodes *lifecycle.NodeInventoryStore + Placements *lifecycle.PlacementIntentStore + WorkspaceBindings workspaceBindingStore + // Deletions holds the chunk-volume deletion reservations. + Deletions *lifecycle.DeletionReservationStore +} + +// Host is the composed master-side block product daemon. Lifecycle +// is: New -> Start -> (serve requests) -> Close. +type Host struct { + probeHub *probeHub // the promotion probe round (probe_round.go) + probeSlots slotServers // replica -> server, for the round + cfg Config + attest *storeAttestations // primaries' attested write-ACK stores + healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6) + log *log.Logger + boot *bootstrap.DurableAuthorityBootstrap + ctrl *authority.TopologyController + obs *authority.ObservationHost + ln net.Listener + frontendRuntimeLn net.Listener + frontendRuntimeHTTP *http.Server + statusLn net.Listener + statusHTTP *http.Server + journal *journalIsolation + reads *readsLevels // each server's reported format read level (format_gate.go) + grantWait sync.Map // "server\x00volume" -> time.Time: first seen waiting for its grant without its process's report (format_gate.go grantWaits) + format formatLevelState // the cluster's format level (format_gate.go) + finalizeMu sync.Mutex // serializes the format finalize and host retires (format_gate.go) + // testPublicationAdmission, when a test sets it before Start, wraps each + // publication admission: next runs the admission itself. + testPublicationAdmission func(ask authority.AssignmentAsk, next func() error) error + grpc *grpc.Server + topo authority.AcceptedTopology + lifecycle *LifecycleStores + // RPC registration/place/move/ACK/delete and product ticks serialize here. + // Order: workspaceMu -> publisher or lifecycle store locks (not reversed). + workspaceMu sync.Mutex + // bindingRetry: volumes whose binding reconcile failed, retried with the + // next call's own volume (workspaceMu held). + bindingRetry map[string]bool + events *eventRing + promotionMu sync.RWMutex + promotionProber PromotionEvidenceProvider + // fencePending: volume -> the epoch a fencing round fenced survivors at + // without a line being published there. Until the line reaches it, those + // survivors refuse the primary, so the gate keeps trying to heal it. + fencePending map[string]uint64 + cancel context.CancelFunc + wg sync.WaitGroup + + started atomic.Bool +} + +// publisherHolder resolves the chicken-and-egg between the +// controller (which needs the publisher as its reader) and the +// publisher (which needs the controller as its directive). +// Construction order: create holder, create controller(holder), +// Bootstrap(dir, controller) builds publisher, set holder=publisher. +// The controller sees an empty reader until Bootstrap returns; +// that's fine because no rebuild runs until host.Start(). +type publisherHolder struct { + mu sync.Mutex + p *authority.Publisher +} + +func (h *publisherHolder) set(p *authority.Publisher) { + h.mu.Lock() + h.p = p + h.mu.Unlock() +} + +func (h *publisherHolder) LastAuthorityBasis(vid, rid string) (authority.AuthorityBasis, bool) { + h.mu.Lock() + p := h.p + h.mu.Unlock() + if p == nil { + return authority.AuthorityBasis{}, false + } + return p.LastAuthorityBasis(vid, rid) +} + +func (h *publisherHolder) VolumeAuthorityLine(vid string) (authority.AuthorityBasis, bool) { + h.mu.Lock() + p := h.p + h.mu.Unlock() + if p == nil { + return authority.AuthorityBasis{}, false + } + return p.VolumeAuthorityLine(vid) +} + +// New constructs a master host but does NOT start live loops. The +// caller composes it, then calls Start. +// +// Startup order matches T0 sketch §5 + S7 restart pin: +// 1. acquire durable store lock + open store (via sparrow.Bootstrap) +// 2. NewPublisher(WithStore) — synchronous reload (inside Bootstrap) +// 3. controller sees reloaded publisher (via holder back-fill) +// 4. NewObservationHost with reloaded publisher; controller as sink +// 5. bind gRPC listener, register services +// +// Live loops (publisher.Run, host.Start, grpc.Serve) run in Start. +func New(cfg Config) (*Host, error) { + if cfg.WorkspaceMaxClockSkew < 0 || cfg.WorkspaceMaxClockSkew >= 60*time.Second { + return nil, fmt.Errorf("master.New: workspace max clock skew must be positive and less than 60s (zero selects default)") + } + if cfg.WorkspaceRPC && (cfg.WorkspaceHeadReader == nil || cfg.LifecycleStoreDir == "") { + return nil, fmt.Errorf("master.New: workspace RPC requires HEAD reader and lifecycle store") + } + if cfg.AuthorityStoreDir == "" { + return nil, fmt.Errorf("master.New: AuthorityStoreDir is required") + } + if cfg.Listen == "" { + return nil, fmt.Errorf("master.New: Listen is required") + } + if err := ValidateStatusListen(cfg.StatusListen); err != nil { + return nil, fmt.Errorf("master.New: %w", err) + } + lg := cfg.Logger + if lg == nil { + lg = log.Default() + } + + holder := &publisherHolder{} + ctrlCfg := cfg.ControllerConfig + if w := cfg.Freshness.EffectiveFreshnessWindow(); ctrlCfg.PrimaryBootGrace <= 0 || ctrlCfg.PrimaryBootGrace > w { + // A restarted primary may stay not-ready for at most the + // window in which its observations are trusted (#128): the + // store's effective window, also when the config omits it. A + // larger configured grace is capped, never widened; an unset + // or nonpositive one takes the window. + if ctrlCfg.PrimaryBootGrace > w { + lg.Printf("blockmaster: primary boot grace %s capped at freshness window %s", ctrlCfg.PrimaryBootGrace, w) + } + ctrlCfg.PrimaryBootGrace = w + } + ctrl := authority.NewTopologyController(ctrlCfg, holder) + + h := &Host{ + probeHub: newProbeHub(), + cfg: cfg, + log: lg, + ctrl: ctrl, + topo: cfg.Topology, + events: newEventRing(1024), + journal: newJournalIsolation(storeident.Identity{}), // sampled once the store exists + reads: newReadsLevels(cfg.Freshness.EffectiveFreshnessWindow()), + } + + boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{ + WorkspaceMaxClockSkew: cfg.WorkspaceMaxClockSkew, + PublishObserver: h.recordAuthorityPublishedEvent, + PublicationAdmission: h.admitWorkspacePublication, + }) + if err != nil { + return nil, fmt.Errorf("master.New: Bootstrap: %w", err) + } + holder.set(boot.Publisher) + // Bootstrap creates a fresh store directory: sample its file system only + // now, or a first start would compare against an unknown device forever. + // An unknown identity (stat error, unsupported platform) never matches. + h.journal.setSelf(storeident.Of(cfg.AuthorityStoreDir)) + if h.attest, err = loadStoreAttestations(cfg.AuthorityStoreDir); err != nil { + _ = boot.Close() // release the store lock: this master never serves + return nil, fmt.Errorf("master.New: %w", err) + } + // The lifecycle stores open before the format decision: they are part of + // the master's state it reads. + lifecycleStores, err := openLifecycleStores(cfg.LifecycleStoreDir) + if err != nil { + _ = boot.Close() + return nil, fmt.Errorf("master.New: lifecycle stores: %w", err) + } + // A new cluster starts at the current level (r2.869): with no prior + // state in any master store (no authority record reloaded or skipped, no + // attestation file, no volume, node, placement or deletion in the + // lifecycle stores), the master writes the level-1 envelope durably now, + // before anything is served. A crash before that write leaves the same + // empty state, so the next start makes the same choice. Existing state + // without the envelope stays level 0: only a cluster that holds v1.0 data + // needs the finalize. + if newClusterAtStart(boot.ReloadedRecords, len(boot.ReloadSkips), h.attest.absent(), lifecycleStores.empty()) { + if _, err := h.attest.finalize(); err != nil { + _ = boot.Close() + return nil, fmt.Errorf("master.New: a new cluster's format level: %w", err) + } + lg.Printf("blockmaster: new cluster: format level 1 (no prior authority state; no finalize needed)") + } + // Under the authority store's lock and before anything is served: the + // cluster's format level is the attestation file's form (the envelope + // is level 1, re-fsynced here; v1.0.x's form is level 0, where this + // master keeps v1.0's semantics: store_attestation.go, format_gate.go). + if err := h.attest.ensureEnvelope(); err != nil { + _ = boot.Close() + return nil, fmt.Errorf("master.New: %w", err) + } + level := h.attest.level() + boot.Publisher.SetFormatLevelBeforeServing(level) + h.format.v.Store(level) + + var sink authority.ControllerSink = ctrl + if len(cfg.Topology.Volumes) == 0 { + // Dynamic lifecycle volumes derive their accepted topology from + // placement intents in RunLifecycleProductTick. With no static + // topology configured, the observation host should collect facts + // but must not submit "unknown volume" reports that would clear + // lifecycle-driven desired authority. + sink = nil + } + obs := authority.NewObservationHost(authority.ObservationHostConfig{ + Freshness: cfg.Freshness, + Topology: cfg.Topology, + Sink: sink, + Reader: boot.Publisher, + }) + // A published line changes what the observation build reads, and no + // heartbeat carries it: it wakes the build. + boot.Publisher.SetLineChangeHook(func(string) { obs.Wake() }) + // An ask built outside the controller (a heal, a planned or workspace + // move, an operator's request) is issued for the process its target + // reports now. + boot.Publisher.SetIncarnationSource(func(volumeID, replicaID, dataAddr, ctrlAddr string) string { + if f, ok := obs.Store().SlotFactAt(volumeID, replicaID, dataAddr, ctrlAddr); ok { + return f.Incarnation + } + return "" + }) + + ln, err := net.Listen("tcp", cfg.Listen) + if err != nil { + _ = boot.Close() + return nil, fmt.Errorf("master.New: listen %q: %w", cfg.Listen, err) + } + + h.boot = boot + h.obs = obs + h.ln = ln + h.lifecycle = lifecycleStores + if h.lifecycle != nil { + // Rebuild permanent grant exclusions before any request, publisher + // loop or lifecycle reconciliation can create positive validity. + for _, volume := range h.lifecycle.Deletions.CommittedVolumes() { + if err := h.Publisher().ReserveWorkspaceDeletion(context.Background(), volume, nil); err != nil { + _ = ln.Close() + _ = boot.Close() + return nil, fmt.Errorf("master.New: deletion reservation recovery: %w", err) + } + } + if err := h.reconcileWorkspaceBindings(); err != nil { + _ = ln.Close() + _ = boot.Close() + return nil, fmt.Errorf("master.New: workspace binding recovery: %w", err) + } + } + + if cfg.FrontendPublicationRuntimeHTTP { + addr := cfg.FrontendPublicationRuntimeListen + if addr == "" { + addr = "127.0.0.1:0" + } + frontendLn, err := net.Listen("tcp", addr) + if err != nil { + _ = ln.Close() + _ = boot.Close() + return nil, fmt.Errorf("master.New: frontend publication runtime listen %q: %w", addr, err) + } + h.frontendRuntimeLn = frontendLn + h.frontendRuntimeHTTP = &http.Server{Handler: h.frontendPublicationRuntimeHandler()} + } + + if cfg.StatusListen != "" { + statusLn, err := net.Listen("tcp", cfg.StatusListen) + if err != nil { + if h.frontendRuntimeLn != nil { + _ = h.frontendRuntimeLn.Close() + } + _ = ln.Close() + _ = boot.Close() + return nil, fmt.Errorf("master.New: status listen %q: %w", cfg.StatusListen, err) + } + h.statusLn = statusLn + // Every connection phase is bounded: a client that withholds a + // declared body or never reads the reply is cut off. + h.statusHTTP = &http.Server{Handler: h.statusHandler(), ReadHeaderTimeout: statusReadTimeout, ReadTimeout: statusReadTimeout, + WriteTimeout: statusWriteTimeout, IdleTimeout: statusIdleTimeout} + } + + grpcSrv := link.NewServer(serverAuth(cfg.Auth), cfg.ServerOptions...) + svc := newServices(h) + control.RegisterObservationServiceServer(grpcSrv, svc) + control.RegisterAssignmentServiceServer(grpcSrv, svc) + control.RegisterEvidenceServiceServer(grpcSrv, svc) + control.RegisterClusterEvidenceServiceServer(grpcSrv, svc) + control.RegisterLifecycleServiceServer(grpcSrv, svc) + control.RegisterFailbackServiceServer(grpcSrv, svc) + control.RegisterWorkspaceServiceServer(grpcSrv, svc) + h.grpc = grpcSrv + + lg.Printf("blockmaster: lock acquired, reloaded=%d, listen=%s", + boot.ReloadedRecords, ln.Addr().String()) + if h.frontendRuntimeLn != nil { + lg.Printf("blockmaster: frontend publication runtime listen=%s", h.frontendRuntimeLn.Addr().String()) + } + if h.statusLn != nil { + lg.Printf("blockmaster: status listen=%s", h.statusLn.Addr().String()) + } + if cfg.StrictJournalIsolation { + lg.Printf("blockmaster: strict journal isolation: nodes sharing the authority store's file system are refused new work") + } + for _, e := range boot.ReloadSkips { + lg.Printf("blockmaster: reload skip: %v", e) + } + return h, nil +} + +func openLifecycleStores(dir string) (*LifecycleStores, error) { + if dir == "" { + return nil, nil + } + volumes, err := lifecycle.OpenFileStore(filepath.Join(dir, "volumes")) + if err != nil { + return nil, err + } + nodes, err := lifecycle.OpenNodeInventoryStore(filepath.Join(dir, "nodes")) + if err != nil { + return nil, err + } + placements, err := lifecycle.OpenPlacementIntentStore(filepath.Join(dir, "placements")) + if err != nil { + return nil, err + } + bindings, err := lifecycle.OpenWorkspaceBindingStore(filepath.Join(dir, "workspace-bindings")) + if err != nil { + return nil, err + } + deletions, err := lifecycle.OpenDeletionReservationStore(filepath.Join(dir, "deletion-reservations")) + if err != nil { + return nil, err + } + return &LifecycleStores{ + Volumes: volumes, + Nodes: nodes, + Placements: placements, + WorkspaceBindings: bindings, + Deletions: deletions, + }, nil +} + +// Addr returns the bound listener address. Valid after New. +func (h *Host) Addr() string { return h.ln.Addr().String() } + +// FrontendPublicationRuntimeAddr returns the bound frontend publication +// runtime HTTP address, or empty when the runtime is disabled. +func (h *Host) FrontendPublicationRuntimeAddr() string { + if h.frontendRuntimeLn == nil { + return "" + } + return h.frontendRuntimeLn.Addr().String() +} + +// StatusAddr returns the bound status HTTP address, or empty when the status +// endpoint is disabled. +func (h *Host) StatusAddr() string { + if h.statusLn == nil { + return "" + } + return h.statusLn.Addr().String() +} + +// Publisher exposes the reloaded publisher for tests and for the +// evidence-query path. +func (h *Host) Publisher() *authority.Publisher { + if h == nil || h.boot == nil { + return nil + } + return h.boot.Publisher +} + +// FailbackAuthorityRuntime exposes the authority-owned failback seam backed by +// the live Publisher. Callers still need an explicit policy gate before using +// it; constructing the runtime does not execute failback. +func (h *Host) FailbackAuthorityRuntime() authority.FailbackAuthorityRuntime { + return authority.FailbackAuthorityRuntime{Publisher: h.Publisher(), Gate: h.plannedMoveEvidenceAt, TargetEndpoint: h.replicaEndpoint} +} + +// replicaEndpoint is the master's own record of a replica's addresses: its +// fresh heartbeat slot (what the automatic path publishes), else its +// placement slot when that names both. +func (h *Host) replicaEndpoint(volumeID, replicaID string) (string, string, bool) { + if s, ok := h.freshCurrentSlot(volumeID, replicaID); ok && s.DataAddr != "" && s.CtrlAddr != "" { + return s.DataAddr, s.CtrlAddr, true + } + if h.lifecycle != nil { + if p, ok := h.lifecycle.Placements.GetPlacement(volumeID); ok { + for _, s := range p.Slots { + if s.ReplicaID == replicaID && s.DataAddr != "" && s.CtrlAddr != "" { + return s.DataAddr, s.CtrlAddr, true + } + } + } + } + return "", "", false +} + +// Controller exposes the controller for tests. +func (h *Host) Controller() *authority.TopologyController { return h.ctrl } + +// ObservationHost exposes the observation host for tests. +func (h *Host) ObservationHost() *authority.ObservationHost { return h.obs } + +// Lifecycle returns product registration stores when configured. Nil means +// the daemon is running in static-topology-only mode. Reading these stores +// must not be treated as assignment authority. +func (h *Host) Lifecycle() *LifecycleStores { return h.lifecycle } + +// replicaSlotsFor returns replica IDs for a volume. Static topology +// remains the allow-list. Dynamic lifecycle volumes may not persist +// placement slots in the lifecycle record, so read-only status paths +// merge fresh observed slots from the observation store; assignment +// authority still comes from the publisher/controller, not this helper. +func (h *Host) replicaSlotsFor(volumeID string) []string { + for _, v := range h.topo.Volumes { + if v.VolumeID != volumeID { + continue + } + out := make([]string, 0, len(v.Slots)) + for _, s := range v.Slots { + out = append(out, s.ReplicaID) + } + return out + } + var out []string + if h.lifecycle != nil && h.lifecycle.Placements != nil { + if placement, ok := h.lifecycle.Placements.GetPlacement(volumeID); ok { + for _, slot := range placement.Slots { + if slot.ReplicaID != "" { + out = appendReplicaID(out, slot.ReplicaID) + } + } + } + } + if h.lifecycle != nil && h.obs != nil { + for _, replicaID := range h.obs.Store().ReplicaIDsForVolume(volumeID) { + out = appendReplicaID(out, replicaID) + } + } + if len(out) == 0 { + return nil + } + return out +} + +func appendReplicaID(in []string, replicaID string) []string { + for _, existing := range in { + if existing == replicaID { + return in + } + } + return append(in, replicaID) +} + +// Start runs the publisher, observation rebuild loop, and gRPC +// server. Returns a context that is cancelled on Close so callers +// can wait on it from their own goroutines. Idempotent — second +// Start() returns the prior ctx. +func (h *Host) Start() context.Context { + if !h.started.CompareAndSwap(false, true) { + return nil + } + ctx, cancel := context.WithCancel(context.Background()) + h.cancel = cancel + + h.wg.Add(1) + go func() { + defer h.wg.Done() + _ = h.boot.Publisher.Run(ctx) + }() + + h.obs.Start(ctx) + + h.wg.Add(1) + go func() { + defer h.wg.Done() + if err := h.grpc.Serve(h.ln); err != nil && err != grpc.ErrServerStopped { + h.log.Printf("blockmaster: grpc.Serve: %v", err) + } + }() + + if h.frontendRuntimeHTTP != nil && h.frontendRuntimeLn != nil { + h.wg.Add(1) + go func() { + defer h.wg.Done() + if err := h.frontendRuntimeHTTP.Serve(h.frontendRuntimeLn); err != nil && err != http.ErrServerClosed { + h.log.Printf("blockmaster: frontend publication runtime Serve: %v", err) + } + }() + } + + if h.statusHTTP != nil && h.statusLn != nil { + h.wg.Add(1) + go func() { + defer h.wg.Done() + if err := h.statusHTTP.Serve(h.statusLn); err != nil && err != http.ErrServerClosed { + h.log.Printf("blockmaster: status Serve: %v", err) + } + }() + } + + return ctx +} + +// Close stops the gRPC server, cancels live loops, and releases +// the durable store lock. Idempotent. +func (h *Host) Close(ctx context.Context) error { + if h.cancel != nil { + h.cancel() + } + if h.frontendRuntimeHTTP != nil { + _ = h.frontendRuntimeHTTP.Shutdown(ctx) + } + var statusErr error + if h.statusHTTP != nil { + statusErr = h.closeStatusHTTP(ctx) + } + h.obs.Stop() + + done := make(chan struct{}) + go func() { + h.grpc.GracefulStop() + close(done) + }() + select { + case <-done: + case <-ctx.Done(): + h.grpc.Stop() + } + + h.wg.Wait() + // Level 0's horizon extenders write through the store: join them first. + h.boot.Publisher.CloseWorkspaceExtenders() + return errors.Join(statusErr, h.boot.Close()) +} + +// Status endpoint connection bounds. +const ( + statusReadTimeout = 5 * time.Second + statusWriteTimeout = 5 * time.Second + statusIdleTimeout = 30 * time.Second +) + +// closeStatusHTTP shuts the status endpoint down gracefully until ctx ends, +// then force-closes the connections still open (Shutdown leaves them). It +// returns the force close's error, if any; an expired graceful shutdown that +// the force close completed is only logged. +func (h *Host) closeStatusHTTP(ctx context.Context) error { + defer h.statusLn.Close() // a listener Start never served is not Shutdown's + err := h.statusHTTP.Shutdown(ctx) + if err == nil { + return nil + } + h.log.Printf("blockmaster: status graceful shutdown: %v; closing its open connections", err) + if cerr := h.statusHTTP.Close(); cerr != nil && !errors.Is(cerr, net.ErrClosed) { + return fmt.Errorf("status endpoint close: %w", cerr) + } + return nil +} diff --git a/seaweed-block/core/host/master/observation_snapshot.go b/seaweed-block/core/host/master/observation_snapshot.go index d21d877748..ee16b9ca8b 100644 --- a/seaweed-block/core/host/master/observation_snapshot.go +++ b/seaweed-block/core/host/master/observation_snapshot.go @@ -28,19 +28,30 @@ func (h *Host) ObservationSnapshot(now time.Time) ops.ClusterEvidence { cluster.Nodes = observationNodes(snapshot.Nodes, snapshot.Placements) cluster.Volumes = h.observationVolumes(snapshot) + waits := h.grantWaits(snapshot.Placements, now) for i := range cluster.Nodes { node := cluster.Nodes[i].NodeName - if !h.awaitingFirstReport(node) { + nodeWaits := waits[node] + if !h.awaitingFirstReport(node) && len(nodeWaits) == 0 { continue } - // An idle unreported host is info (the grant gate keeps it from - // serving: nothing is degraded); a host holding a placed volume that - // has waited for its grant past its startup window is a warning, - // naming each such volume and its wait (r2.877). - severity, message := "info", fmt.Sprintf("awaiting report: no format read level reported since the master started; no grant until its first heartbeat (cluster format level %d)", h.formatLevel()) - if late := h.grantsWaitingPastStartup(node, snapshot.Placements, now); len(late) > 0 { - severity = "warning" - message += "; placed volumes waiting for their grant past the startup window: " + strings.Join(late, ", ") + // Info while the node is idle or its placed volumes wait within their + // startup window; a warning (the cluster degraded) once one has waited + // for its grant past the window (r2.877). Each wait is shown, before + // it is late too. + severity := "info" + message := fmt.Sprintf("awaiting report: no grant to a process of this node before its own report (cluster format level %d)", h.formatLevel()) + if len(nodeWaits) > 0 { + window := h.grantStartupWindow() + parts := make([]string, 0, len(nodeWaits)) + for _, w := range nodeWaits { + state := "within" + if w.late { + state, severity = "past", "warning" + } + parts = append(parts, fmt.Sprintf("%s (waiting %s, %s the %s startup window)", w.volume, w.waited.Round(time.Second), state, window)) + } + message += "; placed volumes waiting for their grant: " + strings.Join(parts, ", ") } cluster.Nodes[i].Conditions = append(cluster.Nodes[i].Conditions, ops.ObservationCondition{ Type: "FormatLevel", Status: "AwaitingReport", Reason: "awaiting_first_report", Severity: severity, Message: message, From d16bd533d56eff8000dba7197925aedf1b2045ca Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 05:28:21 -0800 Subject: [PATCH 5/8] master: one status snapshot reconciles the grant waits at a time The waiting set and its first-seen times are computed and reconciled under one lock, so a concurrent snapshot never drops an entry another just started (its wait would restart). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/format_gate.go | 24 +++++++++++++------ .../master/format_level_new_cluster_test.go | 12 ++++++++-- seaweed-block/core/host/master/host.go | 9 +++---- 3 files changed, 32 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/host/master/format_gate.go b/seaweed-block/core/host/master/format_gate.go index e7c318652c..2b9ab0ac0b 100644 --- a/seaweed-block/core/host/master/format_gate.go +++ b/seaweed-block/core/host/master/format_gate.go @@ -196,6 +196,13 @@ type grantWaitEntry struct { func (h *Host) grantWaits(placements []lifecycle.PlacementIntent, now time.Time) map[string][]grantWaitEntry { out := map[string][]grantWaitEntry{} live := map[string]bool{} + // One snapshot at a time computes the set and reconciles against it, so + // a concurrent snapshot never drops an entry this one just started. + h.grantWaitMu.Lock() + defer h.grantWaitMu.Unlock() + if h.grantWait == nil { + h.grantWait = map[string]time.Time{} + } if h.formatLevel() > 0 { window := h.grantStartupWindow() for _, p := range placements { @@ -211,18 +218,21 @@ func (h *Host) grantWaits(placements []lifecycle.PlacementIntent, now time.Time) } key := slot.ServerID + "\x00" + p.VolumeID live[key] = true - v, _ := h.grantWait.LoadOrStore(key, now) - waited := now.Sub(v.(time.Time)) + first, seen := h.grantWait[key] + if !seen { + first = now + h.grantWait[key] = now + } + waited := now.Sub(first) out[slot.ServerID] = append(out[slot.ServerID], grantWaitEntry{volume: p.VolumeID, waited: waited, late: waited > window}) } } } - h.grantWait.Range(func(k, _ any) bool { - if !live[k.(string)] { - h.grantWait.Delete(k) + for k := range h.grantWait { + if !live[k] { + delete(h.grantWait, k) } - return true - }) + } for server := range out { sort.Slice(out[server], func(i, j int) bool { return out[server][i].volume < out[server][j].volume }) } diff --git a/seaweed-block/core/host/master/format_level_new_cluster_test.go b/seaweed-block/core/host/master/format_level_new_cluster_test.go index 98db73caad..6ee8607687 100644 --- a/seaweed-block/core/host/master/format_level_new_cluster_test.go +++ b/seaweed-block/core/host/master/format_level_new_cluster_test.go @@ -289,10 +289,18 @@ func TestGrantWaitsAreReconciledPerServerAndVolume(t *testing.T) { if c, ok := cond(late, "node-c"); ok { t.Fatalf("node-c after vc's process reported: %+v; want no wait", c) } - if _, kept := r.m.grantWait.Load("node-c\x00vc"); kept { + if kept := r.m.grantWaitKept("node-c\x00vc"); kept { t.Fatal("vc's wait timer outlived its process's report") } - if _, kept := r.m.grantWait.Load("node-b\x00vb"); !kept { + if kept := r.m.grantWaitKept("node-b\x00vb"); !kept { t.Fatal("vb's wait timer was dropped by another node's reconcile") } } + +// grantWaitKept reports whether the master holds a first-seen time for key. +func (h *Host) grantWaitKept(key string) bool { + h.grantWaitMu.Lock() + defer h.grantWaitMu.Unlock() + _, ok := h.grantWait[key] + return ok +} diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 13ee8ed0b2..40e151d623 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -152,10 +152,11 @@ type Host struct { statusLn net.Listener statusHTTP *http.Server journal *journalIsolation - reads *readsLevels // each server's reported format read level (format_gate.go) - grantWait sync.Map // "server\x00volume" -> time.Time: first seen waiting for its grant without its process's report (format_gate.go grantWaits) - format formatLevelState // the cluster's format level (format_gate.go) - finalizeMu sync.Mutex // serializes the format finalize and host retires (format_gate.go) + reads *readsLevels // each server's reported format read level (format_gate.go) + grantWaitMu sync.Mutex // one status snapshot reconciles grantWait at a time + grantWait map[string]time.Time // "server\x00volume" -> first seen waiting for its grant without its process's report (format_gate.go grantWaits) + format formatLevelState // the cluster's format level (format_gate.go) + finalizeMu sync.Mutex // serializes the format finalize and host retires (format_gate.go) // testPublicationAdmission, when a test sets it before Start, wraps each // publication admission: next runs the admission itself. testPublicationAdmission func(ask authority.AssignmentAsk, next func() error) error From 0e433ad908ea5488238efd7424c416a3a9117e69 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 05:37:28 -0800 Subject: [PATCH 6/8] master: a status snapshot reads its placements under the grant-wait lock The waiting set's placements are read inside the lock that reconciles it, so a snapshot that read older placements can never reconcile after a newer one and drop the wait it started. A held-old/new control pins it. host.go is rewritten without the carriage returns the previous commit added. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/format_gate.go | 18 +- .../master/format_level_new_cluster_test.go | 37 + seaweed-block/core/host/master/host.go | 1397 +++++++++-------- .../core/host/master/observation_snapshot.go | 2 +- 4 files changed, 753 insertions(+), 701 deletions(-) diff --git a/seaweed-block/core/host/master/format_gate.go b/seaweed-block/core/host/master/format_gate.go index 2b9ab0ac0b..6538f04618 100644 --- a/seaweed-block/core/host/master/format_gate.go +++ b/seaweed-block/core/host/master/format_gate.go @@ -193,16 +193,25 @@ type grantWaitEntry struct { // it (granted, reported, unplaced, removed) is dropped, a new one starts // now. The key is server and volume, so waits on different servers never // reset each other. -func (h *Host) grantWaits(placements []lifecycle.PlacementIntent, now time.Time) map[string][]grantWaitEntry { +func (h *Host) grantWaits(now time.Time) map[string][]grantWaitEntry { out := map[string][]grantWaitEntry{} live := map[string]bool{} - // One snapshot at a time computes the set and reconciles against it, so - // a concurrent snapshot never drops an entry this one just started. + // One snapshot at a time reads the placements, computes the set and + // reconciles against it: the read is under the lock, so a snapshot that + // read older placements never reconciles after a newer one and drops an + // entry it started. h.grantWaitMu.Lock() defer h.grantWaitMu.Unlock() if h.grantWait == nil { h.grantWait = map[string]time.Time{} } + var placements []lifecycle.PlacementIntent + if stores := h.Lifecycle(); stores != nil { + placements = stores.Placements.ListPlacements() + } + if hook := h.testGrantWaitsRead; hook != nil { + hook() + } if h.formatLevel() > 0 { window := h.grantStartupWindow() for _, p := range placements { @@ -224,6 +233,9 @@ func (h *Host) grantWaits(placements []lifecycle.PlacementIntent, now time.Time) h.grantWait[key] = now } waited := now.Sub(first) + if waited < 0 { // a caller's now taken before another snapshot started this wait + waited = 0 + } out[slot.ServerID] = append(out[slot.ServerID], grantWaitEntry{volume: p.VolumeID, waited: waited, late: waited > window}) } } diff --git a/seaweed-block/core/host/master/format_level_new_cluster_test.go b/seaweed-block/core/host/master/format_level_new_cluster_test.go index 6ee8607687..ab11db303f 100644 --- a/seaweed-block/core/host/master/format_level_new_cluster_test.go +++ b/seaweed-block/core/host/master/format_level_new_cluster_test.go @@ -5,6 +5,7 @@ import ( "os" "path/filepath" "strings" + "sync" "testing" "time" @@ -297,6 +298,42 @@ func TestGrantWaitsAreReconciledPerServerAndVolume(t *testing.T) { } } +// A status snapshot that read the placements before a newer one never +// reconciles after it: snapshot A holds its read (no placement yet) while +// vb is placed on an unreported node and snapshot B is started; B waits for +// A, then starts vb's wait, and the wait stays. +func TestAnOlderStatusSnapshotNeverDropsANewerOnesWait(t *testing.T) { + r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) + if _, err := r.m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-b", DataAddr: "127.0.0.1:19351", CtrlAddr: "127.0.0.1:19352"}); err != nil { + t.Fatal(err) + } + r.createVolume(t, "vb") + now := time.Now() + var once sync.Once + bDone := make(chan struct{}) + bRanDuringA := false + r.m.testGrantWaitsRead = func() { + once.Do(func() { + r.place(t, "vb", "node-b") + go func() { r.m.ObservationSnapshot(now); close(bDone) }() + select { + case <-bDone: + bRanDuringA = true + case <-time.After(300 * time.Millisecond): + } + }) + } + r.m.ObservationSnapshot(now) // A: read before vb was placed + <-bDone + r.m.testGrantWaitsRead = nil + if bRanDuringA { + t.Fatal("snapshot B reconciled while snapshot A held its older read") + } + if !r.m.grantWaitKept("node-b\x00vb") { + t.Fatal("vb's wait, started by the newer snapshot, was dropped by the older one") + } +} + // grantWaitKept reports whether the master holds a first-seen time for key. func (h *Host) grantWaitKept(key string) bool { h.grantWaitMu.Lock() diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 40e151d623..a3db16fa6f 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -1,697 +1,700 @@ -// Package master implements the block master host: the product-side -// composition of P14 authority components (ObservationHost, -// TopologyController, Publisher, durable authority store) plus -// the gRPC server that exposes ObservationService / AssignmentService -// / EvidenceService to block volume daemons and operator tools. -// -// T0 scope (v3-phase-15-t0-sketch.md §1): this package is the -// master-side hosting layer only. It does NOT implement frontend, -// data path, CSI, security, or operator workflows beyond the -// read-only status surface. -// -// Boundary (sketch §3): gRPC messages carry observation facts -// (volume -> master) and minted assignment facts (master -> -// volume). No RPC endpoint accepts an AssignmentAsk or a -// mutation input. -package master - -import ( - "context" - "errors" - "fmt" - "log" - "net" - "net/http" - "path/filepath" - "sync" - "sync/atomic" - "time" - - "github.com/seaweedfs/seaweed-block/core/auth" - "github.com/seaweedfs/seaweed-block/core/authority" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" - "github.com/seaweedfs/seaweed-block/core/host/bootstrap" - "github.com/seaweedfs/seaweed-block/core/lifecycle" - control "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/rpc/link" - "github.com/seaweedfs/seaweed-block/core/storeident" - "google.golang.org/grpc" -) - -// Config holds the master host construction inputs. Flag parsing -// lives in cmd/blockmaster; this type is the testable seam. -type Config struct { - // Auth authenticates and authorizes every gRPC call (phase 0): nil is - // development mode (plaintext; every call is marked so, and the node - // checks admit it). - Auth *auth.Authenticator - // ServerOptions are added to the gRPC server (transport credentials, - // connection age). - ServerOptions []grpc.ServerOption - - // AuthorityStoreDir is the directory passed to - // authority.AcquireStoreLock + NewFileAuthorityStore. Must be - // non-empty. - AuthorityStoreDir string - - // Listen is the TCP address for the gRPC server, e.g. - // "127.0.0.1:0" or ":9180". - Listen string - - // Topology is the accepted topology the observation host - // uses to decide supportability. - Topology authority.AcceptedTopology - - // Freshness configures observation expiry semantics. - Freshness authority.FreshnessConfig - - // ControllerConfig tunes controller knobs (retry window etc). - ControllerConfig authority.TopologyControllerConfig - - // LifecycleProductLoop reports that the host's lifecycle product loop - // runs (blockmaster --lifecycle-product-loop-interval above 0). A volume - // absent from the static topology requires it at CreateVolume and - // PlaceWorkspace; replicated creates also require it in static topology. - LifecycleProductLoop bool - - // LifecycleStoreDir, when non-empty, opens product lifecycle - // registration stores (desired volumes, node inventory, placement - // intents). This is read-only composition for G9D: these stores do - // NOT drive assignment publication. - LifecycleStoreDir string - - // FailbackRuntimeRPC enables the authority failback RPC surface. It is - // disabled by default; callers must still provide expected-current and - // terminal evidence when enabled. - FailbackRuntimeRPC bool - - // WorkspaceRPC enables the RF1 lease/revoke/move surface. HEAD must be - // obtained from the configured remote source, never from operator flags. - WorkspaceMaxClockSkew time.Duration - WorkspaceRPC bool - WorkspaceHeadReader func(context.Context, string) (authority.WorkspaceHead, error) - // LayoutCreateVolume writes VOLUME then the unclaimed HEAD using the - // immutable identity and geometry in the persisted lifecycle record. - LayoutCreateVolume func(context.Context, lifecycle.VolumeSpec) error - // Restore creation reads the source VOLUME's immutable geometry before - // persisting the target, then replays CreateTarget using that record. - LayoutReadVolume func(context.Context, lifecycle.VolumeSpec) (layout.Volume, error) - LayoutReadHead func(context.Context, lifecycle.VolumeSpec) (layout.Head, error) - LayoutCreateTarget func(context.Context, lifecycle.VolumeSpec, lifecycle.VolumeSpec, string) error - - // FrontendPublicationRuntimeHTTP enables the frontend publication runtime - // HTTP surface. It is disabled by default and only confirms a post-failback - // authority line that has already been minted by the failback owner. - FrontendPublicationRuntimeHTTP bool - FrontendPublicationRuntimeListen string - - // StrictJournalIsolation refuses nodes whose durable root shares the - // authority store's file system (one journal): a co-located node that - // serves no volume yet gets its heartbeats refused, and no new placement - // or move targets a co-located node. A co-located node that already - // serves volumes is only alarmed (refusing it would stop its lease - // renewals). Off: alarm only. - StrictJournalIsolation bool - - // StatusListen, when non-empty, serves the read-only status endpoint - // GET /status/workspace-lease on this loopback address. - StatusListen string - - // Logger is used for structured startup and error logging. If - // nil, the default log package logger is used. - Logger *log.Logger -} - -// LifecycleStores groups the product registration stores hosted by -// blockmaster. The stores are controller input only; assignment -// publication remains owned by authority.Controller/Publisher. -type LifecycleStores struct { - Volumes *lifecycle.FileStore - Nodes *lifecycle.NodeInventoryStore - Placements *lifecycle.PlacementIntentStore - WorkspaceBindings workspaceBindingStore - // Deletions holds the chunk-volume deletion reservations. - Deletions *lifecycle.DeletionReservationStore -} - -// Host is the composed master-side block product daemon. Lifecycle -// is: New -> Start -> (serve requests) -> Close. -type Host struct { - probeHub *probeHub // the promotion probe round (probe_round.go) - probeSlots slotServers // replica -> server, for the round - cfg Config - attest *storeAttestations // primaries' attested write-ACK stores - healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6) - log *log.Logger - boot *bootstrap.DurableAuthorityBootstrap - ctrl *authority.TopologyController - obs *authority.ObservationHost - ln net.Listener - frontendRuntimeLn net.Listener - frontendRuntimeHTTP *http.Server - statusLn net.Listener - statusHTTP *http.Server - journal *journalIsolation - reads *readsLevels // each server's reported format read level (format_gate.go) - grantWaitMu sync.Mutex // one status snapshot reconciles grantWait at a time - grantWait map[string]time.Time // "server\x00volume" -> first seen waiting for its grant without its process's report (format_gate.go grantWaits) - format formatLevelState // the cluster's format level (format_gate.go) - finalizeMu sync.Mutex // serializes the format finalize and host retires (format_gate.go) - // testPublicationAdmission, when a test sets it before Start, wraps each - // publication admission: next runs the admission itself. - testPublicationAdmission func(ask authority.AssignmentAsk, next func() error) error - grpc *grpc.Server - topo authority.AcceptedTopology - lifecycle *LifecycleStores - // RPC registration/place/move/ACK/delete and product ticks serialize here. - // Order: workspaceMu -> publisher or lifecycle store locks (not reversed). - workspaceMu sync.Mutex - // bindingRetry: volumes whose binding reconcile failed, retried with the - // next call's own volume (workspaceMu held). - bindingRetry map[string]bool - events *eventRing - promotionMu sync.RWMutex - promotionProber PromotionEvidenceProvider - // fencePending: volume -> the epoch a fencing round fenced survivors at - // without a line being published there. Until the line reaches it, those - // survivors refuse the primary, so the gate keeps trying to heal it. - fencePending map[string]uint64 - cancel context.CancelFunc - wg sync.WaitGroup - - started atomic.Bool -} - -// publisherHolder resolves the chicken-and-egg between the -// controller (which needs the publisher as its reader) and the -// publisher (which needs the controller as its directive). -// Construction order: create holder, create controller(holder), -// Bootstrap(dir, controller) builds publisher, set holder=publisher. -// The controller sees an empty reader until Bootstrap returns; -// that's fine because no rebuild runs until host.Start(). -type publisherHolder struct { - mu sync.Mutex - p *authority.Publisher -} - -func (h *publisherHolder) set(p *authority.Publisher) { - h.mu.Lock() - h.p = p - h.mu.Unlock() -} - -func (h *publisherHolder) LastAuthorityBasis(vid, rid string) (authority.AuthorityBasis, bool) { - h.mu.Lock() - p := h.p - h.mu.Unlock() - if p == nil { - return authority.AuthorityBasis{}, false - } - return p.LastAuthorityBasis(vid, rid) -} - -func (h *publisherHolder) VolumeAuthorityLine(vid string) (authority.AuthorityBasis, bool) { - h.mu.Lock() - p := h.p - h.mu.Unlock() - if p == nil { - return authority.AuthorityBasis{}, false - } - return p.VolumeAuthorityLine(vid) -} - -// New constructs a master host but does NOT start live loops. The -// caller composes it, then calls Start. -// -// Startup order matches T0 sketch §5 + S7 restart pin: -// 1. acquire durable store lock + open store (via sparrow.Bootstrap) -// 2. NewPublisher(WithStore) — synchronous reload (inside Bootstrap) -// 3. controller sees reloaded publisher (via holder back-fill) -// 4. NewObservationHost with reloaded publisher; controller as sink -// 5. bind gRPC listener, register services -// -// Live loops (publisher.Run, host.Start, grpc.Serve) run in Start. -func New(cfg Config) (*Host, error) { - if cfg.WorkspaceMaxClockSkew < 0 || cfg.WorkspaceMaxClockSkew >= 60*time.Second { - return nil, fmt.Errorf("master.New: workspace max clock skew must be positive and less than 60s (zero selects default)") - } - if cfg.WorkspaceRPC && (cfg.WorkspaceHeadReader == nil || cfg.LifecycleStoreDir == "") { - return nil, fmt.Errorf("master.New: workspace RPC requires HEAD reader and lifecycle store") - } - if cfg.AuthorityStoreDir == "" { - return nil, fmt.Errorf("master.New: AuthorityStoreDir is required") - } - if cfg.Listen == "" { - return nil, fmt.Errorf("master.New: Listen is required") - } - if err := ValidateStatusListen(cfg.StatusListen); err != nil { - return nil, fmt.Errorf("master.New: %w", err) - } - lg := cfg.Logger - if lg == nil { - lg = log.Default() - } - - holder := &publisherHolder{} - ctrlCfg := cfg.ControllerConfig - if w := cfg.Freshness.EffectiveFreshnessWindow(); ctrlCfg.PrimaryBootGrace <= 0 || ctrlCfg.PrimaryBootGrace > w { - // A restarted primary may stay not-ready for at most the - // window in which its observations are trusted (#128): the - // store's effective window, also when the config omits it. A - // larger configured grace is capped, never widened; an unset - // or nonpositive one takes the window. - if ctrlCfg.PrimaryBootGrace > w { - lg.Printf("blockmaster: primary boot grace %s capped at freshness window %s", ctrlCfg.PrimaryBootGrace, w) - } - ctrlCfg.PrimaryBootGrace = w - } - ctrl := authority.NewTopologyController(ctrlCfg, holder) - - h := &Host{ - probeHub: newProbeHub(), - cfg: cfg, - log: lg, - ctrl: ctrl, - topo: cfg.Topology, - events: newEventRing(1024), - journal: newJournalIsolation(storeident.Identity{}), // sampled once the store exists - reads: newReadsLevels(cfg.Freshness.EffectiveFreshnessWindow()), - } - - boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{ - WorkspaceMaxClockSkew: cfg.WorkspaceMaxClockSkew, - PublishObserver: h.recordAuthorityPublishedEvent, - PublicationAdmission: h.admitWorkspacePublication, - }) - if err != nil { - return nil, fmt.Errorf("master.New: Bootstrap: %w", err) - } - holder.set(boot.Publisher) - // Bootstrap creates a fresh store directory: sample its file system only - // now, or a first start would compare against an unknown device forever. - // An unknown identity (stat error, unsupported platform) never matches. - h.journal.setSelf(storeident.Of(cfg.AuthorityStoreDir)) - if h.attest, err = loadStoreAttestations(cfg.AuthorityStoreDir); err != nil { - _ = boot.Close() // release the store lock: this master never serves - return nil, fmt.Errorf("master.New: %w", err) - } - // The lifecycle stores open before the format decision: they are part of - // the master's state it reads. - lifecycleStores, err := openLifecycleStores(cfg.LifecycleStoreDir) - if err != nil { - _ = boot.Close() - return nil, fmt.Errorf("master.New: lifecycle stores: %w", err) - } - // A new cluster starts at the current level (r2.869): with no prior - // state in any master store (no authority record reloaded or skipped, no - // attestation file, no volume, node, placement or deletion in the - // lifecycle stores), the master writes the level-1 envelope durably now, - // before anything is served. A crash before that write leaves the same - // empty state, so the next start makes the same choice. Existing state - // without the envelope stays level 0: only a cluster that holds v1.0 data - // needs the finalize. - if newClusterAtStart(boot.ReloadedRecords, len(boot.ReloadSkips), h.attest.absent(), lifecycleStores.empty()) { - if _, err := h.attest.finalize(); err != nil { - _ = boot.Close() - return nil, fmt.Errorf("master.New: a new cluster's format level: %w", err) - } - lg.Printf("blockmaster: new cluster: format level 1 (no prior authority state; no finalize needed)") - } - // Under the authority store's lock and before anything is served: the - // cluster's format level is the attestation file's form (the envelope - // is level 1, re-fsynced here; v1.0.x's form is level 0, where this - // master keeps v1.0's semantics: store_attestation.go, format_gate.go). - if err := h.attest.ensureEnvelope(); err != nil { - _ = boot.Close() - return nil, fmt.Errorf("master.New: %w", err) - } - level := h.attest.level() - boot.Publisher.SetFormatLevelBeforeServing(level) - h.format.v.Store(level) - - var sink authority.ControllerSink = ctrl - if len(cfg.Topology.Volumes) == 0 { - // Dynamic lifecycle volumes derive their accepted topology from - // placement intents in RunLifecycleProductTick. With no static - // topology configured, the observation host should collect facts - // but must not submit "unknown volume" reports that would clear - // lifecycle-driven desired authority. - sink = nil - } - obs := authority.NewObservationHost(authority.ObservationHostConfig{ - Freshness: cfg.Freshness, - Topology: cfg.Topology, - Sink: sink, - Reader: boot.Publisher, - }) - // A published line changes what the observation build reads, and no - // heartbeat carries it: it wakes the build. - boot.Publisher.SetLineChangeHook(func(string) { obs.Wake() }) - // An ask built outside the controller (a heal, a planned or workspace - // move, an operator's request) is issued for the process its target - // reports now. - boot.Publisher.SetIncarnationSource(func(volumeID, replicaID, dataAddr, ctrlAddr string) string { - if f, ok := obs.Store().SlotFactAt(volumeID, replicaID, dataAddr, ctrlAddr); ok { - return f.Incarnation - } - return "" - }) - - ln, err := net.Listen("tcp", cfg.Listen) - if err != nil { - _ = boot.Close() - return nil, fmt.Errorf("master.New: listen %q: %w", cfg.Listen, err) - } - - h.boot = boot - h.obs = obs - h.ln = ln - h.lifecycle = lifecycleStores - if h.lifecycle != nil { - // Rebuild permanent grant exclusions before any request, publisher - // loop or lifecycle reconciliation can create positive validity. - for _, volume := range h.lifecycle.Deletions.CommittedVolumes() { - if err := h.Publisher().ReserveWorkspaceDeletion(context.Background(), volume, nil); err != nil { - _ = ln.Close() - _ = boot.Close() - return nil, fmt.Errorf("master.New: deletion reservation recovery: %w", err) - } - } - if err := h.reconcileWorkspaceBindings(); err != nil { - _ = ln.Close() - _ = boot.Close() - return nil, fmt.Errorf("master.New: workspace binding recovery: %w", err) - } - } - - if cfg.FrontendPublicationRuntimeHTTP { - addr := cfg.FrontendPublicationRuntimeListen - if addr == "" { - addr = "127.0.0.1:0" - } - frontendLn, err := net.Listen("tcp", addr) - if err != nil { - _ = ln.Close() - _ = boot.Close() - return nil, fmt.Errorf("master.New: frontend publication runtime listen %q: %w", addr, err) - } - h.frontendRuntimeLn = frontendLn - h.frontendRuntimeHTTP = &http.Server{Handler: h.frontendPublicationRuntimeHandler()} - } - - if cfg.StatusListen != "" { - statusLn, err := net.Listen("tcp", cfg.StatusListen) - if err != nil { - if h.frontendRuntimeLn != nil { - _ = h.frontendRuntimeLn.Close() - } - _ = ln.Close() - _ = boot.Close() - return nil, fmt.Errorf("master.New: status listen %q: %w", cfg.StatusListen, err) - } - h.statusLn = statusLn - // Every connection phase is bounded: a client that withholds a - // declared body or never reads the reply is cut off. - h.statusHTTP = &http.Server{Handler: h.statusHandler(), ReadHeaderTimeout: statusReadTimeout, ReadTimeout: statusReadTimeout, - WriteTimeout: statusWriteTimeout, IdleTimeout: statusIdleTimeout} - } - - grpcSrv := link.NewServer(serverAuth(cfg.Auth), cfg.ServerOptions...) - svc := newServices(h) - control.RegisterObservationServiceServer(grpcSrv, svc) - control.RegisterAssignmentServiceServer(grpcSrv, svc) - control.RegisterEvidenceServiceServer(grpcSrv, svc) - control.RegisterClusterEvidenceServiceServer(grpcSrv, svc) - control.RegisterLifecycleServiceServer(grpcSrv, svc) - control.RegisterFailbackServiceServer(grpcSrv, svc) - control.RegisterWorkspaceServiceServer(grpcSrv, svc) - h.grpc = grpcSrv - - lg.Printf("blockmaster: lock acquired, reloaded=%d, listen=%s", - boot.ReloadedRecords, ln.Addr().String()) - if h.frontendRuntimeLn != nil { - lg.Printf("blockmaster: frontend publication runtime listen=%s", h.frontendRuntimeLn.Addr().String()) - } - if h.statusLn != nil { - lg.Printf("blockmaster: status listen=%s", h.statusLn.Addr().String()) - } - if cfg.StrictJournalIsolation { - lg.Printf("blockmaster: strict journal isolation: nodes sharing the authority store's file system are refused new work") - } - for _, e := range boot.ReloadSkips { - lg.Printf("blockmaster: reload skip: %v", e) - } - return h, nil -} - -func openLifecycleStores(dir string) (*LifecycleStores, error) { - if dir == "" { - return nil, nil - } - volumes, err := lifecycle.OpenFileStore(filepath.Join(dir, "volumes")) - if err != nil { - return nil, err - } - nodes, err := lifecycle.OpenNodeInventoryStore(filepath.Join(dir, "nodes")) - if err != nil { - return nil, err - } - placements, err := lifecycle.OpenPlacementIntentStore(filepath.Join(dir, "placements")) - if err != nil { - return nil, err - } - bindings, err := lifecycle.OpenWorkspaceBindingStore(filepath.Join(dir, "workspace-bindings")) - if err != nil { - return nil, err - } - deletions, err := lifecycle.OpenDeletionReservationStore(filepath.Join(dir, "deletion-reservations")) - if err != nil { - return nil, err - } - return &LifecycleStores{ - Volumes: volumes, - Nodes: nodes, - Placements: placements, - WorkspaceBindings: bindings, - Deletions: deletions, - }, nil -} - -// Addr returns the bound listener address. Valid after New. -func (h *Host) Addr() string { return h.ln.Addr().String() } - -// FrontendPublicationRuntimeAddr returns the bound frontend publication -// runtime HTTP address, or empty when the runtime is disabled. -func (h *Host) FrontendPublicationRuntimeAddr() string { - if h.frontendRuntimeLn == nil { - return "" - } - return h.frontendRuntimeLn.Addr().String() -} - -// StatusAddr returns the bound status HTTP address, or empty when the status -// endpoint is disabled. -func (h *Host) StatusAddr() string { - if h.statusLn == nil { - return "" - } - return h.statusLn.Addr().String() -} - -// Publisher exposes the reloaded publisher for tests and for the -// evidence-query path. -func (h *Host) Publisher() *authority.Publisher { - if h == nil || h.boot == nil { - return nil - } - return h.boot.Publisher -} - -// FailbackAuthorityRuntime exposes the authority-owned failback seam backed by -// the live Publisher. Callers still need an explicit policy gate before using -// it; constructing the runtime does not execute failback. -func (h *Host) FailbackAuthorityRuntime() authority.FailbackAuthorityRuntime { - return authority.FailbackAuthorityRuntime{Publisher: h.Publisher(), Gate: h.plannedMoveEvidenceAt, TargetEndpoint: h.replicaEndpoint} -} - -// replicaEndpoint is the master's own record of a replica's addresses: its -// fresh heartbeat slot (what the automatic path publishes), else its -// placement slot when that names both. -func (h *Host) replicaEndpoint(volumeID, replicaID string) (string, string, bool) { - if s, ok := h.freshCurrentSlot(volumeID, replicaID); ok && s.DataAddr != "" && s.CtrlAddr != "" { - return s.DataAddr, s.CtrlAddr, true - } - if h.lifecycle != nil { - if p, ok := h.lifecycle.Placements.GetPlacement(volumeID); ok { - for _, s := range p.Slots { - if s.ReplicaID == replicaID && s.DataAddr != "" && s.CtrlAddr != "" { - return s.DataAddr, s.CtrlAddr, true - } - } - } - } - return "", "", false -} - -// Controller exposes the controller for tests. -func (h *Host) Controller() *authority.TopologyController { return h.ctrl } - -// ObservationHost exposes the observation host for tests. -func (h *Host) ObservationHost() *authority.ObservationHost { return h.obs } - -// Lifecycle returns product registration stores when configured. Nil means -// the daemon is running in static-topology-only mode. Reading these stores -// must not be treated as assignment authority. -func (h *Host) Lifecycle() *LifecycleStores { return h.lifecycle } - -// replicaSlotsFor returns replica IDs for a volume. Static topology -// remains the allow-list. Dynamic lifecycle volumes may not persist -// placement slots in the lifecycle record, so read-only status paths -// merge fresh observed slots from the observation store; assignment -// authority still comes from the publisher/controller, not this helper. -func (h *Host) replicaSlotsFor(volumeID string) []string { - for _, v := range h.topo.Volumes { - if v.VolumeID != volumeID { - continue - } - out := make([]string, 0, len(v.Slots)) - for _, s := range v.Slots { - out = append(out, s.ReplicaID) - } - return out - } - var out []string - if h.lifecycle != nil && h.lifecycle.Placements != nil { - if placement, ok := h.lifecycle.Placements.GetPlacement(volumeID); ok { - for _, slot := range placement.Slots { - if slot.ReplicaID != "" { - out = appendReplicaID(out, slot.ReplicaID) - } - } - } - } - if h.lifecycle != nil && h.obs != nil { - for _, replicaID := range h.obs.Store().ReplicaIDsForVolume(volumeID) { - out = appendReplicaID(out, replicaID) - } - } - if len(out) == 0 { - return nil - } - return out -} - -func appendReplicaID(in []string, replicaID string) []string { - for _, existing := range in { - if existing == replicaID { - return in - } - } - return append(in, replicaID) -} - -// Start runs the publisher, observation rebuild loop, and gRPC -// server. Returns a context that is cancelled on Close so callers -// can wait on it from their own goroutines. Idempotent — second -// Start() returns the prior ctx. -func (h *Host) Start() context.Context { - if !h.started.CompareAndSwap(false, true) { - return nil - } - ctx, cancel := context.WithCancel(context.Background()) - h.cancel = cancel - - h.wg.Add(1) - go func() { - defer h.wg.Done() - _ = h.boot.Publisher.Run(ctx) - }() - - h.obs.Start(ctx) - - h.wg.Add(1) - go func() { - defer h.wg.Done() - if err := h.grpc.Serve(h.ln); err != nil && err != grpc.ErrServerStopped { - h.log.Printf("blockmaster: grpc.Serve: %v", err) - } - }() - - if h.frontendRuntimeHTTP != nil && h.frontendRuntimeLn != nil { - h.wg.Add(1) - go func() { - defer h.wg.Done() - if err := h.frontendRuntimeHTTP.Serve(h.frontendRuntimeLn); err != nil && err != http.ErrServerClosed { - h.log.Printf("blockmaster: frontend publication runtime Serve: %v", err) - } - }() - } - - if h.statusHTTP != nil && h.statusLn != nil { - h.wg.Add(1) - go func() { - defer h.wg.Done() - if err := h.statusHTTP.Serve(h.statusLn); err != nil && err != http.ErrServerClosed { - h.log.Printf("blockmaster: status Serve: %v", err) - } - }() - } - - return ctx -} - -// Close stops the gRPC server, cancels live loops, and releases -// the durable store lock. Idempotent. -func (h *Host) Close(ctx context.Context) error { - if h.cancel != nil { - h.cancel() - } - if h.frontendRuntimeHTTP != nil { - _ = h.frontendRuntimeHTTP.Shutdown(ctx) - } - var statusErr error - if h.statusHTTP != nil { - statusErr = h.closeStatusHTTP(ctx) - } - h.obs.Stop() - - done := make(chan struct{}) - go func() { - h.grpc.GracefulStop() - close(done) - }() - select { - case <-done: - case <-ctx.Done(): - h.grpc.Stop() - } - - h.wg.Wait() - // Level 0's horizon extenders write through the store: join them first. - h.boot.Publisher.CloseWorkspaceExtenders() - return errors.Join(statusErr, h.boot.Close()) -} - -// Status endpoint connection bounds. -const ( - statusReadTimeout = 5 * time.Second - statusWriteTimeout = 5 * time.Second - statusIdleTimeout = 30 * time.Second -) - -// closeStatusHTTP shuts the status endpoint down gracefully until ctx ends, -// then force-closes the connections still open (Shutdown leaves them). It -// returns the force close's error, if any; an expired graceful shutdown that -// the force close completed is only logged. -func (h *Host) closeStatusHTTP(ctx context.Context) error { - defer h.statusLn.Close() // a listener Start never served is not Shutdown's - err := h.statusHTTP.Shutdown(ctx) - if err == nil { - return nil - } - h.log.Printf("blockmaster: status graceful shutdown: %v; closing its open connections", err) - if cerr := h.statusHTTP.Close(); cerr != nil && !errors.Is(cerr, net.ErrClosed) { - return fmt.Errorf("status endpoint close: %w", cerr) - } - return nil -} +// Package master implements the block master host: the product-side +// composition of P14 authority components (ObservationHost, +// TopologyController, Publisher, durable authority store) plus +// the gRPC server that exposes ObservationService / AssignmentService +// / EvidenceService to block volume daemons and operator tools. +// +// T0 scope (v3-phase-15-t0-sketch.md §1): this package is the +// master-side hosting layer only. It does NOT implement frontend, +// data path, CSI, security, or operator workflows beyond the +// read-only status surface. +// +// Boundary (sketch §3): gRPC messages carry observation facts +// (volume -> master) and minted assignment facts (master -> +// volume). No RPC endpoint accepts an AssignmentAsk or a +// mutation input. +package master + +import ( + "context" + "errors" + "fmt" + "log" + "net" + "net/http" + "path/filepath" + "sync" + "sync/atomic" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/bootstrap" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "github.com/seaweedfs/seaweed-block/core/storeident" + "google.golang.org/grpc" +) + +// Config holds the master host construction inputs. Flag parsing +// lives in cmd/blockmaster; this type is the testable seam. +type Config struct { + // Auth authenticates and authorizes every gRPC call (phase 0): nil is + // development mode (plaintext; every call is marked so, and the node + // checks admit it). + Auth *auth.Authenticator + // ServerOptions are added to the gRPC server (transport credentials, + // connection age). + ServerOptions []grpc.ServerOption + + // AuthorityStoreDir is the directory passed to + // authority.AcquireStoreLock + NewFileAuthorityStore. Must be + // non-empty. + AuthorityStoreDir string + + // Listen is the TCP address for the gRPC server, e.g. + // "127.0.0.1:0" or ":9180". + Listen string + + // Topology is the accepted topology the observation host + // uses to decide supportability. + Topology authority.AcceptedTopology + + // Freshness configures observation expiry semantics. + Freshness authority.FreshnessConfig + + // ControllerConfig tunes controller knobs (retry window etc). + ControllerConfig authority.TopologyControllerConfig + + // LifecycleProductLoop reports that the host's lifecycle product loop + // runs (blockmaster --lifecycle-product-loop-interval above 0). A volume + // absent from the static topology requires it at CreateVolume and + // PlaceWorkspace; replicated creates also require it in static topology. + LifecycleProductLoop bool + + // LifecycleStoreDir, when non-empty, opens product lifecycle + // registration stores (desired volumes, node inventory, placement + // intents). This is read-only composition for G9D: these stores do + // NOT drive assignment publication. + LifecycleStoreDir string + + // FailbackRuntimeRPC enables the authority failback RPC surface. It is + // disabled by default; callers must still provide expected-current and + // terminal evidence when enabled. + FailbackRuntimeRPC bool + + // WorkspaceRPC enables the RF1 lease/revoke/move surface. HEAD must be + // obtained from the configured remote source, never from operator flags. + WorkspaceMaxClockSkew time.Duration + WorkspaceRPC bool + WorkspaceHeadReader func(context.Context, string) (authority.WorkspaceHead, error) + // LayoutCreateVolume writes VOLUME then the unclaimed HEAD using the + // immutable identity and geometry in the persisted lifecycle record. + LayoutCreateVolume func(context.Context, lifecycle.VolumeSpec) error + // Restore creation reads the source VOLUME's immutable geometry before + // persisting the target, then replays CreateTarget using that record. + LayoutReadVolume func(context.Context, lifecycle.VolumeSpec) (layout.Volume, error) + LayoutReadHead func(context.Context, lifecycle.VolumeSpec) (layout.Head, error) + LayoutCreateTarget func(context.Context, lifecycle.VolumeSpec, lifecycle.VolumeSpec, string) error + + // FrontendPublicationRuntimeHTTP enables the frontend publication runtime + // HTTP surface. It is disabled by default and only confirms a post-failback + // authority line that has already been minted by the failback owner. + FrontendPublicationRuntimeHTTP bool + FrontendPublicationRuntimeListen string + + // StrictJournalIsolation refuses nodes whose durable root shares the + // authority store's file system (one journal): a co-located node that + // serves no volume yet gets its heartbeats refused, and no new placement + // or move targets a co-located node. A co-located node that already + // serves volumes is only alarmed (refusing it would stop its lease + // renewals). Off: alarm only. + StrictJournalIsolation bool + + // StatusListen, when non-empty, serves the read-only status endpoint + // GET /status/workspace-lease on this loopback address. + StatusListen string + + // Logger is used for structured startup and error logging. If + // nil, the default log package logger is used. + Logger *log.Logger +} + +// LifecycleStores groups the product registration stores hosted by +// blockmaster. The stores are controller input only; assignment +// publication remains owned by authority.Controller/Publisher. +type LifecycleStores struct { + Volumes *lifecycle.FileStore + Nodes *lifecycle.NodeInventoryStore + Placements *lifecycle.PlacementIntentStore + WorkspaceBindings workspaceBindingStore + // Deletions holds the chunk-volume deletion reservations. + Deletions *lifecycle.DeletionReservationStore +} + +// Host is the composed master-side block product daemon. Lifecycle +// is: New -> Start -> (serve requests) -> Close. +type Host struct { + probeHub *probeHub // the promotion probe round (probe_round.go) + probeSlots slotServers // replica -> server, for the round + cfg Config + attest *storeAttestations // primaries' attested write-ACK stores + healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6) + log *log.Logger + boot *bootstrap.DurableAuthorityBootstrap + ctrl *authority.TopologyController + obs *authority.ObservationHost + ln net.Listener + frontendRuntimeLn net.Listener + frontendRuntimeHTTP *http.Server + statusLn net.Listener + statusHTTP *http.Server + journal *journalIsolation + reads *readsLevels // each server's reported format read level (format_gate.go) + grantWaitMu sync.Mutex // one status snapshot reads and reconciles the grant waits at a time + grantWait map[string]time.Time // "server\x00volume" -> first seen waiting for its grant without its process's report (format_gate.go grantWaits) + format formatLevelState // the cluster's format level (format_gate.go) + finalizeMu sync.Mutex // serializes the format finalize and host retires (format_gate.go) + // testGrantWaitsRead, when a test sets it, runs after a status snapshot + // has read its placements, still holding grantWaitMu. + testGrantWaitsRead func() + // testPublicationAdmission, when a test sets it before Start, wraps each + // publication admission: next runs the admission itself. + testPublicationAdmission func(ask authority.AssignmentAsk, next func() error) error + grpc *grpc.Server + topo authority.AcceptedTopology + lifecycle *LifecycleStores + // RPC registration/place/move/ACK/delete and product ticks serialize here. + // Order: workspaceMu -> publisher or lifecycle store locks (not reversed). + workspaceMu sync.Mutex + // bindingRetry: volumes whose binding reconcile failed, retried with the + // next call's own volume (workspaceMu held). + bindingRetry map[string]bool + events *eventRing + promotionMu sync.RWMutex + promotionProber PromotionEvidenceProvider + // fencePending: volume -> the epoch a fencing round fenced survivors at + // without a line being published there. Until the line reaches it, those + // survivors refuse the primary, so the gate keeps trying to heal it. + fencePending map[string]uint64 + cancel context.CancelFunc + wg sync.WaitGroup + + started atomic.Bool +} + +// publisherHolder resolves the chicken-and-egg between the +// controller (which needs the publisher as its reader) and the +// publisher (which needs the controller as its directive). +// Construction order: create holder, create controller(holder), +// Bootstrap(dir, controller) builds publisher, set holder=publisher. +// The controller sees an empty reader until Bootstrap returns; +// that's fine because no rebuild runs until host.Start(). +type publisherHolder struct { + mu sync.Mutex + p *authority.Publisher +} + +func (h *publisherHolder) set(p *authority.Publisher) { + h.mu.Lock() + h.p = p + h.mu.Unlock() +} + +func (h *publisherHolder) LastAuthorityBasis(vid, rid string) (authority.AuthorityBasis, bool) { + h.mu.Lock() + p := h.p + h.mu.Unlock() + if p == nil { + return authority.AuthorityBasis{}, false + } + return p.LastAuthorityBasis(vid, rid) +} + +func (h *publisherHolder) VolumeAuthorityLine(vid string) (authority.AuthorityBasis, bool) { + h.mu.Lock() + p := h.p + h.mu.Unlock() + if p == nil { + return authority.AuthorityBasis{}, false + } + return p.VolumeAuthorityLine(vid) +} + +// New constructs a master host but does NOT start live loops. The +// caller composes it, then calls Start. +// +// Startup order matches T0 sketch §5 + S7 restart pin: +// 1. acquire durable store lock + open store (via sparrow.Bootstrap) +// 2. NewPublisher(WithStore) — synchronous reload (inside Bootstrap) +// 3. controller sees reloaded publisher (via holder back-fill) +// 4. NewObservationHost with reloaded publisher; controller as sink +// 5. bind gRPC listener, register services +// +// Live loops (publisher.Run, host.Start, grpc.Serve) run in Start. +func New(cfg Config) (*Host, error) { + if cfg.WorkspaceMaxClockSkew < 0 || cfg.WorkspaceMaxClockSkew >= 60*time.Second { + return nil, fmt.Errorf("master.New: workspace max clock skew must be positive and less than 60s (zero selects default)") + } + if cfg.WorkspaceRPC && (cfg.WorkspaceHeadReader == nil || cfg.LifecycleStoreDir == "") { + return nil, fmt.Errorf("master.New: workspace RPC requires HEAD reader and lifecycle store") + } + if cfg.AuthorityStoreDir == "" { + return nil, fmt.Errorf("master.New: AuthorityStoreDir is required") + } + if cfg.Listen == "" { + return nil, fmt.Errorf("master.New: Listen is required") + } + if err := ValidateStatusListen(cfg.StatusListen); err != nil { + return nil, fmt.Errorf("master.New: %w", err) + } + lg := cfg.Logger + if lg == nil { + lg = log.Default() + } + + holder := &publisherHolder{} + ctrlCfg := cfg.ControllerConfig + if w := cfg.Freshness.EffectiveFreshnessWindow(); ctrlCfg.PrimaryBootGrace <= 0 || ctrlCfg.PrimaryBootGrace > w { + // A restarted primary may stay not-ready for at most the + // window in which its observations are trusted (#128): the + // store's effective window, also when the config omits it. A + // larger configured grace is capped, never widened; an unset + // or nonpositive one takes the window. + if ctrlCfg.PrimaryBootGrace > w { + lg.Printf("blockmaster: primary boot grace %s capped at freshness window %s", ctrlCfg.PrimaryBootGrace, w) + } + ctrlCfg.PrimaryBootGrace = w + } + ctrl := authority.NewTopologyController(ctrlCfg, holder) + + h := &Host{ + probeHub: newProbeHub(), + cfg: cfg, + log: lg, + ctrl: ctrl, + topo: cfg.Topology, + events: newEventRing(1024), + journal: newJournalIsolation(storeident.Identity{}), // sampled once the store exists + reads: newReadsLevels(cfg.Freshness.EffectiveFreshnessWindow()), + } + + boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{ + WorkspaceMaxClockSkew: cfg.WorkspaceMaxClockSkew, + PublishObserver: h.recordAuthorityPublishedEvent, + PublicationAdmission: h.admitWorkspacePublication, + }) + if err != nil { + return nil, fmt.Errorf("master.New: Bootstrap: %w", err) + } + holder.set(boot.Publisher) + // Bootstrap creates a fresh store directory: sample its file system only + // now, or a first start would compare against an unknown device forever. + // An unknown identity (stat error, unsupported platform) never matches. + h.journal.setSelf(storeident.Of(cfg.AuthorityStoreDir)) + if h.attest, err = loadStoreAttestations(cfg.AuthorityStoreDir); err != nil { + _ = boot.Close() // release the store lock: this master never serves + return nil, fmt.Errorf("master.New: %w", err) + } + // The lifecycle stores open before the format decision: they are part of + // the master's state it reads. + lifecycleStores, err := openLifecycleStores(cfg.LifecycleStoreDir) + if err != nil { + _ = boot.Close() + return nil, fmt.Errorf("master.New: lifecycle stores: %w", err) + } + // A new cluster starts at the current level (r2.869): with no prior + // state in any master store (no authority record reloaded or skipped, no + // attestation file, no volume, node, placement or deletion in the + // lifecycle stores), the master writes the level-1 envelope durably now, + // before anything is served. A crash before that write leaves the same + // empty state, so the next start makes the same choice. Existing state + // without the envelope stays level 0: only a cluster that holds v1.0 data + // needs the finalize. + if newClusterAtStart(boot.ReloadedRecords, len(boot.ReloadSkips), h.attest.absent(), lifecycleStores.empty()) { + if _, err := h.attest.finalize(); err != nil { + _ = boot.Close() + return nil, fmt.Errorf("master.New: a new cluster's format level: %w", err) + } + lg.Printf("blockmaster: new cluster: format level 1 (no prior authority state; no finalize needed)") + } + // Under the authority store's lock and before anything is served: the + // cluster's format level is the attestation file's form (the envelope + // is level 1, re-fsynced here; v1.0.x's form is level 0, where this + // master keeps v1.0's semantics: store_attestation.go, format_gate.go). + if err := h.attest.ensureEnvelope(); err != nil { + _ = boot.Close() + return nil, fmt.Errorf("master.New: %w", err) + } + level := h.attest.level() + boot.Publisher.SetFormatLevelBeforeServing(level) + h.format.v.Store(level) + + var sink authority.ControllerSink = ctrl + if len(cfg.Topology.Volumes) == 0 { + // Dynamic lifecycle volumes derive their accepted topology from + // placement intents in RunLifecycleProductTick. With no static + // topology configured, the observation host should collect facts + // but must not submit "unknown volume" reports that would clear + // lifecycle-driven desired authority. + sink = nil + } + obs := authority.NewObservationHost(authority.ObservationHostConfig{ + Freshness: cfg.Freshness, + Topology: cfg.Topology, + Sink: sink, + Reader: boot.Publisher, + }) + // A published line changes what the observation build reads, and no + // heartbeat carries it: it wakes the build. + boot.Publisher.SetLineChangeHook(func(string) { obs.Wake() }) + // An ask built outside the controller (a heal, a planned or workspace + // move, an operator's request) is issued for the process its target + // reports now. + boot.Publisher.SetIncarnationSource(func(volumeID, replicaID, dataAddr, ctrlAddr string) string { + if f, ok := obs.Store().SlotFactAt(volumeID, replicaID, dataAddr, ctrlAddr); ok { + return f.Incarnation + } + return "" + }) + + ln, err := net.Listen("tcp", cfg.Listen) + if err != nil { + _ = boot.Close() + return nil, fmt.Errorf("master.New: listen %q: %w", cfg.Listen, err) + } + + h.boot = boot + h.obs = obs + h.ln = ln + h.lifecycle = lifecycleStores + if h.lifecycle != nil { + // Rebuild permanent grant exclusions before any request, publisher + // loop or lifecycle reconciliation can create positive validity. + for _, volume := range h.lifecycle.Deletions.CommittedVolumes() { + if err := h.Publisher().ReserveWorkspaceDeletion(context.Background(), volume, nil); err != nil { + _ = ln.Close() + _ = boot.Close() + return nil, fmt.Errorf("master.New: deletion reservation recovery: %w", err) + } + } + if err := h.reconcileWorkspaceBindings(); err != nil { + _ = ln.Close() + _ = boot.Close() + return nil, fmt.Errorf("master.New: workspace binding recovery: %w", err) + } + } + + if cfg.FrontendPublicationRuntimeHTTP { + addr := cfg.FrontendPublicationRuntimeListen + if addr == "" { + addr = "127.0.0.1:0" + } + frontendLn, err := net.Listen("tcp", addr) + if err != nil { + _ = ln.Close() + _ = boot.Close() + return nil, fmt.Errorf("master.New: frontend publication runtime listen %q: %w", addr, err) + } + h.frontendRuntimeLn = frontendLn + h.frontendRuntimeHTTP = &http.Server{Handler: h.frontendPublicationRuntimeHandler()} + } + + if cfg.StatusListen != "" { + statusLn, err := net.Listen("tcp", cfg.StatusListen) + if err != nil { + if h.frontendRuntimeLn != nil { + _ = h.frontendRuntimeLn.Close() + } + _ = ln.Close() + _ = boot.Close() + return nil, fmt.Errorf("master.New: status listen %q: %w", cfg.StatusListen, err) + } + h.statusLn = statusLn + // Every connection phase is bounded: a client that withholds a + // declared body or never reads the reply is cut off. + h.statusHTTP = &http.Server{Handler: h.statusHandler(), ReadHeaderTimeout: statusReadTimeout, ReadTimeout: statusReadTimeout, + WriteTimeout: statusWriteTimeout, IdleTimeout: statusIdleTimeout} + } + + grpcSrv := link.NewServer(serverAuth(cfg.Auth), cfg.ServerOptions...) + svc := newServices(h) + control.RegisterObservationServiceServer(grpcSrv, svc) + control.RegisterAssignmentServiceServer(grpcSrv, svc) + control.RegisterEvidenceServiceServer(grpcSrv, svc) + control.RegisterClusterEvidenceServiceServer(grpcSrv, svc) + control.RegisterLifecycleServiceServer(grpcSrv, svc) + control.RegisterFailbackServiceServer(grpcSrv, svc) + control.RegisterWorkspaceServiceServer(grpcSrv, svc) + h.grpc = grpcSrv + + lg.Printf("blockmaster: lock acquired, reloaded=%d, listen=%s", + boot.ReloadedRecords, ln.Addr().String()) + if h.frontendRuntimeLn != nil { + lg.Printf("blockmaster: frontend publication runtime listen=%s", h.frontendRuntimeLn.Addr().String()) + } + if h.statusLn != nil { + lg.Printf("blockmaster: status listen=%s", h.statusLn.Addr().String()) + } + if cfg.StrictJournalIsolation { + lg.Printf("blockmaster: strict journal isolation: nodes sharing the authority store's file system are refused new work") + } + for _, e := range boot.ReloadSkips { + lg.Printf("blockmaster: reload skip: %v", e) + } + return h, nil +} + +func openLifecycleStores(dir string) (*LifecycleStores, error) { + if dir == "" { + return nil, nil + } + volumes, err := lifecycle.OpenFileStore(filepath.Join(dir, "volumes")) + if err != nil { + return nil, err + } + nodes, err := lifecycle.OpenNodeInventoryStore(filepath.Join(dir, "nodes")) + if err != nil { + return nil, err + } + placements, err := lifecycle.OpenPlacementIntentStore(filepath.Join(dir, "placements")) + if err != nil { + return nil, err + } + bindings, err := lifecycle.OpenWorkspaceBindingStore(filepath.Join(dir, "workspace-bindings")) + if err != nil { + return nil, err + } + deletions, err := lifecycle.OpenDeletionReservationStore(filepath.Join(dir, "deletion-reservations")) + if err != nil { + return nil, err + } + return &LifecycleStores{ + Volumes: volumes, + Nodes: nodes, + Placements: placements, + WorkspaceBindings: bindings, + Deletions: deletions, + }, nil +} + +// Addr returns the bound listener address. Valid after New. +func (h *Host) Addr() string { return h.ln.Addr().String() } + +// FrontendPublicationRuntimeAddr returns the bound frontend publication +// runtime HTTP address, or empty when the runtime is disabled. +func (h *Host) FrontendPublicationRuntimeAddr() string { + if h.frontendRuntimeLn == nil { + return "" + } + return h.frontendRuntimeLn.Addr().String() +} + +// StatusAddr returns the bound status HTTP address, or empty when the status +// endpoint is disabled. +func (h *Host) StatusAddr() string { + if h.statusLn == nil { + return "" + } + return h.statusLn.Addr().String() +} + +// Publisher exposes the reloaded publisher for tests and for the +// evidence-query path. +func (h *Host) Publisher() *authority.Publisher { + if h == nil || h.boot == nil { + return nil + } + return h.boot.Publisher +} + +// FailbackAuthorityRuntime exposes the authority-owned failback seam backed by +// the live Publisher. Callers still need an explicit policy gate before using +// it; constructing the runtime does not execute failback. +func (h *Host) FailbackAuthorityRuntime() authority.FailbackAuthorityRuntime { + return authority.FailbackAuthorityRuntime{Publisher: h.Publisher(), Gate: h.plannedMoveEvidenceAt, TargetEndpoint: h.replicaEndpoint} +} + +// replicaEndpoint is the master's own record of a replica's addresses: its +// fresh heartbeat slot (what the automatic path publishes), else its +// placement slot when that names both. +func (h *Host) replicaEndpoint(volumeID, replicaID string) (string, string, bool) { + if s, ok := h.freshCurrentSlot(volumeID, replicaID); ok && s.DataAddr != "" && s.CtrlAddr != "" { + return s.DataAddr, s.CtrlAddr, true + } + if h.lifecycle != nil { + if p, ok := h.lifecycle.Placements.GetPlacement(volumeID); ok { + for _, s := range p.Slots { + if s.ReplicaID == replicaID && s.DataAddr != "" && s.CtrlAddr != "" { + return s.DataAddr, s.CtrlAddr, true + } + } + } + } + return "", "", false +} + +// Controller exposes the controller for tests. +func (h *Host) Controller() *authority.TopologyController { return h.ctrl } + +// ObservationHost exposes the observation host for tests. +func (h *Host) ObservationHost() *authority.ObservationHost { return h.obs } + +// Lifecycle returns product registration stores when configured. Nil means +// the daemon is running in static-topology-only mode. Reading these stores +// must not be treated as assignment authority. +func (h *Host) Lifecycle() *LifecycleStores { return h.lifecycle } + +// replicaSlotsFor returns replica IDs for a volume. Static topology +// remains the allow-list. Dynamic lifecycle volumes may not persist +// placement slots in the lifecycle record, so read-only status paths +// merge fresh observed slots from the observation store; assignment +// authority still comes from the publisher/controller, not this helper. +func (h *Host) replicaSlotsFor(volumeID string) []string { + for _, v := range h.topo.Volumes { + if v.VolumeID != volumeID { + continue + } + out := make([]string, 0, len(v.Slots)) + for _, s := range v.Slots { + out = append(out, s.ReplicaID) + } + return out + } + var out []string + if h.lifecycle != nil && h.lifecycle.Placements != nil { + if placement, ok := h.lifecycle.Placements.GetPlacement(volumeID); ok { + for _, slot := range placement.Slots { + if slot.ReplicaID != "" { + out = appendReplicaID(out, slot.ReplicaID) + } + } + } + } + if h.lifecycle != nil && h.obs != nil { + for _, replicaID := range h.obs.Store().ReplicaIDsForVolume(volumeID) { + out = appendReplicaID(out, replicaID) + } + } + if len(out) == 0 { + return nil + } + return out +} + +func appendReplicaID(in []string, replicaID string) []string { + for _, existing := range in { + if existing == replicaID { + return in + } + } + return append(in, replicaID) +} + +// Start runs the publisher, observation rebuild loop, and gRPC +// server. Returns a context that is cancelled on Close so callers +// can wait on it from their own goroutines. Idempotent — second +// Start() returns the prior ctx. +func (h *Host) Start() context.Context { + if !h.started.CompareAndSwap(false, true) { + return nil + } + ctx, cancel := context.WithCancel(context.Background()) + h.cancel = cancel + + h.wg.Add(1) + go func() { + defer h.wg.Done() + _ = h.boot.Publisher.Run(ctx) + }() + + h.obs.Start(ctx) + + h.wg.Add(1) + go func() { + defer h.wg.Done() + if err := h.grpc.Serve(h.ln); err != nil && err != grpc.ErrServerStopped { + h.log.Printf("blockmaster: grpc.Serve: %v", err) + } + }() + + if h.frontendRuntimeHTTP != nil && h.frontendRuntimeLn != nil { + h.wg.Add(1) + go func() { + defer h.wg.Done() + if err := h.frontendRuntimeHTTP.Serve(h.frontendRuntimeLn); err != nil && err != http.ErrServerClosed { + h.log.Printf("blockmaster: frontend publication runtime Serve: %v", err) + } + }() + } + + if h.statusHTTP != nil && h.statusLn != nil { + h.wg.Add(1) + go func() { + defer h.wg.Done() + if err := h.statusHTTP.Serve(h.statusLn); err != nil && err != http.ErrServerClosed { + h.log.Printf("blockmaster: status Serve: %v", err) + } + }() + } + + return ctx +} + +// Close stops the gRPC server, cancels live loops, and releases +// the durable store lock. Idempotent. +func (h *Host) Close(ctx context.Context) error { + if h.cancel != nil { + h.cancel() + } + if h.frontendRuntimeHTTP != nil { + _ = h.frontendRuntimeHTTP.Shutdown(ctx) + } + var statusErr error + if h.statusHTTP != nil { + statusErr = h.closeStatusHTTP(ctx) + } + h.obs.Stop() + + done := make(chan struct{}) + go func() { + h.grpc.GracefulStop() + close(done) + }() + select { + case <-done: + case <-ctx.Done(): + h.grpc.Stop() + } + + h.wg.Wait() + // Level 0's horizon extenders write through the store: join them first. + h.boot.Publisher.CloseWorkspaceExtenders() + return errors.Join(statusErr, h.boot.Close()) +} + +// Status endpoint connection bounds. +const ( + statusReadTimeout = 5 * time.Second + statusWriteTimeout = 5 * time.Second + statusIdleTimeout = 30 * time.Second +) + +// closeStatusHTTP shuts the status endpoint down gracefully until ctx ends, +// then force-closes the connections still open (Shutdown leaves them). It +// returns the force close's error, if any; an expired graceful shutdown that +// the force close completed is only logged. +func (h *Host) closeStatusHTTP(ctx context.Context) error { + defer h.statusLn.Close() // a listener Start never served is not Shutdown's + err := h.statusHTTP.Shutdown(ctx) + if err == nil { + return nil + } + h.log.Printf("blockmaster: status graceful shutdown: %v; closing its open connections", err) + if cerr := h.statusHTTP.Close(); cerr != nil && !errors.Is(cerr, net.ErrClosed) { + return fmt.Errorf("status endpoint close: %w", cerr) + } + return nil +} diff --git a/seaweed-block/core/host/master/observation_snapshot.go b/seaweed-block/core/host/master/observation_snapshot.go index ee16b9ca8b..e3ec00bbad 100644 --- a/seaweed-block/core/host/master/observation_snapshot.go +++ b/seaweed-block/core/host/master/observation_snapshot.go @@ -28,7 +28,7 @@ func (h *Host) ObservationSnapshot(now time.Time) ops.ClusterEvidence { cluster.Nodes = observationNodes(snapshot.Nodes, snapshot.Placements) cluster.Volumes = h.observationVolumes(snapshot) - waits := h.grantWaits(snapshot.Placements, now) + waits := h.grantWaits(now) for i := range cluster.Nodes { node := cluster.Nodes[i].NodeName nodeWaits := waits[node] From 18ffa85a4002fd10a4c7979460fc55ff481cf1a1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 05:40:59 -0800 Subject: [PATCH 7/8] Regenerate status schema for the pending-work skip reason --- seaweed-block/docs/status-schema.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index a811e5245b..1e40cb8403 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -240,7 +240,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Maintenance.inProgress` | bool | a maintenance callback is running | | `Volumes[].Chunk.Maintenance.currentStartNs` | int64 | unix ns start of the running pass; zero when idle | | `Volumes[].Chunk.Maintenance.lastPass` | object | absent until a pass ends (omitted when empty) | -| `Volumes[].Chunk.Maintenance.lastPass.skipReason` | string | omitted normally; `newer_pending_work` means list-page retirement is conservatively skipped while reserved `lists` remain; serving and the pass outcome are unchanged | +| `Volumes[].Chunk.Maintenance.lastPass.skipReason` | ListRetirementSkipReason (string) | conservative list-page retirement skip; never changes serving or the pass outcome (omitted when empty) | | `Volumes[].Chunk.Maintenance.lastPass.atNs` | int64 | unix ns when the pass ended | | `Volumes[].Chunk.Maintenance.lastPass.planned` | int64 | all objects considered for removal | | `Volumes[].Chunk.Maintenance.lastPass.removed` | int64 | all objects removed | From 492a56f2798e01b78bad625b978bb94187c899c3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 05:45:02 -0800 Subject: [PATCH 8/8] master: the held-old/new snapshot control holds only the older snapshot A non-blocking one-shot guard holds snapshot A alone (B passes the hook without blocking, so a read outside the lock lets B finish during A's hold), the newer wait's first-seen time is pinned to B's, and A's completion and B's join are bounded. Co-Authored-By: Claude Opus 5.5 --- .../master/format_level_new_cluster_test.go | 58 +++++++++++++------ 1 file changed, 39 insertions(+), 19 deletions(-) diff --git a/seaweed-block/core/host/master/format_level_new_cluster_test.go b/seaweed-block/core/host/master/format_level_new_cluster_test.go index ab11db303f..e2cd395baa 100644 --- a/seaweed-block/core/host/master/format_level_new_cluster_test.go +++ b/seaweed-block/core/host/master/format_level_new_cluster_test.go @@ -5,7 +5,7 @@ import ( "os" "path/filepath" "strings" - "sync" + "sync/atomic" "testing" "time" @@ -300,40 +300,60 @@ func TestGrantWaitsAreReconciledPerServerAndVolume(t *testing.T) { // A status snapshot that read the placements before a newer one never // reconciles after it: snapshot A holds its read (no placement yet) while -// vb is placed on an unreported node and snapshot B is started; B waits for -// A, then starts vb's wait, and the wait stays. +// vb is placed on an unreported node and snapshot B is started; B must wait +// for A (the hook lets B through without blocking: only A is held), then +// starts vb's wait at its own time, and that wait stays. Every wait is +// bounded. func TestAnOlderStatusSnapshotNeverDropsANewerOnesWait(t *testing.T) { r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) if _, err := r.m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-b", DataAddr: "127.0.0.1:19351", CtrlAddr: "127.0.0.1:19352"}); err != nil { t.Fatal(err) } r.createVolume(t, "vb") - now := time.Now() - var once sync.Once - bDone := make(chan struct{}) + nowA := time.Now() + nowB := nowA.Add(time.Second) + var armed atomic.Bool + armed.Store(true) + aDone, bDone := make(chan struct{}), make(chan struct{}) bRanDuringA := false r.m.testGrantWaitsRead = func() { - once.Do(func() { - r.place(t, "vb", "node-b") - go func() { r.m.ObservationSnapshot(now); close(bDone) }() - select { - case <-bDone: - bRanDuringA = true - case <-time.After(300 * time.Millisecond): - } - }) + if !armed.CompareAndSwap(true, false) { + return // B, or any later snapshot: not held + } + r.place(t, "vb", "node-b") + go func() { r.m.ObservationSnapshot(nowB); close(bDone) }() + select { + case <-bDone: + bRanDuringA = true + case <-time.After(300 * time.Millisecond): + } + } + go func() { r.m.ObservationSnapshot(nowA); close(aDone) }() // A: read before vb was placed + for name, done := range map[string]chan struct{}{"A": aDone, "B": bDone} { + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatalf("snapshot %s did not finish", name) + } } - r.m.ObservationSnapshot(now) // A: read before vb was placed - <-bDone r.m.testGrantWaitsRead = nil if bRanDuringA { t.Fatal("snapshot B reconciled while snapshot A held its older read") } - if !r.m.grantWaitKept("node-b\x00vb") { - t.Fatal("vb's wait, started by the newer snapshot, was dropped by the older one") + first, kept := r.m.grantWaitFirst("node-b\x00vb") + if !kept || !first.Equal(nowB) { + t.Fatalf("vb's wait: first seen %v (kept %v), want %v (started by the newer snapshot, not dropped by the older one)", first, kept, nowB) } } +// grantWaitFirst is the first-seen time the master holds for key. +func (h *Host) grantWaitFirst(key string) (time.Time, bool) { + h.grantWaitMu.Lock() + defer h.grantWaitMu.Unlock() + first, ok := h.grantWait[key] + return first, ok +} + // grantWaitKept reports whether the master holds a first-seen time for key. func (h *Host) grantWaitKept(key string) bool { h.grantWaitMu.Lock()