diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index fcac948db0..85e5bd9bcf 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -172,6 +172,10 @@ type Publisher struct { leaseClosing bool extWG sync.WaitGroup extendFailures map[string]int // guarded by mu + + // testAfterIssuePublish, when set by a test, runs under mu right after + // an issued move's lease view is published. + testAfterIssuePublish func(volume string) } // PublicationAdmission surrounds an ordinary mint with local ownership/lifetime @@ -610,10 +614,14 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr } p.state[k] = assignmentState{info: next, present: true} - p.refreshLeaseViewLocked(ask.VolumeID) if issuedWorkspace != nil { // The issued move starts the new holder's lease (issuedAt+TTL grant). - p.setLeaseDeadlineLocked(ask.VolumeID, issuedAt.Add(p.workspaceTTL), false) + p.publishIssuedLeaseLocked(ask.VolumeID, issuedAt.Add(p.workspaceTTL)) + if hook := p.testAfterIssuePublish; hook != nil { + hook(ask.VolumeID) + } + } else { + p.refreshLeaseViewLocked(ask.VolumeID) } // Snapshot subscribers under lock, release the lock BEFORE diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index a1f4c1877d..b197774f0d 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -273,9 +273,11 @@ func sameWorkspaceRequest(r WorkspaceMoveRecord, q WorkspaceMoveRequest) bool { // WorkspaceForcedMoveAdmitted reports whether a forced move of volume away // from holder at epoch is admitted now: the lease expiry and the granted or // restart deadline, each plus the clock-skew margin, have passed. A caller -// reads HEAD only after this returns nil, so the HEAD a forced move checks -// can no longer be changed by a holder of that epoch's grants. The move -// itself checks admission again. A request id the journal already holds is +// reads HEAD only after this returns nil: by then the holder's own lease has +// expired, so it starts no new claim or cut. HEAD is not frozen: a claim the +// holder or an earlier one sent may still land (ownership only, RemoteLSN +// unchanged), and the next holder's higher-epoch claim supersedes it. The +// move itself checks admission again. A request id the journal already holds is // left to MoveWorkspace: its replay never uses a new HEAD. func (p *Publisher) WorkspaceForcedMoveAdmitted(ctx context.Context, volume, requestID, holder string, epoch uint64) error { if err := ctx.Err(); err != nil { @@ -317,22 +319,6 @@ func (p *Publisher) forcedMoveAdmissionLocked(volume string, lease *WorkspaceLea return lostUntil, nil } -// headUnclaimedSinceIssue reports whether h is still the HEAD the move to the -// expected holder was issued against, so that holder never claimed it (every -// HEAD write advances Gen). Only a forced move may use it: the expected -// holder's grant has expired, so it can no longer claim. -func headUnclaimedSinceIssue(s *WorkspaceState, q WorkspaceMoveRequest, h WorkspaceHead) bool { - for i := len(s.Moves) - 1; i >= 0; i-- { - r := s.Moves[i] - if !r.Issued { - continue - } - return r.NewEpoch == q.ExpectedEpoch && r.NewHost == q.ExpectedHost && r.NewReplicaID == q.ExpectedReplicaID && - h.Gen != 0 && h.Gen == r.HeadGen && h.RemoteLSN == r.RemoteLSN && h.Epoch < q.ExpectedEpoch - } - return false -} - // issueWorkspaceMove marks the move issued and starts the new holder's lease // in the same write as the new epoch, so a holder that dies before its first // renewal still leaves a lease that expires and admits a forced move. @@ -384,9 +370,12 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra } owned := h.Gen != 0 && h.Epoch == q.ExpectedEpoch && h.Holder == q.ExpectedHost+"/"+q.ExpectedReplicaID if !owned && q.Kind == "forced" { - // A holder that died between its grant and its claim left HEAD - // naming its predecessor. - owned = headUnclaimedSinceIssue(s, q, h) + // Admitted (the expected holder's lease has expired) and HEAD read + // after that: a HEAD at an older epoch means the expected holder + // never claimed it, or an earlier holder's late claim landed. The + // lost range starts at this HEAD's RemoteLSN. A HEAD at the expected + // or a higher epoch that is not the expected holder's stays refused. + owned = h.Gen != 0 && h.Epoch < q.ExpectedEpoch } if !owned { return nil, 0, time.Time{}, fmt.Errorf("workspace move: HEAD not owned by expected holder") diff --git a/seaweed-block/core/authority/workspace_issue_publish_test.go b/seaweed-block/core/authority/workspace_issue_publish_test.go new file mode 100644 index 0000000000..3c650a87dc --- /dev/null +++ b/seaweed-block/core/authority/workspace_issue_publish_test.go @@ -0,0 +1,62 @@ +package authority + +import ( + "context" + "testing" + "time" +) + +// A renewal of the new epoch that lands right after an issued move is +// published (the seam runs under the publisher lock, where only the leaf +// renewal path can run) raises the deadline; the issue must not lower it +// afterwards, or a later renewal inside that outstanding grant is refused. +func TestWorkspaceIssuePublishNeverLowersARenewedDeadline(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return now })) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen}); err != nil { + t.Fatal(err) + } + now = now.Add(100 * time.Millisecond) + issued := now + var grant WorkspaceLease + var hooked int + p.testAfterIssuePublish = func(volume string) { + hooked++ + now = issued.Add(200 * time.Millisecond) + l, err := p.RenewWorkspaceLease(ctx, volume, "r", 2) + if err != nil { + t.Errorf("renewal of the new epoch at the issue publication: %v", err) + return + } + grant = l + } + req := WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} + if r, err := p.MoveWorkspace(ctx, req, predecessorHead); err != nil || r.NewEpoch != 2 { + t.Fatal("clean move:", r, err) + } + p.testAfterIssuePublish = nil + if hooked != 1 || grant.Epoch != 2 || grant.ExpiresAtNS != issued.Add(200*time.Millisecond+grantTTL).UnixNano() { + t.Fatalf("seam ran %d times, grant %+v", hooked, grant) + } + if got := p.leaseDeadlineLockedForTest("v"); got.UnixNano() < grant.ExpiresAtNS { + t.Fatalf("the issue lowered the deadline to %s below the outstanding grant %s", got, time.Unix(0, grant.ExpiresAtNS)) + } + // Past issue+TTL but inside the outstanding grant: the holder still renews. + now = issued.Add(grantTTL + 50*time.Millisecond) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { + t.Fatal("renewal inside the outstanding grant:", err) + } + assertLeaseViewMatches(t, p, "after issue and renewal") + p.CloseWorkspaceExtenders() +} diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index d6b57dcab9..758c86766b 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -68,6 +68,25 @@ func (p *Publisher) refreshLeaseViewLocked(volume string) { lv.d = d } +// publishIssuedLeaseLocked publishes an issued move's derived view (the new +// epoch and the new holder's lease) and that lease's initial deadline in one +// leaseMu section: a renewal of the new epoch sees both or neither, so the +// issue never lowers a deadline a renewal has raised. Caller holds p.mu. +func (p *Publisher) publishIssuedLeaseLocked(volume string, deadline time.Time) { + d := p.deriveLeaseLocked(volume) + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + lv := p.leaseViews[volume] + if lv == nil { + lv = &leaseView{} + p.leaseViews[volume] = lv + } + lv.d = d + if deadline.After(lv.deadline) { + lv.deadline = deadline + } +} + // leaseDeadlineLocked reads the granted deadline. Caller holds p.mu. func (p *Publisher) leaseDeadlineLocked(volume string) time.Time { p.leaseMu.Lock() @@ -78,8 +97,7 @@ func (p *Publisher) leaseDeadlineLocked(volume string) time.Time { return time.Time{} } -// setLeaseDeadlineLocked replaces the deadline (restart rule, move issue: the -// new holder's lease starts with the grant issue+TTL) or, +// setLeaseDeadlineLocked replaces the deadline (restart rule) or, // with raise, raises it to at least t (a grant). Caller holds p.mu. func (p *Publisher) setLeaseDeadlineLocked(volume string, t time.Time, raise bool) { d := p.deriveLeaseLocked(volume) diff --git a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go index e2b88b87f7..d57b36760e 100644 --- a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go +++ b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go @@ -129,9 +129,11 @@ func TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry(t *testing.T) { } } -// The HEAD rule: a forced move from a grantee that never claimed HEAD accepts -// the predecessor's HEAD only when it is unchanged since the issue (same Gen -// and RemoteLSN, an older epoch). Clean moves never accept it. +// The HEAD rule: after admission, a forced move from a grantee that never +// claimed HEAD accepts any HEAD at an older epoch (its Gen and RemoteLSN may +// have moved, e.g. by an earlier holder's late claim); the lost range starts +// at that HEAD's RemoteLSN. A HEAD at the expected or a higher epoch that is +// not the grantee's, or no HEAD, is refused. Clean moves never accept it. func TestWorkspaceUnclaimedGrantHEADRule(t *testing.T) { ctx := context.Background() disk, _ := newTempStore(t) @@ -153,20 +155,16 @@ func TestWorkspaceUnclaimedGrantHEADRule(t *testing.T) { } now = issued.Add(10 * grantTTL) - changed := map[string]WorkspaceHead{} + refused := map[string]WorkspaceHead{} h := predecessorHead - h.Gen++ - changed["gen advanced"] = h - h = predecessorHead - h.RemoteLSN++ - changed["remote LSN differs"] = h - h = predecessorHead h.Epoch = 2 - changed["epoch not older"] = h + refused["expected epoch, another holder"] = h + h = WorkspaceHead{Gen: 9, Epoch: 3, Holder: "third-node/r", RemoteLSN: 50} + refused["epoch above expected"] = h h = predecessorHead h.Gen = 0 - changed["no HEAD"] = h - for what, h := range changed { + refused["no HEAD"] = h + for what, h := range refused { if _, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced-"+what), h); err == nil || !strings.Contains(err.Error(), "HEAD not owned by expected holder") { t.Fatalf("%s: forced move accepted %+v: %v", what, h, err) } @@ -174,16 +172,21 @@ func TestWorkspaceUnclaimedGrantHEADRule(t *testing.T) { if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(p.WorkspaceState("v").Moves) != 1 { t.Fatal("a refused HEAD changed authority or journal", line) } - r, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), predecessorHead) - if err != nil || r.NewEpoch != 3 { - t.Fatal("forced move with the unchanged predecessor HEAD:", r, err) + // An older-epoch HEAD whose Gen and RemoteLSN moved since the issue. + moved := predecessorHead + moved.Gen, moved.RemoteLSN = predecessorHead.Gen+1, predecessorHead.RemoteLSN+8 + r, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), moved) + if err != nil || r.NewEpoch != 3 || r.HeadGen != moved.Gen || r.RemoteLSN != moved.RemoteLSN { + t.Fatal("forced move with an older-epoch HEAD:", r, err) } - // A chain: the epoch-3 grantee dies unclaimed too; HEAD is still the - // same predecessor HEAD, recorded by both moves. + if lost := p.WorkspaceLostRanges("v"); len(lost) != 1 || lost[0].LostAfterLSN != moved.RemoteLSN { + t.Fatalf("lost range must start at the fresh HEAD's RemoteLSN: %+v", lost) + } + // A chain: the epoch-3 grantee dies unclaimed too. now = now.Add(10 * grantTTL) next := forcedFromGrantee("forced-again") next.ExpectedHost, next.TargetHost, next.ExpectedEpoch = "third-node", "fourth-node", 3 - if r, err := p.MoveWorkspace(ctx, next, predecessorHead); err != nil || r.NewEpoch != 4 { + if r, err := p.MoveWorkspace(ctx, next, moved); err != nil || r.NewEpoch != 4 { t.Fatal("second unclaimed grant:", r, err) } } @@ -269,3 +272,42 @@ func TestWorkspaceReplayedIssueStartsGranteeLease(t *testing.T) { t.Fatal("forced move after the replayed grant expired:", r, err) } } + +// The double fault: grantee 1 renews and sends its HEAD claim, then stalls; +// its lease expires and a forced move grants grantee 2 against the +// predecessor's HEAD; grantee 1's in-flight claim lands afterwards (HEAD +// moves to its epoch and the next generation); grantee 2 dies unclaimed. +// The next forced move must still be admitted on that older-epoch HEAD, with +// the lost range from its RemoteLSN; never refused for good. +func TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, disk, &now) + now = issued.Add(100 * time.Millisecond) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { + t.Fatal("grantee 1 renewal:", err) + } + // Grantee 1's claim is in flight; it renews no more. + now = now.Add(10 * grantTTL) + r, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced-1"), predecessorHead) + if err != nil || r.NewEpoch != 3 { + t.Fatal("forced move to grantee 2:", r, err) + } + late := WorkspaceHead{Gen: predecessorHead.Gen + 1, Epoch: 2, Holder: "new-node/r", RemoteLSN: predecessorHead.RemoteLSN} + // Grantee 2 dies unclaimed. + now = now.Add(10 * grantTTL) + next := forcedFromGrantee("forced-2") + next.ExpectedHost, next.TargetHost, next.ExpectedEpoch = "third-node", "fourth-node", 3 + r, err = p.MoveWorkspace(ctx, next, late) + if err != nil || r.NewEpoch != 4 || r.HeadGen != late.Gen || r.RemoteLSN != late.RemoteLSN { + t.Fatal("forced move after grantee 1's late claim and grantee 2's death:", r, err) + } + lost := p.WorkspaceLostRanges("v") + if len(lost) != 2 || lost[1].NewEpoch != 4 || lost[1].LostAfterLSN != late.RemoteLSN { + t.Fatalf("lost ranges %+v", lost) + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 4 { + t.Fatal("authority line", line) + } +} diff --git a/seaweed-block/core/host/master/workspace_paused_grantee_test.go b/seaweed-block/core/host/master/workspace_paused_grantee_test.go index 30d4749b97..69af179701 100644 --- a/seaweed-block/core/host/master/workspace_paused_grantee_test.go +++ b/seaweed-block/core/host/master/workspace_paused_grantee_test.go @@ -3,6 +3,7 @@ package master import ( "bytes" "context" + "sync" "testing" "time" @@ -14,6 +15,47 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) +// attachWitness records each projection read: the first refused read (not +// healthy) with the HEAD current at that instant, and whether any read was +// healthy. +type attachWitness struct { + base frontend.ProjectionView + head func() authority.WorkspaceHead + + mu sync.Mutex + refusals int + firstAt authority.WorkspaceHead + healthy bool +} + +func (w *attachWitness) Projection() frontend.Projection { + p := w.base.Projection() + var h authority.WorkspaceHead + if !p.Healthy { + h = w.head() + } + w.mu.Lock() + defer w.mu.Unlock() + if p.Healthy { + w.healthy = true + } else if w.refusals++; w.refusals == 1 { + w.firstAt = h + } + return p +} + +func (w *attachWitness) first() (authority.WorkspaceHead, int) { + w.mu.Lock() + defer w.mu.Unlock() + return w.firstAt, w.refusals +} + +func (w *attachWitness) admitted() bool { + w.mu.Lock() + defer w.mu.Unlock() + return w.healthy +} + // A grantee renews its issued lease, then pauses before claiming HEAD. The // forced move away from it is admitted only after the GRANT's lease expiry // plus skew (the predecessor's older lease never satisfies it), and is @@ -155,25 +197,33 @@ func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) { if guard.Projection().Healthy { t.Fatal("the paused grantee still serves after the forced move") } - granteeProv := open("new-node/r", guard) - deadline := time.Now().Add(300 * time.Millisecond) - for time.Now().Before(deadline) { - if h := readHead(); h != predecessor { - t.Fatalf("the paused grantee claimed HEAD after the forced move: %+v, was %+v", h, predecessor) + // The attach decision is witnessed, not waited for: recovery runs the + // first attach attempt synchronously, and every admission read of the + // projection records the HEAD current at that instant. Close then + // settles the deferred attempts, so none can land afterwards. + witness := &attachWitness{base: guard, head: func() authority.WorkspaceHead { + h, err := remote.GetHead(context.Background()) // also read off the test goroutine: no t.Fatal + if err != nil { + return authority.WorkspaceHead{} } - time.Sleep(20 * time.Millisecond) + return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached} + }} + granteeProv := open("new-node/r", witness) + refusedAt, refusals := witness.first() + if refusals == 0 || refusedAt != predecessor { + t.Fatalf("no witnessed refused attach decision while the predecessor HEAD was current (refusals %d, HEAD %+v)", refusals, refusedAt) } - if bk, err := granteeProv.Open(ctx, "v"); err == nil { - if n, err := bk.Write(ctx, 0, make([]byte, 4096)); err == nil && n == 4096 { - if err := bk.Sync(ctx); err == nil { - if _, err := granteeProv.CaptureVolume(ctx, "v"); err == nil { - t.Fatal("the paused grantee published a cut after the forced move") - } - } - } + if witness.admitted() { + t.Fatal("the paused grantee's attach read a healthy projection after the forced move") } if h := readHead(); h != predecessor { - t.Fatalf("HEAD changed by the paused grantee: %+v", h) + t.Fatalf("the paused grantee claimed HEAD after the forced move: %+v, was %+v", h, predecessor) + } + if err := granteeProv.Close(); err != nil { + t.Fatal(err) + } + if h := readHead(); h != predecessor || witness.admitted() { + t.Fatalf("HEAD changed by the paused grantee before its provider settled: %+v", h) } // The new owner claims at the higher epoch. diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 44b7ab10bf..4f51bf89d7 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -136,10 +136,11 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err := s.workspaceVolume(q.GetVolumeId()); err != nil { return nil, err } - // A forced move reads HEAD only after its lease admission holds: once - // the expected holder's grants have expired, it can no longer change - // HEAD, so the HEAD read below is the one the move and its lost range - // rest on. The publisher re-checks admission when it issues the move. + // A forced move reads HEAD only after its lease admission holds: the + // expected holder's lease has then expired, so it starts no new claim or + // cut before this read. A claim it already sent may still land after it + // (WorkspaceForcedMoveAdmitted). The publisher re-checks admission when + // it issues the move. if q.GetKind() == "forced" { if err := s.host.Publisher().WorkspaceForcedMoveAdmitted(ctx, q.GetVolumeId(), q.GetRequestId(), q.GetExpectedReplicaId(), q.GetExpectedEpoch()); err != nil { return nil, workspaceError(err) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 97e3a0a084..0a06dc8f5b 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -245,6 +245,8 @@ The attempt path is never removed, so a late create can never land after a delet **FORCED move:** blockmaster waits until both the persisted lease horizon (at least every grant, so at most TTL/2 later than the last grant) and the granted or conservative restart deadline, plus the full skew bound, have passed (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). The old host's late CAS fails on the epoch; its uploads become orphans for GC. Writes since the old host's last cut are lost. +**Move issue starts the new holder's lease.** The write that issues epoch e+1 also writes the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view update; the holder's first renewal is an ordinary renewal of it (`core/authority/workspace.go` `issueWorkspaceMove`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`). A new holder that dies before it renews or claims HEAD therefore expires like any holder, and a forced move away from it waits for that lease's expiry and deadline plus the skew bound, never a predecessor's. Blockmaster reads HEAD for a forced move only after that admission holds (`core/host/master/workspace_service.go` `MoveWorkspace`): the holder then starts no new claim or cut, but a claim it already sent may still land, so HEAD is not frozen. A forced move accepts a HEAD that names the expected holder at the expected epoch, or any HEAD at an older epoch (the expected holder never claimed it, or an earlier holder's late claim landed); its lost range starts at that HEAD's `RemoteLSN`. A HEAD at the expected or a higher epoch that is not the expected holder's is refused. A returning holder is stopped by two fences: its lease-gated attach refuses to claim (its lease has expired), and a HEAD that already carries a higher epoch fences its claim. + **Takeover** (`core/storage/chunk_restore.go` `ClaimChunkHead`, called before the chunk layer attaches in `core/frontend/durable/provider_chunk.go`): read HEAD; fence if HEAD has a higher epoch or another holder at the same epoch; seed the local LSN frontier from HEAD (`PrepareRestore`); CAS HEAD to the new epoch and holder with `State = active`; on an unknown outcome, succeed only if a re-read shows the exact proposal. I/O opens afterwards; blocks load lazily on first read. ```mermaid @@ -266,7 +268,14 @@ sequenceDiagram A->>A: self-fence when ValidForNs runs out M->>M: wait for expiry, restart deadline and skew bound, then mint epoch e+1 end + M->>M: the issue write also starts B's lease (horizon issue+1.5·TTL, deadline issue+TTL) M->>B: assignment at epoch e+1 and a lease + opt B dies before renewing or claiming (HEAD still at epoch e) + M->>M: wait for B's lease expiry, deadline and skew bound + M->>F: GetHead (only after that admission) + M->>M: HEAD epoch is older than e+1, so mint epoch e+2 for host C, lost range from that HEAD's RemoteLSN + Note over B,F: a claim B already sent may still land at e+1, C's claim at e+2 supersedes it, and a returning B is refused at attach (expired lease) and by the higher HEAD epoch + end B->>F: GetHead B->>B: refuse if HEAD epoch is higher, else seed the local frontier from HEAD B->>F: CASHead expected {current gen, e}, next {epoch e+1, holder B, active} @@ -284,13 +293,14 @@ Lease states: ```mermaid stateDiagram-v2 state "Lease (blockmaster)" as L { - [*] --> Granted: Renew + [*] --> Granted: first Renew after bind + [*] --> Granted: move issue starts the new holder's lease Granted --> Granted: Renew before horizon and deadline (from memory) Granted --> Revoking: BeginWorkspaceRevocation Revoking --> Acked: host acks detached HEAD gen while the lease is valid Acked --> Moved: CLEAN move Granted --> Expired: horizon or deadline passes - Expired --> Moved: FORCED move after expiry + skew bound + Expired --> Moved: FORCED move after expiry + skew bound, then HEAD read (an older-epoch HEAD is accepted) } ``` diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5872e8378b..e60c026e60 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -95,8 +95,8 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | | Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | -| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's, or, when that holder never claimed it, still the HEAD its move was issued against (same generation and remote LSN, older epoch; forced moves only) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | -| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), so a holder that dies before its first renewal still expires | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | +| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | +| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001` | ### M3 Replica role and peer state @@ -383,9 +383,9 @@ Notes: |---|---|---|---|---|---|---| | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | +| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | | `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. A move issue publishes the derived view and the new holder's initial deadline in one lease-lock section, never lowering a deadline a renewal raised. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceIssuePublishNeverLowersARenewedDeadline` (`core/authority/workspace_issue_publish_test.go`) | — | ACTIVE | | `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that replaces the lease with the new holder's is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | @@ -427,16 +427,16 @@ Notes: | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | | `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | +| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE | +| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound, of the current holder's lease (a move issue starts it; a predecessor's never admits); the lease reported to the host is the grant, never the horizon, and excludes half of the bound. HEAD is read only after that admission; it must be the expected holder's at the expected epoch or be at an older epoch, and the lost range starts at the remote LSN of that HEAD. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact`, `MoveWorkspace` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE | Notes: - `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary. - `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits). -- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. +- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here. ### B.5 Workspace: the cut pipeline