From 7e92532357efb39fbb2c2632d2cd1f8e8d7a64f6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 17:31:14 -0800 Subject: [PATCH 1/3] layout: a holder's start applies the local-root rules Start is the HEAD side of a holder starting on its granted line with the claim id its local root's marker carries. At HEAD's epoch and server it continues only on the root whose claim id HEAD holds (its own restart, or a claim whose reply was lost); a fresh root with another claim id is refused as a missing local root, naming the likely cause and the way back (a forced move, also to the same host); an older root with another claim id is refused as stale and fenced; neither writes HEAD. At a higher epoch it claims with its local claim id. The package guard makes Start the only caller of the claim; the HEAD reader enumeration classifies its read. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/head_readers_test.go | 11 ++ .../frontend/chunkstore/layout/guard_test.go | 8 ++ .../frontend/chunkstore/layout/stale_test.go | 5 +- .../core/frontend/chunkstore/layout/start.go | 61 ++++++++++ .../frontend/chunkstore/layout/start_test.go | 113 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 4 +- 6 files changed, 200 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/start.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/start_test.go diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index dacb9c1b35..9c121deeb4 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -41,6 +41,7 @@ var headReaders = map[string]string{ "core/frontend/chunkstore/usage.go Usage -> ReadHead": "GAP: reports an empty image, no error (probe Usage)", "core/frontend/chunkstore/verify.go readHead -> LookupEntry": "finding ROOT_INVALID (probe Verify)", "core/frontend/chunkstore/layout/delete.go OperatorReleaseDependent -> ReadHead": "reads the source's HEAD (absent: refuses ErrHeadAbsent) and the target's: a target with no HEAD and no VOLUME was never created and is refused, one with VOLUME and no HEAD is being created and is refused; nothing is written (probe LayoutOperatorRelease)", + "core/frontend/chunkstore/layout/start.go Start -> ReadHead": "refuses ErrHeadAbsent and creates nothing (probe LayoutStart)", "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and deletes nothing (probe LayoutRemoval)", "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", "core/frontend/chunkstore/verify.go run -> LookupEntry": "finding ROOT_INVALID (probe Verify)", @@ -306,6 +307,12 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { t.Fatalf("operator release with the source HEAD absent: %v; want ErrHeadAbsent", err) } }) + t.Run("LayoutStart", func(t *testing.T) { + st := &absentLayoutHead{} + if _, err := layout.Start(ctx, st, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "h"}, layout.LocalRoot{ClaimID: "k", Fresh: true}); !errors.Is(err, layout.ErrHeadAbsent) || st.updates != 0 { + t.Fatalf("start over an absent HEAD: %v, %d writes; want ErrHeadAbsent and none", err, st.updates) + } + }) t.Run("ForkReplay", func(t *testing.T) { f, b := headReaderForkFixture(t) c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) @@ -361,3 +368,7 @@ func (p *presentLayoutHead) UpdateHead(context.Context, uint64, layout.Head) err p.updates++ return nil } + +type okClaimLease struct{} + +func (okClaimLease) OldLeaseEnded(context.Context, uint64) error { return nil } diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index aaa2f1e556..3721b54530 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -123,6 +123,8 @@ func owners(m map[string]bool) []string { // - Lease, claim half: OldLeaseEnded is used only in RunClaim, and // RunClaim, when it is declared, uses it. // - Every declared exported Run function goes through runTransition. +// - Claim: RunClaim is used only by Start, which applies the local-root +// rules (own epoch: continue only on HEAD's claim id) before claiming. // - Release of a dependent: RunReleaseDependent is used only by // DeleteVolume (its own HEAD is deleting) and OperatorReleaseDependent, // which reads the target's HEAD before it releases. @@ -171,6 +173,11 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) bad = append(bad, fn+" is declared and does not go through runTransition") } } + for _, fn := range owners(code["RunClaim"]) { + if fn != "Start" { + bad = append(bad, fn+" uses RunClaim: a claim is made only by Start, which first applies the local-root rules") + } + } for _, fn := range owners(code["RunReleaseDependent"]) { if fn != "DeleteVolume" && fn != "OperatorReleaseDependent" { bad = append(bad, fn+" uses RunReleaseDependent: only DeleteVolume (target deleting) and OperatorReleaseDependent (target checked) release") @@ -474,6 +481,7 @@ func DeleteVolume(ctx context.Context, st HeadStore, id VolumeID, srcs []HeadSto "ignored lease check": {file: "remove.go", src: removeVariant(t, "ignored"), want: "without a lease gate immediately before it"}, "one check, two deletes": {file: "remove.go", src: removeVariant(t, "second"), want: "without a lease gate immediately before it"}, "unlisted removal method": {file: "remove.go", src: removeVariant(t, "other"), want: "without a lease gate immediately before it"}, + "claim outside Start": {src: `func w(ctx context.Context, st HeadStore, l LeaseWait, me HolderID) { _, _ = RunClaim(ctx, st, l, me) }`, want: "a claim is made only by Start"}, "remover method value": {src: `type p interface{ RemoveName(string) } func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable (after its lease re-check) and DeleteVolume"}, } { diff --git a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go index 462195cd01..bfef09c8e5 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go @@ -81,7 +81,10 @@ func TestHolderFunctions_RefuseAStaleHolder(t *testing.T) { t.Errorf("RemoveUnreachable by %s: %v, %d deletes; want ErrNotHolder and none", who, err, len(o.deletes)) } } - covered := map[string]bool{"RemoveUnreachable": true} + // Start: an older line, another server at HEAD's epoch and another claim + // id are its cases in start_test.go (TestStart_Refusals and the same-host + // forced successor). + covered := map[string]bool{"RemoveUnreachable": true, "Start": true} var missing []string for fname, src := range packageSources(t, false) { file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0) diff --git a/seaweed-block/core/frontend/chunkstore/layout/start.go b/seaweed-block/core/frontend/chunkstore/layout/start.go new file mode 100644 index 0000000000..3284007244 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/start.go @@ -0,0 +1,61 @@ +package layout + +import ( + "context" + "errors" + "fmt" +) + +var ( + // ErrMissingLocalRoot: the holder starts at its own epoch on a fresh + // local root; it cannot prove it holds what it acknowledged. + ErrMissingLocalRoot = errors.New("layout: local root missing at the holder's own epoch") + // ErrStaleLocalRoot: the local root belongs to an earlier claim of this + // server (a same-host forced move published past it). + ErrStaleLocalRoot = errors.New("layout: local root is from an earlier claim") +) + +// MissingLocalRootCure is the way back the refusal names. +const MissingLocalRootCure = "check for a wrong or unmounted data directory; if the local data is gone, a forced move (also to the same host) records the lost range and restarts from the published image" + +// LocalRoot is what a starting holder knows of its local data: the claim +// id its local root's marker carries, and whether the root is fresh (just +// created, holding no data). +type LocalRoot struct { + ClaimID string + Fresh bool +} + +// Start is the HEAD side of a holder's start on the line it was granted +// (epoch, server), with the claim id of its local root. At HEAD's epoch +// and server, the local root whose claim id HEAD holds continues (its own +// restart, or a claim whose reply was lost); a fresh root with another +// claim id is ErrMissingLocalRoot, an older root with another claim id is +// ErrStaleLocalRoot (fenced); neither writes HEAD. At a higher epoch the +// holder claims with its local claim id (RunClaim, which waits for the old +// lease). An older epoch, another server at HEAD's epoch, a deleting +// volume and an absent HEAD are refused. +func Start(ctx context.Context, st HeadStore, lease LeaseWait, line HolderID, local LocalRoot) (Head, error) { + if local.ClaimID == "" { + return Head{}, errors.New("layout: start needs the local root's claim id") + } + h, found, err := st.ReadHead(ctx) + if err != nil { + return Head{}, err + } + if !found { + return Head{}, ErrHeadAbsent + } + me := HolderID{Epoch: line.Epoch, Holder: line.Holder, ClaimID: local.ClaimID} + if h.Epoch == line.Epoch && h.Holder == line.Holder && h.State == StateLive { + switch { + case h.ClaimID == local.ClaimID: + return h, nil + case local.Fresh: + return Head{}, fmt.Errorf("%w at epoch %d: %s", ErrMissingLocalRoot, h.Epoch, MissingLocalRootCure) + default: + return Head{}, fmt.Errorf("%w (%w): HEAD holds claim %q at epoch %d, the local root carries %q", ErrStaleLocalRoot, ErrNotHolder, h.ClaimID, h.Epoch, local.ClaimID) + } + } + return RunClaim(ctx, st, lease, me) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/start_test.go b/seaweed-block/core/frontend/chunkstore/layout/start_test.go new file mode 100644 index 0000000000..ef5269b597 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/start_test.go @@ -0,0 +1,113 @@ +package layout + +import ( + "context" + "errors" + "strings" + "testing" +) + +// The start rules, carried from the store-independent tests of the same +// rule on the current store: a holder's local data is identified by the +// claim id its local root's marker carries, together with the epoch. + +func startHead(epoch uint64, holder, claim string) Head { + return Head{Gen: 7, VolumeID: idFor("v1"), Epoch: epoch, Holder: holder, ClaimID: claim, Activity: Activity{Kind: ActIdle}} +} + +func start(t *testing.T, h Head, line HolderID, local LocalRoot) (*memHead, Head, error) { + t.Helper() + st := &memHead{h: &h} + got, err := Start(context.Background(), st, &fakeLease{ended: true}, line, local) + return st, got, err +} + +// A fresh local root at the holder's own epoch cannot prove it holds the +// acknowledged suffix: refused before any claim, with the likely cause and +// the way back, HEAD unchanged; a retry on the same (still fresh) root is +// refused too. +func TestStart_OwnEpochFreshRootRefusedBeforeClaim(t *testing.T) { + h := startHead(3, "s1/r1", "k-old") + line := HolderID{Epoch: 3, Holder: "s1/r1"} + fresh := LocalRoot{ClaimID: "k-new", Fresh: true} + st, _, err := start(t, h, line, fresh) + if !errors.Is(err, ErrMissingLocalRoot) { + t.Fatalf("own-epoch fresh root: %v; want ErrMissingLocalRoot", err) + } + for _, words := range []string{"wrong or unmounted data directory", "forced move (also to the same host)"} { + if !strings.Contains(err.Error(), words) { + t.Fatalf("refusal %q lacks %q", err, words) + } + } + if st.updates != 0 || st.h.ClaimID != "k-old" || st.h.Epoch != 3 { + t.Fatalf("refused start changed HEAD: %+v (%d writes)", st.h, st.updates) + } + if _, err := Start(context.Background(), st, &fakeLease{ended: true}, line, fresh); !errors.Is(err, ErrMissingLocalRoot) || st.updates != 0 { + t.Fatalf("retry on the same fresh root: %v (%d writes)", err, st.updates) + } +} + +// The same root restarting at its own epoch continues: its marker is the +// claim id HEAD holds. No claim is written. +func TestStart_OwnEpochSameRootContinues(t *testing.T) { + st, got, err := start(t, startHead(3, "s1/r1", "k3"), HolderID{Epoch: 3, Holder: "s1/r1"}, LocalRoot{ClaimID: "k3"}) + if err != nil || st.updates != 0 || got.ClaimID != "k3" { + t.Fatalf("same-root restart: %+v %v (%d writes); want continue without a write", got, err, st.updates) + } +} + +// A fresh root whose claim was written but whose reply was lost restarts +// with the same marker: HEAD holds that claim id at this epoch, so it +// continues. +func TestStart_LostClaimReplyContinues(t *testing.T) { + st, got, err := start(t, startHead(5, "s1/r1", "k5"), HolderID{Epoch: 5, Holder: "s1/r1"}, LocalRoot{ClaimID: "k5", Fresh: true}) + if err != nil || st.updates != 0 || got.Epoch != 5 { + t.Fatalf("restart after a lost claim reply: %+v %v (%d writes)", got, err, st.updates) + } +} + +// After a same-host forced move the successor (epoch 4, its own claim id) +// holds HEAD; the old root (claim id of epoch 3, with a long unpublished +// suffix) remounted under epoch 4 is refused as stale and fenced; HEAD and +// its image are unchanged. +func TestStart_SameHostForcedSuccessorRefusesTheRemountedOldRoot(t *testing.T) { + rn := RootName{Hash: Sum([]byte("successor image"))} + h := startHead(4, "s1/r1", "k4") + h.Current = &rn + st, _, err := start(t, h, HolderID{Epoch: 4, Holder: "s1/r1"}, LocalRoot{ClaimID: "k3"}) + if !errors.Is(err, ErrStaleLocalRoot) || !errors.Is(err, ErrNotHolder) { + t.Fatalf("remounted old root: %v; want ErrStaleLocalRoot and fenced (ErrNotHolder)", err) + } + if st.updates != 0 || st.h.ClaimID != "k4" || *st.h.Current != rn { + t.Fatalf("refused start changed HEAD: %+v", st.h) + } +} + +// A fresh root at a higher issued epoch, on the same server or another, +// claims with its marker's claim id. +func TestStart_FreshRootAtHigherEpochClaims(t *testing.T) { + for _, server := range []string{"s1/r1", "s2/r1"} { + st, got, err := start(t, startHead(3, "s1/r1", "k3"), HolderID{Epoch: 4, Holder: server}, LocalRoot{ClaimID: "k4", Fresh: true}) + if err != nil || st.updates != 1 || got.Epoch != 4 || got.Holder != server || got.ClaimID != "k4" { + t.Fatalf("fresh root at epoch 4 on %s: %+v %v (%d writes)", server, got, err, st.updates) + } + } +} + +// An older line is fenced; the same epoch held by another server is not +// this holder's; an absent HEAD is refused (nothing is created). +func TestStart_Refusals(t *testing.T) { + if _, _, err := start(t, startHead(4, "s1/r1", "k4"), HolderID{Epoch: 3, Holder: "s1/r1"}, LocalRoot{ClaimID: "k3"}); !errors.Is(err, ErrStaleEpoch) { + t.Errorf("older line: %v; want ErrStaleEpoch", err) + } + if _, _, err := start(t, startHead(4, "s1/r1", "k4"), HolderID{Epoch: 4, Holder: "s2/r1"}, LocalRoot{ClaimID: "k9", Fresh: true}); !errors.Is(err, ErrNotHolder) { + t.Errorf("same epoch, another server: %v; want ErrNotHolder", err) + } + st := &memHead{} + if _, err := Start(context.Background(), st, &fakeLease{ended: true}, HolderID{Epoch: 1, Holder: "s1/r1"}, LocalRoot{ClaimID: "k1", Fresh: true}); !errors.Is(err, ErrHeadAbsent) || st.updates != 0 { + t.Errorf("absent HEAD: %v", err) + } + if _, _, err := start(t, startHead(3, "s1/r1", "k3"), HolderID{Epoch: 4, Holder: "s1/r1"}, LocalRoot{}); err == nil { + t.Error("start without a local claim id accepted") + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 96b93e2937..7e95352ad1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -549,7 +549,7 @@ stateDiagram-v2 ## Part B. Invariant ledger -353 rows: 282 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 338 new. +355 rows: 284 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 340 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -1113,6 +1113,8 @@ Notes: | `INV-SNAPK-RELEASE-CALLERS-001` | Only the target's own delete (its HEAD already deleting) and the operator's command release a dependent; a source scan restricts the callers and requires the operator's read of the target. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-OPERATOR-001` | The operator's command releases only a target that exists and is deleted (HEAD deleting or deleted, or its name holding another volume id) or whose live roots name no chunk of the source. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-REFUSE-001` | The operator's command refuses a live target still naming the source, a target being created and a target never created, and then writes nothing to the source. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-START-ROOT-001` | At its own epoch a holder continues only on the local root whose claim id HEAD holds; a fresh root with another id is refused as a missing local root naming the cure, an older one as stale and fenced; neither writes HEAD. | M9 start (before any transition) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues`, `TestStart_LostClaimReplyContinues`, `TestStart_SameHostForcedSuccessorRefusesTheRemountedOldRoot` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-START-CLAIM-001` | A claim is made only by Start, at an epoch above HEAD's, with the local root's claim id; a source scan refuses any other caller of RunClaim. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `start.go` `Start`; (source scan) | `TestStart_FreshRootAtHigherEpochClaims`, `TestStart_Refusals`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server, the same epoch held by another server, and the same epoch and server with another claim id, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | Notes: From df93d2141dd608daa60b5d0a32d521709b4797e1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 17:37:01 -0800 Subject: [PATCH 2/3] layout: start refuses another lineage at any epoch and old copies At an epoch above HEAD's a holder now claims only with a fresh root (it restores from HEAD) or the root whose claim id HEAD holds (the continuing lineage); any other root holds data older than HEAD's image and is refused as stale, HEAD unchanged: the directory may be the only copy of a reported lost range, and discarding it is the operator's act. A root carrying HEAD's claim id but synced below HEAD's published position is an old copy and is refused too. A start killed at its claim restarts with the same marker and continues: the claim id it writes is the one its local root already carries. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/start.go | 23 +++++-- .../frontend/chunkstore/layout/start_test.go | 69 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 6 +- 3 files changed, 90 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/start.go b/seaweed-block/core/frontend/chunkstore/layout/start.go index 3284007244..d9bef588f1 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/start.go +++ b/seaweed-block/core/frontend/chunkstore/layout/start.go @@ -19,11 +19,13 @@ var ( const MissingLocalRootCure = "check for a wrong or unmounted data directory; if the local data is gone, a forced move (also to the same host) records the lost range and restarts from the published image" // LocalRoot is what a starting holder knows of its local data: the claim -// id its local root's marker carries, and whether the root is fresh (just -// created, holding no data). +// id its local root's marker carries (written before any claim, so it is +// durable before HEAD can name it), whether the root is fresh (just +// created, holding no data), and the position it holds synced. type LocalRoot struct { - ClaimID string - Fresh bool + ClaimID string + Fresh bool + Position uint64 // the position the local root holds synced } // Start is the HEAD side of a holder's start on the line it was granted @@ -33,8 +35,11 @@ type LocalRoot struct { // claim id is ErrMissingLocalRoot, an older root with another claim id is // ErrStaleLocalRoot (fenced); neither writes HEAD. At a higher epoch the // holder claims with its local claim id (RunClaim, which waits for the old -// lease). An older epoch, another server at HEAD's epoch, a deleting -// volume and an absent HEAD are refused. +// lease) only if its root is fresh (it restores from HEAD) or carries +// HEAD's claim id (the continuing lineage); any other root holds data +// older than HEAD's image and is ErrStaleLocalRoot. An older epoch, +// another server at HEAD's epoch, a deleting volume and an absent HEAD +// are refused. func Start(ctx context.Context, st HeadStore, lease LeaseWait, line HolderID, local LocalRoot) (Head, error) { if local.ClaimID == "" { return Head{}, errors.New("layout: start needs the local root's claim id") @@ -47,6 +52,9 @@ func Start(ctx context.Context, st HeadStore, lease LeaseWait, line HolderID, lo return Head{}, ErrHeadAbsent } me := HolderID{Epoch: line.Epoch, Holder: line.Holder, ClaimID: local.ClaimID} + if !local.Fresh && local.ClaimID == h.ClaimID && local.Position < h.Position && line.Epoch >= h.Epoch { + return Head{}, fmt.Errorf("%w (%w): the local root holds position %d, HEAD published %d: an old copy of this lineage", ErrStaleLocalRoot, ErrNotHolder, local.Position, h.Position) + } if h.Epoch == line.Epoch && h.Holder == line.Holder && h.State == StateLive { switch { case h.ClaimID == local.ClaimID: @@ -57,5 +65,8 @@ func Start(ctx context.Context, st HeadStore, lease LeaseWait, line HolderID, lo return Head{}, fmt.Errorf("%w (%w): HEAD holds claim %q at epoch %d, the local root carries %q", ErrStaleLocalRoot, ErrNotHolder, h.ClaimID, h.Epoch, local.ClaimID) } } + if line.Epoch > h.Epoch && !local.Fresh && local.ClaimID != h.ClaimID { + return Head{}, fmt.Errorf("%w (%w): the local root carries claim %q, HEAD's lineage is %q; a root that is not the continuing lineage starts fresh", ErrStaleLocalRoot, ErrNotHolder, local.ClaimID, h.ClaimID) + } return RunClaim(ctx, st, lease, me) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/start_test.go b/seaweed-block/core/frontend/chunkstore/layout/start_test.go index ef5269b597..042845d340 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/start_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/start_test.go @@ -111,3 +111,72 @@ func TestStart_Refusals(t *testing.T) { t.Error("start without a local claim id accepted") } } + +// A same-host forced move put a fresh root Y at epoch 4 (claim k4, its +// image published); the old root X (claim k3, data) is remounted while the +// master grants epoch 5: X's data predates Y's image, so it is refused as +// stale and fenced, HEAD unchanged. At a higher epoch only a fresh root, or +// the root whose claim id HEAD holds (the continuing lineage), claims. +func TestStart_HigherEpochRefusesAnOlderLineage(t *testing.T) { + rn := RootName{Hash: Sum([]byte("image published at epoch 4"))} + h := startHead(4, "s1/r1", "k4") + h.Current = &rn + st, _, err := start(t, h, HolderID{Epoch: 5, Holder: "s1/r1"}, LocalRoot{ClaimID: "k3"}) + if !errors.Is(err, ErrStaleLocalRoot) || !errors.Is(err, ErrNotHolder) { + t.Fatalf("old root at a higher epoch: %v; want ErrStaleLocalRoot, fenced", err) + } + if st.updates != 0 || st.h.ClaimID != "k4" || st.h.Epoch != 4 || *st.h.Current != rn { + t.Fatalf("refused start changed HEAD: %+v (%d writes)", st.h, st.updates) + } + // The continuing lineage (the root HEAD's claim id names) claims at the + // higher epoch, keeping its data. + st2, got, err := start(t, h, HolderID{Epoch: 5, Holder: "s1/r1"}, LocalRoot{ClaimID: "k4"}) + if err != nil || st2.updates != 1 || got.Epoch != 5 || got.ClaimID != "k4" { + t.Fatalf("continuing lineage at epoch 5: %+v %v (%d writes)", got, err, st2.updates) + } +} + +// A root carrying HEAD's claim id but synced only below HEAD's published +// position is an old copy of the right directory: refused as stale, at its +// own epoch and at a higher one, HEAD unchanged. +func TestStart_OldCopyOfTheRightRootRefused(t *testing.T) { + h := startHead(4, "s1/r1", "k4") + h.Position = 100 + for _, epoch := range []uint64{4, 5} { + st, _, err := start(t, h, HolderID{Epoch: epoch, Holder: "s1/r1"}, LocalRoot{ClaimID: "k4", Position: 99}) + if !errors.Is(err, ErrStaleLocalRoot) || st.updates != 0 { + t.Fatalf("root at position 99 under HEAD at 100, epoch %d: %v (%d writes); want ErrStaleLocalRoot, no write", epoch, err, st.updates) + } + st, _, err = start(t, h, HolderID{Epoch: epoch, Holder: "s1/r1"}, LocalRoot{ClaimID: "k4", Position: 100}) + if err != nil { + t.Fatalf("root at HEAD's position, epoch %d: %v", epoch, err) + } + } +} + +// Killed at the claim's HEAD write (before it applies, and applied with +// its reply lost), the holder restarts with the same local root: the claim +// id it writes is the one its marker already carries, so the re-run either +// claims or finds its own claim and continues; it is never refused. +func TestStart_InterruptAtTheClaim(t *testing.T) { + for _, fresh := range []bool{true, false} { + local := LocalRoot{ClaimID: "k3", Fresh: fresh} + for _, after := range []bool{false, true} { + h := startHead(3, "s1/r1", "k3") + if fresh { + h = startHead(3, "s1/r1", "k-previous") + local.ClaimID = "k-fresh" + } + st := &memHead{h: &h, killAt: 1, after: after} + line := HolderID{Epoch: 4, Holder: "s1/r1"} + if _, err := Start(context.Background(), st, &fakeLease{ended: true}, line, local); !errors.Is(err, errKilled) { + t.Fatalf("killed start: %v", err) + } + st.restart() + got, err := Start(context.Background(), st, &fakeLease{ended: true}, line, local) + if err != nil || got.Epoch != 4 || got.ClaimID != local.ClaimID { + t.Fatalf("restart (fresh %t, applied %t): %+v %v; want claimed or continued at epoch 4 with %q", fresh, after, got, err, local.ClaimID) + } + } + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7e95352ad1..e25905469b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -549,7 +549,7 @@ stateDiagram-v2 ## Part B. Invariant ledger -355 rows: 284 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 340 new. +357 rows: 286 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 342 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -1114,7 +1114,9 @@ Notes: | `INV-SNAPK-RELEASE-OPERATOR-001` | The operator's command releases only a target that exists and is deleted (HEAD deleting or deleted, or its name holding another volume id) or whose live roots name no chunk of the source. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-REFUSE-001` | The operator's command refuses a live target still naming the source, a target being created and a target never created, and then writes nothing to the source. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-START-ROOT-001` | At its own epoch a holder continues only on the local root whose claim id HEAD holds; a fresh root with another id is refused as a missing local root naming the cure, an older one as stale and fenced; neither writes HEAD. | M9 start (before any transition) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues`, `TestStart_LostClaimReplyContinues`, `TestStart_SameHostForcedSuccessorRefusesTheRemountedOldRoot` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-START-CLAIM-001` | A claim is made only by Start, at an epoch above HEAD's, with the local root's claim id; a source scan refuses any other caller of RunClaim. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `start.go` `Start`; (source scan) | `TestStart_FreshRootAtHigherEpochClaims`, `TestStart_Refusals`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-START-LINEAGE-001` | At an epoch above HEAD's a holder claims only with a fresh root (it restores from HEAD) or the root whose claim id HEAD holds; any other root holds older data and is refused as stale, HEAD unchanged. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_HigherEpochRefusesAnOlderLineage`, `TestStart_FreshRootAtHigherEpochClaims` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-START-POSITION-001` | A root carrying HEAD's claim id but synced below HEAD's published position is an old copy of that lineage and is refused as stale, at its own epoch and above, HEAD unchanged. | M9 start (before any transition) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_OldCopyOfTheRightRootRefused` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-START-CLAIM-001` | A claim is made only by Start, at an epoch above HEAD's, with the local root's claim id; a source scan refuses any other caller of RunClaim. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `start.go` `Start`; (source scan) | `TestStart_FreshRootAtHigherEpochClaims`, `TestStart_Refusals`, `TestStart_InterruptAtTheClaim`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server, the same epoch held by another server, and the same epoch and server with another claim id, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | Notes: From 6e43955848eaefd6d71f6371eb1e488ed4cc607e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:47:27 -0800 Subject: [PATCH 3/3] layout: Start validates the local root against the HEAD its claim updates Start checked the local root against its first read of HEAD, then claimed through a transition that read HEAD again without the check: a claim by another lineage, or a published position rising past the local root, between the two reads was written over. The local-root check now runs again inside the claim's transition, on the very HEAD the conditional update replaces. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/claim.go | 7 ++++- .../frontend/chunkstore/layout/stale_test.go | 5 ++-- .../core/frontend/chunkstore/layout/start.go | 29 +++++++++++++++---- .../frontend/chunkstore/layout/start_test.go | 22 ++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 5 files changed, 55 insertions(+), 10 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/claim.go b/seaweed-block/core/frontend/chunkstore/layout/claim.go index 73d8e2c350..d25869363b 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/claim.go +++ b/seaweed-block/core/frontend/chunkstore/layout/claim.go @@ -48,11 +48,16 @@ func (h Head) Claim(me HolderID) (next Head, changed bool, err error) { // RunClaim reads HEAD, applies Claim, waits for the old lease's end (the // check runs after the read and before the update), and commits by one // conditional update. An absent HEAD refuses. -func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID) (Head, error) { +func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID, pre ...func(Head) error) (Head, error) { if lease == nil { return Head{}, errors.New("layout: Claim needs a lease wait") } return runTransition(ctx, st, func(h Head) (Head, bool, error) { + for _, check := range pre { + if err := check(h); err != nil { + return Head{}, false, err + } + } next, changed, err := h.Claim(me) if err != nil || !changed { return next, changed, err diff --git a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go index 3c1e09dc40..6548fff1f5 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go @@ -83,8 +83,9 @@ func TestHolderFunctions_RefuseAStaleHolder(t *testing.T) { } // Start: an older line, another server at HEAD's epoch and another claim // id are its cases in start_test.go (TestStart_Refusals and the same-host - // forced successor). - covered := map[string]bool{"RemoveUnreachable": true, "Start": true} + // forced successor); startCheck is Start's check, run again inside the + // claim (TestStart_ValidatesAgainstTheHeadItUpdates). + covered := map[string]bool{"RemoveUnreachable": true, "Start": true, "startCheck": true} var missing []string for fname, src := range packageSources(t, false) { file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0) diff --git a/seaweed-block/core/frontend/chunkstore/layout/start.go b/seaweed-block/core/frontend/chunkstore/layout/start.go index 1a00223628..f56254a4c1 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/start.go +++ b/seaweed-block/core/frontend/chunkstore/layout/start.go @@ -58,22 +58,39 @@ func Start(ctx context.Context, st HeadStore, lease LeaseWait, line HolderID, lo if !found { return Head{}, ErrHeadAbsent } + if err := startCheck(h, line, local); err != nil { + return Head{}, err + } + if h.Epoch == line.Epoch && h.Holder == line.Holder && h.State == StateLive { + return h, nil // HEAD holds this root's claim id: it continues + } + // The claim re-checks the local root against the very HEAD it updates: + // another lineage's claim or a higher published position after the + // read above refuses, never writes over the newer HEAD. me := HolderID{Epoch: line.Epoch, Holder: line.Holder, ClaimID: local.ClaimID} + return RunClaim(ctx, st, lease, me, func(h Head) error { return startCheck(h, line, local) }) +} + +// startCheck refuses a local root that cannot start on h: an old copy of +// HEAD's lineage (same claim id, position below HEAD's), at HEAD's epoch +// and server a root without HEAD's claim id, and above HEAD's epoch a +// non-fresh root of another lineage. +func startCheck(h Head, line HolderID, local LocalRoot) error { if !local.Fresh && local.ClaimID == h.ClaimID && local.Position < h.Position && line.Epoch >= h.Epoch { - return Head{}, fmt.Errorf("%w (%w): the local root holds position %d, HEAD published %d: an old copy of this lineage", ErrStaleLocalRoot, ErrNotHolder, local.Position, h.Position) + return fmt.Errorf("%w (%w): the local root holds position %d, HEAD published %d: an old copy of this lineage", ErrStaleLocalRoot, ErrNotHolder, local.Position, h.Position) } if h.Epoch == line.Epoch && h.Holder == line.Holder && h.State == StateLive { switch { case h.ClaimID == local.ClaimID: - return h, nil + return nil case local.Fresh: - return Head{}, fmt.Errorf("%w at epoch %d: %s", ErrMissingLocalRoot, h.Epoch, MissingLocalRootCure) + return fmt.Errorf("%w at epoch %d: %s", ErrMissingLocalRoot, h.Epoch, MissingLocalRootCure) default: - return Head{}, fmt.Errorf("%w (%w): HEAD holds claim %q at epoch %d, the local root carries %q: %s", ErrStaleLocalRoot, ErrNotHolder, h.ClaimID, h.Epoch, local.ClaimID, StaleLocalRootCure) + return fmt.Errorf("%w (%w): HEAD holds claim %q at epoch %d, the local root carries %q: %s", ErrStaleLocalRoot, ErrNotHolder, h.ClaimID, h.Epoch, local.ClaimID, StaleLocalRootCure) } } if line.Epoch > h.Epoch && !local.Fresh && local.ClaimID != h.ClaimID { - return Head{}, fmt.Errorf("%w (%w): the local root carries claim %q, HEAD's lineage is %q: %s", ErrStaleLocalRoot, ErrNotHolder, local.ClaimID, h.ClaimID, StaleLocalRootCure) + return fmt.Errorf("%w (%w): the local root carries claim %q, HEAD's lineage is %q: %s", ErrStaleLocalRoot, ErrNotHolder, local.ClaimID, h.ClaimID, StaleLocalRootCure) } - return RunClaim(ctx, st, lease, me) + return nil } diff --git a/seaweed-block/core/frontend/chunkstore/layout/start_test.go b/seaweed-block/core/frontend/chunkstore/layout/start_test.go index 7bfb83547a..b2c4ef8b01 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/start_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/start_test.go @@ -226,3 +226,25 @@ func TestStart_StaleRootNamesTheCure(t *testing.T) { t.Fatalf("old directory after a move away and back: %v; want ErrStaleLocalRoot naming %q", err, StaleLocalRootCure) } } + +// Start validates the local root against the very HEAD its claim updates: +// if HEAD changes after Start's first view (another lineage claims, or the +// published position rises past the local root), the claim is refused, +// never written over the newer HEAD. +func TestStart_ValidatesAgainstTheHeadItUpdates(t *testing.T) { + for name, change := range map[string]func(h *Head){ + "another lineage claims": func(h *Head) { h.Epoch, h.Holder, h.ClaimID = 4, "s2/r1", "k-other" }, + "published position rises": func(h *Head) { h.Position = 100 }, + } { + t.Run(name, func(t *testing.T) { + h := startHead(3, "s1/r1", "k3") + h.Position = 50 + st := &memHead{h: &h} + st.afterRead = func() { change(st.h) } + _, err := Start(context.Background(), st, &fakeLease{ended: true}, HolderID{Epoch: 5, Holder: "s1/r1"}, LocalRoot{ClaimID: "k3", Position: 50}) + if !errors.Is(err, ErrStaleLocalRoot) || st.updates != 0 { + t.Fatalf("start after HEAD changed under it: %v (%d writes); want ErrStaleLocalRoot, nothing written", err, st.updates) + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 8d310d99da..24e93ed552 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1120,7 +1120,7 @@ Notes: | `INV-SNAPK-RELEASE-OPERATOR-001` | The operator's command releases a target that is deleted (HEAD deleting or deleted, or its directory's VOLUME of another id), one whose live roots name no chunk of the source, or one without HEAD, after its tombstone. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-REFUSE-001` | The operator's command refuses a live target still naming the source and one whose HEAD appeared before its tombstone, and then writes nothing to the source. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-START-ROOT-001` | At its own epoch a holder continues only on the local root whose claim id HEAD holds; a fresh root with another id is refused as a missing local root naming the cure, an older one as stale and fenced; neither writes HEAD. | M9 start (before any transition) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues`, `TestStart_LostClaimReplyContinues`, `TestStart_SameHostForcedSuccessorRefusesTheRemountedOldRoot` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-START-LINEAGE-001` | At an epoch above HEAD's a holder claims only with a fresh root (it restores from HEAD) or the root whose claim id HEAD holds; any other root holds older data and is refused as stale, HEAD unchanged. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_HigherEpochRefusesAnOlderLineage`, `TestStart_FreshRootAtHigherEpochClaims`, `TestStart_StaleRootNamesTheCure`, `TestStart_DeletingVolumeRefused` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-START-LINEAGE-001` | At an epoch above HEAD's a holder claims only with a fresh root (it restores from HEAD) or the root whose claim id HEAD holds; any other root holds older data and is refused as stale, HEAD unchanged. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_HigherEpochRefusesAnOlderLineage`, `TestStart_FreshRootAtHigherEpochClaims`, `TestStart_StaleRootNamesTheCure`, `TestStart_DeletingVolumeRefused`, `TestStart_ValidatesAgainstTheHeadItUpdates` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-START-POSITION-001` | A root carrying HEAD's claim id but synced below HEAD's published position is an old copy of that lineage and is refused as stale, at its own epoch and above, HEAD unchanged. | M9 start (before any transition) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_OldCopyOfTheRightRootRefused`, `TestStart_FreshAcrossACrashContinuesTheRestore` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-START-CLAIM-001` | A claim is made only by Start, at an epoch above HEAD's, with the local root's claim id; a source scan refuses any other caller of RunClaim. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `start.go` `Start`; (source scan) | `TestStart_FreshRootAtHigherEpochClaims`, `TestStart_Refusals`, `TestStart_InterruptAtTheClaim`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server, the same epoch held by another server, and the same epoch and server with another claim id, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE |