diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 52f8d7fe1f..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 @@ -478,9 +482,10 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr } var issuedWorkspace *WorkspaceState var reservedEpoch uint64 + var issuedAt time.Time if grant != nil { var err error - issuedWorkspace, reservedEpoch, err = p.prepareWorkspaceMoveLocked(ask, *grant) + issuedWorkspace, reservedEpoch, issuedAt, err = p.prepareWorkspaceMoveLocked(ask, *grant) if err != nil { p.mu.Unlock() return err @@ -609,9 +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 { - p.setLeaseDeadlineLocked(ask.VolumeID, time.Time{}, false) // the issued move clears the lease + // The issued move starts the new holder's lease (issuedAt+TTL grant). + 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 6d6301e1b3..b197774f0d 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -270,29 +270,81 @@ func sameWorkspaceRequest(r WorkspaceMoveRecord, q WorkspaceMoveRequest) bool { r.TargetDataAddr == q.TargetDataAddr && r.TargetCtrlAddr == q.TargetCtrlAddr } +// 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: 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 { + return err + } + p.mu.Lock() + defer p.mu.Unlock() + _, line, ok := p.workspaceLineLocked(volume) + s := p.workspace[volume] + if s != nil { + for _, r := range s.Moves { + if r.RequestID == requestID { + return nil + } + } + } + if !ok || line.info.Epoch != epoch || line.info.ReplicaID != holder || s == nil || s.Lease == nil { + return fmt.Errorf("workspace move: missing or changed authority/lease") + } + _, err := p.forcedMoveAdmissionLocked(volume, s.Lease) + return err +} + +// forcedMoveAdmissionLocked returns the audit bound of the lost range when a +// forced move is admitted. Caller holds p.mu. +func (p *Publisher) forcedMoveAdmissionLocked(volume string, lease *WorkspaceLease) (int64, error) { + now := p.workspaceNow() + skew := p.workspaceSkew(lease) + deadline := p.leaseDeadlineLocked(volume) + if now.Before(time.Unix(0, lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { + return 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") + } + // The audit bound only, in wall time: the admission above keeps both + // predicates (the deadline's monotonic reading included). + lostUntil := time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano() + if d := deadline.Add(skew).UnixNano(); d > lostUntil { + lostUntil = d + } + return lostUntil, nil +} + +// 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. +func (p *Publisher) issueWorkspaceMove(s *WorkspaceState, idx int, now time.Time) { + r := &s.Moves[idx] + r.Issued = true + s.Lease, _ = p.newWorkspaceLease(r.NewReplicaID, r.NewEpoch, now) + s.Ack = nil +} + // Called only under Publisher.mu. First persist a reservation with the OLD // assignment. The subsequent authority write includes that same journal record. // A crash at either boundary cannot expose an epoch without its grant record. -func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGrant) (*WorkspaceState, uint64, error) { +// The returned time is the issue time the new holder's lease starts from. +func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGrant) (*WorkspaceState, uint64, time.Time, error) { q, h := g.request, g.head _, line, ok := p.workspaceLineLocked(q.VolumeID) s := cloneWorkspace(p.workspace[q.VolumeID]) if !ok || line.info.Epoch != q.ExpectedEpoch || line.info.ReplicaID != q.ExpectedReplicaID || s == nil || s.Lease == nil { - return nil, 0, fmt.Errorf("workspace move: missing or changed authority/lease") + return nil, 0, time.Time{}, fmt.Errorf("workspace move: missing or changed authority/lease") } var lostUntil int64 if q.Kind == "forced" { - now := p.workspaceNow() - skew := p.workspaceSkew(s.Lease) - deadline := p.leaseDeadlineLocked(q.VolumeID) - if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { - return nil, 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") - } - // The audit bound only, in wall time: the admission above keeps both - // predicates (the deadline's monotonic reading included). - lostUntil = time.Unix(0, s.Lease.ExpiresAtNS).Add(skew).UnixNano() - if d := deadline.Add(skew).UnixNano(); d > lostUntil { - lostUntil = d + var err error + if lostUntil, err = p.forcedMoveAdmissionLocked(q.VolumeID, s.Lease); err != nil { + return nil, 0, time.Time{}, err } } // A restart may resume the identical durable reservation; it never grants @@ -300,7 +352,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra for idx, r := range s.Moves { if r.RequestID == q.RequestID { if r.Issued || !sameWorkspaceRequest(r, q) { - return nil, 0, fmt.Errorf("workspace move reservation differs") + return nil, 0, time.Time{}, fmt.Errorf("workspace move reservation differs") } // A forced reservation issues only with the exact range recorded // before it; a missing one (a reservation older than lost ranges, @@ -308,21 +360,29 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra // request records a fresh range. if r.Kind == "forced" { if _, ok := p.lostRangeLocked(q.VolumeID, r.RequestID, r.NewEpoch); !ok { - return nil, 0, fmt.Errorf("workspace forced move reservation %s has no recorded lost range; retry with a new request id", r.RequestID) + return nil, 0, time.Time{}, fmt.Errorf("workspace forced move reservation %s has no recorded lost range; retry with a new request id", r.RequestID) } } - s.Moves[idx].Issued = true - s.Lease = nil - s.Ack = nil - return s, r.NewEpoch, nil + now := p.workspaceNow() + p.issueWorkspaceMove(s, idx, now) + return s, r.NewEpoch, now, nil } } - if h.Gen == 0 || h.Epoch != q.ExpectedEpoch || h.Holder != q.ExpectedHost+"/"+q.ExpectedReplicaID { - return nil, 0, fmt.Errorf("workspace move: HEAD not owned by expected holder") + owned := h.Gen != 0 && h.Epoch == q.ExpectedEpoch && h.Holder == q.ExpectedHost+"/"+q.ExpectedReplicaID + if !owned && q.Kind == "forced" { + // 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") } if q.Kind == "clean" { if !h.Detached || !s.Lease.Revoking || s.Ack == nil || s.Ack.ReplicaID != q.ExpectedReplicaID || s.Ack.Epoch != q.ExpectedEpoch || s.Ack.HeadGen != h.Gen { - return nil, 0, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK") + return nil, 0, time.Time{}, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK") } } max := maxPublishedEpochForVolume(p.state, q.VolumeID) @@ -332,22 +392,21 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra } } if max == ^uint64(0) { - return nil, 0, fmt.Errorf("workspace epoch exhausted") + return nil, 0, time.Time{}, fmt.Errorf("workspace epoch exhausted") } r := WorkspaceMoveRecord{RequestID: q.RequestID, VolumeID: q.VolumeID, OldHost: q.ExpectedHost, NewHost: q.TargetHost, OldReplicaID: q.ExpectedReplicaID, NewReplicaID: q.TargetReplicaID, Kind: q.Kind, OldEpoch: q.ExpectedEpoch, NewEpoch: max + 1, HeadGen: h.Gen, RemoteLSN: h.RemoteLSN, TargetDataAddr: q.TargetDataAddr, TargetCtrlAddr: q.TargetCtrlAddr} if q.Kind == "forced" { lost := WorkspaceLostRange{RequestID: r.RequestID, NewEpoch: r.NewEpoch, OldReplicaID: r.OldReplicaID, OldEpoch: r.OldEpoch, LostAfterLSN: r.RemoteLSN, LostUntilNS: lostUntil} if err := p.recordLostRangeLocked(q.VolumeID, lost); err != nil { - return nil, 0, err + return nil, 0, time.Time{}, err } } s.Moves = append(s.Moves, r) if err := p.persistWorkspaceLocked(q.VolumeID, s); err != nil { - return nil, 0, err + return nil, 0, time.Time{}, err } - s.Moves[len(s.Moves)-1].Issued = true - s.Lease = nil - s.Ack = nil - return s, r.NewEpoch, nil + now := p.workspaceNow() + p.issueWorkspaceMove(s, len(s.Moves)-1, now) + return s, r.NewEpoch, now, nil } diff --git a/seaweed-block/core/authority/workspace_forced_admission_test.go b/seaweed-block/core/authority/workspace_forced_admission_test.go new file mode 100644 index 0000000000..39329f88fc --- /dev/null +++ b/seaweed-block/core/authority/workspace_forced_admission_test.go @@ -0,0 +1,36 @@ +package authority + +import ( + "context" + "strings" + "testing" + "time" +) + +// WorkspaceForcedMoveAdmitted gives the move's own answer: refused before +// the lease expiry plus skew, admitted at it; a journaled request id is left +// to MoveWorkspace (its replay uses no new HEAD). +func TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, disk, &now) + barrier := issued.Add(grantTTL + grantTTL/2 + p.workspaceSkew(p.WorkspaceState("v").Lease)) + now = barrier.Add(-time.Nanosecond) + if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "forced", "r", 2); err == nil || !strings.Contains(err.Error(), "expiry plus clock-skew margin has not elapsed") { + t.Fatalf("admitted before expiry+skew: %v", err) + } + if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "forced", "r", 1); err == nil || !strings.Contains(err.Error(), "missing or changed authority/lease") { + t.Fatalf("admitted a stale epoch: %v", err) + } + if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "clean", "r", 1); err != nil { + t.Fatalf("a journaled request id must be left to MoveWorkspace: %v", err) + } + now = barrier + if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "forced", "r", 2); err != nil { + t.Fatal("refused after expiry+skew:", err) + } + if _, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), predecessorHead); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/authority/workspace_issue_publish_structure_test.go b/seaweed-block/core/authority/workspace_issue_publish_structure_test.go new file mode 100644 index 0000000000..c9ca23bcb6 --- /dev/null +++ b/seaweed-block/core/authority/workspace_issue_publish_structure_test.go @@ -0,0 +1,166 @@ +package authority + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" + "testing" +) + +// publisherMethods parses this package's production files and returns every +// *Publisher method declaration by name. +func publisherMethods(t *testing.T) map[string]*ast.FuncDecl { + t.Helper() + paths, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + fset := token.NewFileSet() + out := map[string]*ast.FuncDecl{} + for _, path := range paths { + if strings.HasSuffix(path, "_test.go") { + continue + } + src, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + file, err := parser.ParseFile(fset, path, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range file.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Recv == nil || len(fn.Recv.List) != 1 || fn.Body == nil { + continue + } + typ := fn.Recv.List[0].Type + if star, ok := typ.(*ast.StarExpr); ok { + typ = star.X + } + if id, ok := typ.(*ast.Ident); ok && id.Name == "Publisher" { + out[fn.Name.Name] = fn + } + } + } + return out +} + +// leaseMuCall reports whether call is .leaseMu.(). +func leaseMuCall(call *ast.CallExpr, method string) bool { + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != method { + return false + } + inner, ok := sel.X.(*ast.SelectorExpr) + return ok && inner.Sel.Name == "leaseMu" +} + +// The issued move's lease view and its initial deadline are published in +// ONE leaseMu hold (INV-LEASE-VIEW-001): a renewal of the new epoch sees both +// or neither. Structural guard: publishIssuedLeaseLocked takes leaseMu +// exactly once, holds it (deferred unlock) across both the derived-view and +// the deadline assignment, and calls no other Publisher method that takes +// leaseMu, directly or transitively. A split into two sections (for example +// refreshLeaseViewLocked then setLeaseDeadlineLocked) fails it. +func TestWorkspaceIssuePublishIsOneLeaseHold(t *testing.T) { + methods := publisherMethods(t) + callees := map[string][]string{} + direct := map[string]bool{} + for name, fn := range methods { + ast.Inspect(fn.Body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + if leaseMuCall(call, "Lock") { + direct[name] = true + } else if sel, ok := call.Fun.(*ast.SelectorExpr); ok { + if _, isMethod := methods[sel.Sel.Name]; isMethod { + callees[name] = append(callees[name], sel.Sel.Name) + } + } + return true + }) + } + takes := map[string]bool{} + for name := range direct { + takes[name] = true + } + for changed := true; changed; { + changed = false + for name, cs := range callees { + for _, c := range cs { + if takes[c] && !takes[name] { + takes[name], changed = true, true + } + } + } + } + // The analysis is not vacuous: the two halves of a split publication + // are known lease-taking methods. + for _, name := range []string{"refreshLeaseViewLocked", "setLeaseDeadlineLocked", "leaseDeadlineLocked"} { + if !takes[name] { + t.Fatalf("structure scan does not see %s take leaseMu; the guard would be vacuous", name) + } + } + + fn := methods["publishIssuedLeaseLocked"] + if fn == nil { + t.Fatal("publishIssuedLeaseLocked not found") + } + var locks, unlocks, deferredUnlocks int + var lockPos token.Pos + var viewSet, deadlineSet []token.Pos + var lockingCallees []string + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.DeferStmt: + if leaseMuCall(x.Call, "Unlock") { + deferredUnlocks++ + return false + } + case *ast.CallExpr: + switch { + case leaseMuCall(x, "Lock"): + locks++ + lockPos = x.Pos() + case leaseMuCall(x, "Unlock"): + unlocks++ + default: + if sel, ok := x.Fun.(*ast.SelectorExpr); ok && takes[sel.Sel.Name] { + lockingCallees = append(lockingCallees, sel.Sel.Name) + } + } + case *ast.AssignStmt: + for _, lhs := range x.Lhs { + if sel, ok := lhs.(*ast.SelectorExpr); ok { + switch sel.Sel.Name { + case "d": + viewSet = append(viewSet, x.Pos()) + case "deadline": + deadlineSet = append(deadlineSet, x.Pos()) + } + } + } + } + return true + }) + if locks != 1 || deferredUnlocks != 1 || unlocks != 0 { + t.Fatalf("publishIssuedLeaseLocked must take leaseMu exactly once and hold it to return (defer Unlock): Lock %d, deferred Unlock %d, explicit Unlock %d", locks, deferredUnlocks, unlocks) + } + if len(lockingCallees) != 0 { + t.Fatalf("publishIssuedLeaseLocked calls methods that take leaseMu (a second lease hold): %v", lockingCallees) + } + if len(viewSet) == 0 || len(deadlineSet) == 0 { + t.Fatalf("publishIssuedLeaseLocked must set both the derived view (lv.d: %d) and the deadline (lv.deadline: %d)", len(viewSet), len(deadlineSet)) + } + for _, pos := range append(append([]token.Pos{}, viewSet...), deadlineSet...) { + if pos < lockPos { + t.Fatal("publishIssuedLeaseLocked sets the view or the deadline before taking leaseMu") + } + } +} 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_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 2a43a9c5b9..7d35415762 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -186,8 +186,10 @@ func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) { t.Fatal(err) } check("clean move issued") - if p.leaseDeadlineLockedForTest("v") != (time.Time{}) { - t.Fatal("move issue kept the old deadline") + // The issue replaces the old holder's deadline with the new holder's + // first grant: issue time (10 s) + TTL. + if got := p.leaseDeadlineLockedForTest("v"); !got.Equal(c.sec(40)) { + t.Fatalf("move issue deadline %s; want the new holder's issue+TTL %s", got, c.sec(40)) } // w: forced move whose issue write fails after the reservation persisted. c.at(30 + 15 + 20 + 1) // past w's horizon (45) + skew (20) @@ -940,10 +942,13 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { if extensions.Load() == 0 { t.Fatal("no horizon-extension write was observed") } - if st := p.WorkspaceState(vol(forcedVol)); st == nil || st.Lease != nil || len(st.Moves) != 1 || !st.Moves[0].Issued || st.Moves[0].Kind != "forced" { + // An issued move starts the new holder's lease at the new epoch. + if st := p.WorkspaceState(vol(forcedVol)); st == nil || len(st.Moves) != 1 || !st.Moves[0].Issued || st.Moves[0].Kind != "forced" || + st.Lease == nil || st.Lease.Epoch != st.Moves[0].NewEpoch || st.Lease.Revoking { t.Fatalf("forced move not issued: %+v", st) } - if st := p.WorkspaceState(vol(cleanVol)); st == nil || st.Lease != nil || len(st.Moves) != 1 || st.Moves[0].Kind != "clean" { + if st := p.WorkspaceState(vol(cleanVol)); st == nil || len(st.Moves) != 1 || st.Moves[0].Kind != "clean" || + st.Lease == nil || st.Lease.Epoch != st.Moves[0].NewEpoch || st.Lease.Revoking { t.Fatalf("clean move not issued: %+v", st) } assertLeaseViewMatches(t, p, "after concurrency") @@ -959,8 +964,8 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { } for i := 0; i < n; i++ { st := p.WorkspaceState(vol(i)) - if st == nil || st.Lease == nil { - continue // a completed move cleared the lease (out of S1's scope) + if st == nil || st.Lease == nil || st.Lease.Epoch != 1 { + continue // a completed move started the next epoch's lease (out of S1's scope) } if onDisk[vol(i)] < st.Lease.ExpiresAtNS || st.Lease.ExpiresAtNS < maxGrant[i].Load() { t.Fatalf("%s: S1 broken: disk %d, published horizon %d, max grant %d", vol(i), onDisk[vol(i)], st.Lease.ExpiresAtNS, maxGrant[i].Load()) diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index 6cfc82d8a5..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,7 +97,7 @@ func (p *Publisher) leaseDeadlineLocked(volume string) time.Time { return time.Time{} } -// setLeaseDeadlineLocked replaces the deadline (restart rule, move issue) 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) @@ -201,7 +220,8 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri } // firstWorkspaceGrant creates a lease synchronously under p.mu (one write per -// assignment epoch). A host whose first renewal fails does not fence: it has +// assignment epoch) for an epoch that has none: a move issue already started +// its holder's lease. A host whose first renewal fails does not fence: it has // no deadline yet and retries. The durable horizon starts at now+1.5*TTL. func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { p.mu.Lock() @@ -226,17 +246,22 @@ func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder stri p.mu.Unlock() return WorkspaceLease{}, fmt.Errorf("workspace lease: created concurrently; retry") } - now := p.workspaceNow() - skew := int64(p.workspaceSkew(nil)) - grant := now.Add(p.workspaceTTL) - s.Lease = &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: skew} + lease, grant := p.newWorkspaceLease(holder, epoch, p.workspaceNow()) + s.Lease = lease if err := p.persistWorkspaceLocked(volume, s); err != nil { p.mu.Unlock() return WorkspaceLease{}, err } p.setLeaseDeadlineLocked(volume, grant, true) p.mu.Unlock() - return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: skew}, nil + return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lease.MaxClockSkewNS}, nil +} + +// newWorkspaceLease starts a lease at now: the durable horizon is +// now+1.5*TTL and the grant (the deadline) now+TTL. Both a first grant and a +// move issue start a lease this way. +func (p *Publisher) newWorkspaceLease(holder string, epoch uint64, now time.Time) (*WorkspaceLease, time.Time) { + return &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(nil))}, now.Add(p.workspaceTTL) } // extendWorkspaceLease is an ordinary writer: under p.mu it rechecks the diff --git a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go new file mode 100644 index 0000000000..d57b36760e --- /dev/null +++ b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go @@ -0,0 +1,313 @@ +package authority + +import ( + "context" + "strings" + "sync/atomic" + "testing" + "time" +) + +// countPutStore counts authority writes. +type countPutStore struct { + AuthorityStore + puts atomic.Int64 +} + +func (s *countPutStore) Put(r DurableRecord) error { + s.puts.Add(1) + return s.AuthorityStore.Put(r) +} + +const grantTTL = time.Second + +// The predecessor's detached HEAD: the grantee of the clean move below never +// claims it, so HEAD keeps naming the predecessor. +var predecessorHead = WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/r", RemoteLSN: 42, Detached: true} + +// cleanMoveToGrantee binds v to r at epoch 1, then moves it cleanly from +// old-node to new-node (epoch 2) at the returned issue time. +func cleanMoveToGrantee(t *testing.T, store AuthorityStore, now *time.Time) (*Publisher, time.Time) { + t.Helper() + ctx := context.Background() + p := NewPublisher(nil, WithStore(store), 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) + req := WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} + r, err := p.MoveWorkspace(ctx, req, predecessorHead) + if err != nil || !r.Issued || r.NewEpoch != 2 { + t.Fatal("clean move to the grantee:", r, err) + } + return p, *now +} + +// assertGranteeLease checks the lease the move issue started: the grantee's +// identity at the new epoch, horizon issue+1.5*TTL, not revoking, no ACK. +func assertGranteeLease(t *testing.T, p *Publisher, issued time.Time) { + t.Helper() + st := p.WorkspaceState("v") + want := WorkspaceLease{ReplicaID: "r", Epoch: 2, ExpiresAtNS: issued.Add(grantTTL + grantTTL/2).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(nil))} + if st == nil || st.Lease == nil || *st.Lease != want || st.Ack != nil { + t.Fatalf("move issue must start the grantee's lease %+v; state %+v", want, st) + } +} + +func forcedFromGrantee(id string) WorkspaceMoveRequest { + return WorkspaceMoveRequest{RequestID: id, VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "new-node", TargetHost: "third-node", ExpectedEpoch: 2, TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true} +} + +// A grantee that dies between its grant and its HEAD claim never renews: +// the lease the move issue started expires, and a forced move to a third +// host is admitted after its expiry plus the skew margin, never before. The +// same holds when blockmaster restarts between the issue and the forced move. +func TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry(t *testing.T) { + for _, restart := range []bool{false, true} { + name := "same-master" + if restart { + name = "restart" + } + t.Run(name, func(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, disk, &now) + assertGranteeLease(t, p, issued) + assertLeaseViewMatches(t, p, "after issue") + if lease, ok := p.WorkspaceLeaseReply("v"); !ok || lease.Epoch != 2 || lease.ExpiresAtNS != issued.Add(grantTTL).UnixNano() { + t.Fatalf("reported lease after issue: %+v %v; want the issue+TTL grant", lease, ok) + } + if restart { + now = now.Add(200 * time.Millisecond) + p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return now })) + assertGranteeLease(t, p, issued) + assertLeaseViewMatches(t, p, "after restart") + } + skew := p.workspaceSkew(p.WorkspaceState("v").Lease) + // The horizon (issue+1.5*TTL) is the later bound: the deadline is + // issue+TTL, or restart+TTL after a restart 0.2*TTL later. + barrier := issued.Add(grantTTL + grantTTL/2 + skew) + // The predecessor's lease (renewed 0.1 s before the issue) has + // expired plus skew by then: only the grant's lease may admit. + if old := issued.Add(-100*time.Millisecond + grantTTL + grantTTL/2 + skew); !barrier.Add(-time.Nanosecond).After(old) { + t.Fatal("test clock does not separate the predecessor's barrier from the grant's") + } + now = barrier.Add(-time.Nanosecond) + if _, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), predecessorHead); err == nil || !strings.Contains(err.Error(), "expiry plus clock-skew margin has not elapsed") { + t.Fatalf("forced move before expiry+skew: %v", err) + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(p.WorkspaceState("v").Moves) != 1 { + t.Fatal("early refusal changed authority or journal", line) + } + now = barrier + r, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), predecessorHead) + if err != nil { + t.Fatal("forced move after expiry+skew:", err) + } + if !r.Issued || r.NewEpoch != 3 || r.NewHost != "third-node" || r.HeadGen != predecessorHead.Gen || r.RemoteLSN != predecessorHead.RemoteLSN { + t.Fatalf("forced grant %+v", r) + } + lost := p.WorkspaceLostRanges("v") + if len(lost) != 1 || lost[0].NewEpoch != 3 || lost[0].OldEpoch != 2 || lost[0].LostAfterLSN != predecessorHead.RemoteLSN { + t.Fatalf("lost range %+v", lost) + } + if st := p.WorkspaceState("v"); st.Lease == nil || st.Lease.Epoch != 3 || st.Lease.ExpiresAtNS != now.Add(grantTTL+grantTTL/2).UnixNano() { + t.Fatalf("forced issue must start the next holder's lease: %+v", st.Lease) + } + assertLeaseViewMatches(t, p, "after forced move") + }) + } +} + +// 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) + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, disk, &now) + + // Clean: even with the grantee's revocation ACK naming that HEAD + // generation, the predecessor's HEAD is not the grantee's. + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 2); err != nil { + t.Fatal("revoke the grantee's issued lease:", err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 2, HeadGen: predecessorHead.Gen}); err != nil { + t.Fatal(err) + } + clean := forcedFromGrantee("clean-2") + clean.Kind, clean.Force = "clean", false + if _, err := p.MoveWorkspace(ctx, clean, predecessorHead); err == nil || !strings.Contains(err.Error(), "HEAD not owned by expected holder") { + t.Fatalf("clean move accepted the predecessor's HEAD: %v", err) + } + + now = issued.Add(10 * grantTTL) + refused := map[string]WorkspaceHead{} + h := predecessorHead + h.Epoch = 2 + 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 + 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) + } + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(p.WorkspaceState("v").Moves) != 1 { + t.Fatal("a refused HEAD changed authority or journal", line) + } + // 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) + } + 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, moved); err != nil || r.NewEpoch != 4 { + t.Fatal("second unclaimed grant:", r, err) + } +} + +// The grantee's first renewal is an ordinary renewal of the lease the issue +// started: no authority write, no new epoch; the old epoch stays refused. +func TestWorkspaceUnclaimedGrantGranteeRenewsNormally(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + store := &countPutStore{AuthorityStore: disk} + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, store, &now) + writes := store.puts.Load() + now = issued.Add(100 * time.Millisecond) + l, err := p.RenewWorkspaceLease(ctx, "v", "r", 2) + if err != nil { + t.Fatal("grantee's first renewal:", err) + } + if l.Epoch != 2 || l.ReplicaID != "r" || l.ExpiresAtNS != now.Add(grantTTL).UnixNano() { + t.Fatalf("first renewal %+v", l) + } + if store.puts.Load() != writes { + t.Fatalf("first renewal wrote %d authority records; the issue already persisted the lease", store.puts.Load()-writes) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil { + t.Fatal("old epoch renewed after the move") + } + // Past 0.25*TTL the renewal starts an extension of the issued lease. + now = issued.Add(grantTTL / 2) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { + t.Fatal(err) + } + st := p.WorkspaceState("v") + for wait := time.Now().Add(5 * time.Second); time.Now().Before(wait) && (st.Lease == nil || st.Lease.ExpiresAtNS == issued.Add(grantTTL+grantTTL/2).UnixNano()); st = p.WorkspaceState("v") { + time.Sleep(5 * time.Millisecond) + } + p.CloseWorkspaceExtenders() + if st.Lease == nil || st.Lease.Epoch != 2 || st.Lease.ExpiresAtNS != now.Add(grantTTL+grantTTL/2).UnixNano() { + t.Fatalf("issued lease not extended: %+v", st.Lease) + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(st.Moves) != 1 { + t.Fatal("renewals changed authority", line) + } + assertLeaseViewMatches(t, p, "after renewals") +} + +// A forced reservation resumed after a crash issues through the replay path, +// which starts the new holder's lease the same way. +func TestWorkspaceReplayedIssueStartsGranteeLease(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + fault := &workspaceFailStore{AuthorityStore: disk} + now := time.Unix(1000, 0) + p := NewPublisher(nil, WithStore(fault), 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) + } + now = now.Add(3 * grantTTL) + req := WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} + head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/r", RemoteLSN: 42} + fault.failIssue = true + if _, err := p.MoveWorkspace(ctx, req, head); err == nil { + t.Fatal("injected crash ignored") + } + loaded := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return now })) + now = now.Add(2 * grantTTL) // past the restart deadline plus skew + r, err := loaded.MoveWorkspace(ctx, req, WorkspaceHead{}) + if err != nil || !r.Issued || r.NewEpoch != 2 { + t.Fatal("replayed issue:", r, err) + } + assertGranteeLease(t, loaded, now) + assertLeaseViewMatches(t, loaded, "after replayed issue") + if _, err := loaded.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { + t.Fatal("grantee renewal after the replayed issue:", err) + } + // Unrenewed after this, the replayed grant expires like any other. + now = now.Add(grantTTL + grantTTL/2 + loaded.workspaceSkew(nil)) + next := WorkspaceMoveRequest{RequestID: "m2", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "new-node", TargetHost: "third-node", ExpectedEpoch: 2, TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true} + if r, err := loaded.MoveWorkspace(ctx, next, head); err != nil || r.NewEpoch != 3 { + 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 new file mode 100644 index 0000000000..69af179701 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_paused_grantee_test.go @@ -0,0 +1,234 @@ +package master + +import ( + "bytes" + "context" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "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 +// granted on the predecessor's unchanged HEAD. The grantee resumes before +// the new owner claims: HEAD's epoch has not moved yet, so the epoch alone +// would let it claim; the authority check at attach (its lease-gated +// projection) refuses it. The new owner then claims at the higher epoch. +func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := authority.NewFileAuthorityStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := store.Close(); err != nil { + t.Error(err) + } + }) + const ttl = 3 * time.Second + start := time.Now() + masterNow, hostNow := start, start + dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} + p := authority.NewPublisher(dir, authority.WithStore(store), authority.WithWorkspaceLeaseConfig(ttl, func() time.Time { return masterNow })) + seedSkewPublisher(t, p, dir) // v bound to r at epoch 1 + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + oldBarrier := time.Unix(0, p.WorkspaceState("v").Lease.ExpiresAtNS) + + remote := storage.NewMemChunkRemote() + readHead := func() authority.WorkspaceHead { + t.Helper() + h, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached} + } + open := func(holder string, view frontend.ProjectionView) *durable.DurableProvider { + t.Helper() + prov, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + ChunkHolder: holder, ChunkAssignmentTimeout: 2 * time.Second, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = prov.Close() }) + if _, err := prov.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + if _, err := prov.RecoverVolume(ctx, "v"); err != nil { + t.Fatalf("%s recovery: %v", holder, err) + } + return prov + } + healthy := func(epoch uint64) restoreProjection { + return restoreProjection{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: epoch, EndpointVersion: 1, Healthy: true}} + } + + // The predecessor writes, cuts and detaches; the clean move grants new-node. + oldProv := open("old-node/r", healthy(1)) + b, err := oldProv.Open(ctx, "v") + if err != nil { + t.Fatal(err) + } + if n, err := b.Write(ctx, 0, bytes.Repeat([]byte{0xA5}, 4096)); err != nil || n != 4096 { + t.Fatal(n, err) + } + if err := b.Sync(ctx); err != nil { + t.Fatal(err) + } + if _, err := oldProv.CaptureVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + detached, _, err := oldProv.DetachVolume(ctx, "v") + if err != nil || detached.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach: %+v %v", detached.Head, err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", authority.WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: detached.Head.Gen}); err != nil { + t.Fatal(err) + } + // The lease reply's validity is measured on the real clock: keep the + // fake clocks at real time for the move and the grantee's renewal. + masterNow = time.Now() + if min := start.Add(500 * time.Millisecond); masterNow.Before(min) { + masterNow = min + } + hostNow = masterNow + clean, err := p.MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, + TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"}, readHead()) + if err != nil || clean.NewEpoch != 2 { + t.Fatal("clean move:", clean, err) + } + predecessor := readHead() + + // The grantee renews (its guard is valid), then pauses before its claim. + guard, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 2, EndpointVersion: 1, Healthy: true}}, skewLeaseClient{p}, + &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 2}, func(context.Context) (uint64, error) { return 0, nil }, func() time.Time { return hostNow }) + if err != nil { + t.Fatal(err) + } + if err := guard.Refresh(ctx); err != nil { + t.Fatal("grantee renewal:", err) + } + if !guard.Projection().Healthy { + t.Fatal("grantee not serving after its renewal") + } + lease := p.WorkspaceState("v").Lease + if lease == nil || lease.Epoch != 2 { + t.Fatalf("grantee lease %+v", lease) + } + skew := time.Duration(lease.MaxClockSkewNS) + grantBarrier := time.Unix(0, lease.ExpiresAtNS).Add(skew) + forced := authority.WorkspaceMoveRequest{RequestID: "forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "new-node", TargetHost: "third-node", ExpectedEpoch: 2, + TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true} + + // After the predecessor's lease (plus skew) but before the grant's: refused. + masterNow = oldBarrier.Add(skew).Add(grantBarrier.Sub(oldBarrier.Add(skew)) / 2) + if !masterNow.After(oldBarrier.Add(skew)) || !masterNow.Before(grantBarrier) { + t.Fatalf("test clock: %s not between %s and %s", masterNow, oldBarrier.Add(skew), grantBarrier) + } + if _, err := p.MoveWorkspace(ctx, forced, readHead()); err == nil { + t.Fatal("forced move admitted on the predecessor's lease before the grant's lease expired") + } + masterNow = grantBarrier + r, err := p.MoveWorkspace(ctx, forced, readHead()) + if err != nil || r.NewEpoch != 3 || r.HeadGen != predecessor.Gen { + t.Fatal("forced move after the grant's lease expired:", r, err) + } + + // The grantee resumes before the new owner claims. Its attach is refused. + hostNow = masterNow + if guard.Projection().Healthy { + t.Fatal("the paused grantee still serves after the forced move") + } + // 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{} + } + 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 witness.admitted() { + t.Fatal("the paused grantee's attach read a healthy projection after the forced move") + } + if h := readHead(); h != predecessor { + 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. + open("third-node/r", healthy(3)) + if h := readHead(); h.Epoch != 3 || h.Holder != "third-node/r" || h.RemoteLSN != predecessor.RemoteLSN { + t.Fatalf("HEAD after the new owner's claim: %+v", h) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index fabe00514c..4f51bf89d7 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -136,6 +136,16 @@ 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: 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) + } + } // Always bound the configured reader, even when the caller omitted a deadline. readCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() diff --git a/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go b/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go new file mode 100644 index 0000000000..3a6b4defa4 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go @@ -0,0 +1,190 @@ +package master + +import ( + "context" + "errors" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// seedDetachedHead installs the predecessor's detached final cut. +func seedDetachedHead(t *testing.T, ctx context.Context, remote *storage.MemChunkRemote, holder string, epoch, lsn uint64) storage.ChunkHead { + t.Helper() + h := storage.ChunkHead{Epoch: epoch, Holder: holder, RemoteLSN: lsn, State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Holder: holder, Epoch: epoch, Gen: 1}} + gen, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, h) + if err != nil { + t.Fatal(err) + } + h.Gen = gen + return h +} + +// A clean move grants vol-a to node-b, whose host dies before its first +// renewal and so before it claims HEAD: HEAD still names node-a. A forced +// move to node-c is refused before the lease the issue started has expired +// plus the skew bound, without reading HEAD; after it, it reads HEAD (only +// then) and is granted on the predecessor's unchanged HEAD. A late claim by +// the dead grantee never displaces the new owner's higher epoch. +func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) { + // The real lease horizon (1.5 x the 30 s TTL) plus skew takes ~45 s. + ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + var reads atomic.Int64 + var lastReadNS atomic.Int64 + reader := func(ctx context.Context, _ string) (authority.WorkspaceHead, error) { + reads.Add(1) + lastReadNS.Store(time.Now().UnixNano()) + h, err := remote.GetHead(ctx) + if err != nil { + return authority.WorkspaceHead{}, err + } + return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached}, nil + } + const skew = 100 * time.Millisecond + m, err := New(Config{WorkspaceMaxClockSkew: skew, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: reader}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + + for _, server := range []string{"node-a", "node-b", "node-c"} { + if _, err = m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + } + if _, err = lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + src := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-a", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"} + dst := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-b", DataAddr: "127.0.0.1:29200", CtrlAddr: "127.0.0.1:29100"} + third := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-c", DataAddr: "127.0.0.1:39200", CtrlAddr: "127.0.0.1:39100"} + for _, b := range []*control.WorkspaceBinding{src, dst, third} { + if _, err = ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err = ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "vol-a", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + if _, err = control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-a", ReplicaId: "r1", DataAddr: src.DataAddr, CtrlAddr: src.CtrlAddr}}}); err != nil { + t.Fatal(err) + } + if _, err = m.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a") + oldID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: oldLine.ReplicaID, Epoch: oldLine.Epoch} + if _, err = ws.RenewWorkspaceLease(ctx, oldID); err != nil { + t.Fatal(err) + } + + // node-a detaches its final cut and ACKs; the clean move grants node-b. + seed := seedDetachedHead(t, ctx, remote, "node-a/"+oldLine.ReplicaID, oldLine.Epoch, 42) + if _, err = ws.RevokeWorkspace(ctx, oldID); err != nil { + t.Fatal(err) + } + if _, err = ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: oldID, HeadGen: seed.Gen}); err != nil { + t.Fatal(err) + } + clean, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "clean-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: oldLine.Epoch, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: dst.DataAddr, TargetCtrlAddr: dst.CtrlAddr, Kind: "clean"}) + if err != nil { + t.Fatal("clean move:", err) + } + grantee := clean.GetNewEpoch() + st := m.Publisher().WorkspaceState("vol-a") + if st == nil || st.Lease == nil || st.Lease.ReplicaID != "r1" || st.Lease.Epoch != grantee || st.Lease.Revoking { + t.Fatalf("the issued move must start node-b's lease: %+v", st) + } + barrier := time.Unix(0, st.Lease.ExpiresAtNS).Add(skew) + if q, err := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-a"}); err != nil || q.GetLease() == nil || q.GetLease().GetEpoch() != grantee { + t.Fatalf("QueryWorkspace after the issue: %+v %v", q.GetLease(), err) + } + + // node-b dies before renewing or claiming. Before expiry plus skew the + // forced move is refused, and HEAD is not read for it. + forced := &control.WorkspaceMove{RequestId: "forced-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: grantee, TargetReplicaId: "r1", + TargetServerId: "node-c", TargetDataAddr: third.DataAddr, TargetCtrlAddr: third.CtrlAddr, Kind: "forced", Force: true} + before := reads.Load() + if _, err := ws.MoveWorkspace(ctx, forced); err == nil || !strings.Contains(err.Error(), "expiry plus clock-skew margin has not elapsed") { + t.Fatalf("forced move before the issued lease expired: %v", err) + } + if n := reads.Load() - before; n != 0 { + t.Fatalf("HEAD read %d times for a forced move whose admission had not passed", n) + } + + select { + case <-time.After(time.Until(barrier) + 50*time.Millisecond): + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + grant, err := ws.MoveWorkspace(ctx, forced) + if err != nil { + t.Fatal("forced move after the issued lease expired:", err) + } + if reads.Load() == before || time.Unix(0, lastReadNS.Load()).Before(barrier) { + t.Fatalf("the forced move's HEAD was not read after admission (reads %d, last read %s, barrier %s)", reads.Load()-before, time.Unix(0, lastReadNS.Load()), barrier) + } + line, _ := m.Publisher().VolumeAuthorityLine("vol-a") + if !grant.Issued || grant.NewEpoch != grantee+1 || line.Epoch != grant.NewEpoch || grant.HeadGen != seed.Gen || grant.RemoteLsn != seed.RemoteLSN { + t.Fatalf("forced grant %+v line %+v; want epoch %d on HEAD gen %d lsn %d", grant, line, grantee+1, seed.Gen, seed.RemoteLSN) + } + if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: "r1", Epoch: grantee}); err == nil { + t.Fatal("the dead grantee's epoch renewed after the forced move") + } + + // A late grantee claim. (b) Its CAS lands after the forced move's HEAD + // read but before the new owner claims: the new owner still takes HEAD + // at the higher epoch, and the grantee is fenced afterwards. + granteeCfg := storage.ChunkLayerConfig{Epoch: grantee, Holder: "node-b/r1"} + ownerCfg := storage.ChunkLayerConfig{Epoch: grant.NewEpoch, Holder: "node-c/r1"} + late, err := storage.ClaimChunkHead(ctx, remote, granteeCfg) + if err != nil { + t.Fatal("late grantee claim landing first:", err) + } + owned, err := storage.ClaimChunkHead(ctx, remote, ownerCfg) + if err != nil || owned.Epoch != grant.NewEpoch || owned.Holder != "node-c/r1" || owned.RemoteLSN != seed.RemoteLSN { + t.Fatalf("new owner's claim over the late grantee: %+v %v", owned, err) + } + if _, err := storage.ClaimChunkHead(ctx, remote, granteeCfg); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("grantee re-claim after the new owner: %v; want fenced", err) + } + stale := late + stale.State = storage.ChunkHeadActive + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: late.Gen, Epoch: late.Epoch}, stale); !errors.Is(err, storage.ErrChunkHeadPrecondition) { + t.Fatalf("grantee HEAD write after the new owner: %v; want a CAS precondition failure", err) + } + // (a) The new owner claims first; the late grantee claim is fenced. + fresh := storage.NewMemChunkRemote() + seedDetachedHead(t, ctx, fresh, "node-a/"+oldLine.ReplicaID, oldLine.Epoch, 42) + if _, err := storage.ClaimChunkHead(ctx, fresh, ownerCfg); err != nil { + t.Fatal(err) + } + if _, err := storage.ClaimChunkHead(ctx, fresh, granteeCfg); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("late grantee claim after the new owner: %v; want fenced", err) + } + for _, r := range []*storage.MemChunkRemote{remote, fresh} { + if h, err := r.GetHead(ctx); err != nil || h.Epoch != grant.NewEpoch || h.Holder != "node-c/r1" { + t.Fatalf("HEAD after the late claim: %+v %v; want the new owner", h, err) + } + } +} diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 8b1152d2cd..d4d621ecd1 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 d2227ca9d4..3db602c58e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -88,15 +88,15 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | From | To | Event and guard | Enforced in | Protects | |---|---|---|---|---| -| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | +| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL (an epoch issued by a move already has its lease) | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | | Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | 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 | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `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 | `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 @@ -405,10 +405,10 @@ 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-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 clears the lease 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-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 | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | @@ -453,17 +453,17 @@ 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-STOP-PENDING-001` | Stop-pending changes only when the lease guard renews, never what it admits or acknowledges: from the start of a chunk detach until the guard fences, its sleep after a completed renewal is at most 250 ms; it returns to the normal renewal delay only when that same (latest) detach attempt provably did not happen and serving resumed. It bounds scheduling, not the time from a revocation to its acknowledgement. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/frontend/durable/provider_chunk.go` `DetachVolume`, `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay` | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | 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`) | — | 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. - `INV-WS-STOP-PENDING-001`: `WorkspaceTakeover` has no renewal cadence (a host may renew at any step), so StopPending adds no state to the model and no configuration is re-run; `INV-WS-LEASE-001` and `INV-WS-REVOKE-ACK-001` hold in StopPending unchanged. ### B.5 Workspace: the cut pipeline