diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 6556be2cc4..7cf968bcd9 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -157,12 +157,20 @@ type Publisher struct { // Workspace state is serialized with assignment minting under mu. Remote // HEAD reads and subscriber delivery never run under this lock. - workspace map[string]*WorkspaceState - workspaceUncertain map[string]bool - workspaceNow func() time.Time - workspaceTTL time.Duration - workspaceMaxClockSkew time.Duration - workspaceLeaseDeadline map[string]time.Time + workspace map[string]*WorkspaceState + workspaceUncertain map[string]bool + workspaceNow func() time.Time + workspaceTTL time.Duration + workspaceMaxClockSkew time.Duration + + // Lease renewal state (workspace_lease_view.go). leaseMu is a memory-only + // leaf: lock order p.mu -> leaseMu, never the reverse, and nothing is + // acquired, waited on or written while it is held. + leaseMu sync.Mutex + leaseViews map[string]*leaseView + leaseClosing bool + extWG sync.WaitGroup + extendFailures map[string]int // guarded by mu } // PublicationAdmission surrounds an ordinary mint with local ownership/lifetime @@ -221,15 +229,16 @@ func WithPublishObserver(observer PublishObserver) PublisherOption { // the pieces. func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher { p := &Publisher{ - dir: dir, - state: make(map[subKey]assignmentState), - subs: make(map[subKey][]*subscription), - writeSeqByVolume: map[string]uint64{}, - workspace: map[string]*WorkspaceState{}, - workspaceUncertain: map[string]bool{}, - workspaceNow: time.Now, - workspaceTTL: 30 * time.Second, - workspaceLeaseDeadline: map[string]time.Time{}, + dir: dir, + state: make(map[subKey]assignmentState), + subs: make(map[subKey][]*subscription), + writeSeqByVolume: map[string]uint64{}, + workspace: map[string]*WorkspaceState{}, + workspaceUncertain: map[string]bool{}, + workspaceNow: time.Now, + workspaceTTL: 30 * time.Second, + leaseViews: map[string]*leaseView{}, + extendFailures: map[string]int{}, } for _, opt := range opts { if opt != nil { @@ -256,9 +265,6 @@ func (p *Publisher) reloadFromStore() { for _, rec := range records { if rec.Workspace != nil { p.workspace[rec.VolumeID] = cloneWorkspace(rec.Workspace) - // Conservatively cover every previously granted TTL after restart. - // Persisted wall time alone must never shorten a live host's lease. - p.workspaceLeaseDeadline[rec.VolumeID] = p.workspaceNow().Add(p.workspaceTTL) } key := subKey{volumeID: rec.VolumeID, replicaID: rec.ReplicaID} p.state[key] = assignmentState{ @@ -277,6 +283,14 @@ func (p *Publisher) reloadFromStore() { } } p.loadErrs = append(p.loadErrs, skips...) + for _, rec := range records { + p.refreshLeaseViewLocked(rec.VolumeID) + if rec.Workspace != nil { + // Conservatively cover every previously granted TTL after restart. + // Persisted wall time alone must never shorten a live host's lease. + p.setLeaseDeadlineLocked(rec.VolumeID, p.workspaceNow().Add(p.workspaceTTL), false) + } + } } // LoadErrors returns the per-record skip errors observed during @@ -575,6 +589,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr // unwind. Just report the failure. if record.Workspace != nil { p.workspaceUncertain[ask.VolumeID] = true + p.refreshLeaseViewLocked(ask.VolumeID) } p.mu.Unlock() return fmt.Errorf("authority: durable Put failed, rolling back mint: %w", err) @@ -583,10 +598,13 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr } if issuedWorkspace != nil { p.workspace[ask.VolumeID] = issuedWorkspace - delete(p.workspaceLeaseDeadline, ask.VolumeID) } 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 + } // Snapshot subscribers under lock, release the lock BEFORE // delivering. This prevents a slow consumer goroutine from diff --git a/seaweed-block/core/authority/authority_store_test.go b/seaweed-block/core/authority/authority_store_test.go index 99674cf04b..3a270db010 100644 --- a/seaweed-block/core/authority/authority_store_test.go +++ b/seaweed-block/core/authority/authority_store_test.go @@ -362,6 +362,12 @@ func TestDurableAuthority_StoreWriteCallerAllowlist_BoundaryGuard(t *testing.T) if !strings.HasSuffix(path, ".go") { return nil } + // Test doubles outside the package (for example a slow-store wrapper + // that delays and then delegates Put) are not production write + // callers; the guard is about the production tree. + if strings.HasSuffix(path, "_test.go") { + return nil + } // The authority package itself is the only legitimate // write caller. if strings.Contains(path, string(filepath.Separator)+"core"+string(filepath.Separator)+"authority"+string(filepath.Separator)) { diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index ea4f05b7fa..514520b38c 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -92,41 +92,6 @@ func (p *Publisher) workspaceSkew(lease *WorkspaceLease) time.Duration { return skew } -func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { - if err := ctx.Err(); err != nil { - return WorkspaceLease{}, err - } - p.mu.Lock() - defer p.mu.Unlock() - _, line, ok := p.workspaceLineLocked(volume) - if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch { - return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority") - } - s := cloneWorkspace(p.workspace[volume]) - if s == nil { - s = &WorkspaceState{} - } - if len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued { - return WorkspaceLease{}, fmt.Errorf("workspace lease: move pending") - } - now := p.workspaceNow() - if s.Lease != nil { - if s.Lease.Revoking { - return *s.Lease, nil - } // tell the host to drain; never extend - if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.workspaceLeaseDeadline[volume]) { - return WorkspaceLease{}, fmt.Errorf("workspace lease expired or revoking") - } - } - lease := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(s.Lease))} - s.Lease = &lease - if err := p.persistWorkspaceLocked(volume, s); err != nil { - return WorkspaceLease{}, err - } - p.workspaceLeaseDeadline[volume] = now.Add(p.workspaceTTL) - return lease, nil -} - // Replica IDs are logical assignment identities; HEAD.Holder is qualified // as / and is checked separately against ExpectedHost. type WorkspaceMoveRequest struct { @@ -246,7 +211,7 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a return fmt.Errorf("workspace revoke ACK: stale or unsolicited") } now := p.workspaceNow() - if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.workspaceLeaseDeadline[volume]) { + if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.leaseDeadlineLocked(volume)) { return fmt.Errorf("workspace revoke ACK: lease expired; forced move required") } if s.Ack != nil && *s.Ack != ack { @@ -286,10 +251,12 @@ func (p *Publisher) persistWorkspaceLocked(volume string, s *WorkspaceState) err WriteSeq: p.writeSeqByVolume[volume] + 1, Workspace: cloneWorkspace(s)} if err := p.store.Put(record); err != nil { p.workspaceUncertain[volume] = true + p.refreshLeaseViewLocked(volume) return err } p.writeSeqByVolume[volume] = record.WriteSeq p.workspace[volume] = cloneWorkspace(s) + p.refreshLeaseViewLocked(volume) return nil } @@ -316,7 +283,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra if q.Kind == "forced" { now := p.workspaceNow() skew := p.workspaceSkew(s.Lease) - if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(p.workspaceLeaseDeadline[q.VolumeID].Add(skew)) { + if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(p.leaseDeadlineLocked(q.VolumeID).Add(skew)) { return nil, 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") } } diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go new file mode 100644 index 0000000000..ee90181d43 --- /dev/null +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -0,0 +1,984 @@ +package authority + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// GREEN-gating controls for the #205 fix (design r1 section 8). + +// hookStore runs before (an error is a known no-write) and after (an error +// after the real Put is an unknown outcome: the record landed) hooks. +type hookStore struct { + AuthorityStore + before atomic.Pointer[func(DurableRecord) error] + after atomic.Pointer[func(DurableRecord) error] +} + +func (s *hookStore) Put(r DurableRecord) error { + if f := s.before.Load(); f != nil { + if err := (*f)(r); err != nil { + return err + } + } + if err := s.AuthorityStore.Put(r); err != nil { + return err + } + if f := s.after.Load(); f != nil { + return (*f)(r) + } + return nil +} + +func (s *hookStore) setBefore(f func(DurableRecord) error) { s.before.Store(&f) } +func (s *hookStore) setAfter(f func(DurableRecord) error) { s.after.Store(&f) } + +// isExtension reports a lease write that raises the horizon above firstH and +// is not a revocation: the extender's write. +func isExtension(r DurableRecord, volume string, firstH int64) bool { + return r.VolumeID == volume && r.Workspace != nil && r.Workspace.Lease != nil && !r.Workspace.Lease.Revoking && r.Workspace.Lease.ExpiresAtNS > firstH +} + +type testClock struct{ ns atomic.Int64 } + +func newTestClock() *testClock { + c := &testClock{} + c.ns.Store(time.Unix(1000, 0).UnixNano()) + return c +} +func (c *testClock) now() time.Time { return time.Unix(0, c.ns.Load()) } +func (c *testClock) at(sec float64) { + c.ns.Store(time.Unix(1000, 0).Add(time.Duration(sec * float64(time.Second))).UnixNano()) +} +func (c *testClock) sec(sec float64) time.Time { + return time.Unix(1000, 0).Add(time.Duration(sec * float64(time.Second))) +} + +// newLeasePublisher joins extenders on cleanup, before the store closes +// (newTempStore registers its Close first, so it runs later). +func newLeasePublisher(t *testing.T, store AuthorityStore, ttl time.Duration, c *testClock) *Publisher { + t.Helper() + p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(ttl, c.now)) + t.Cleanup(p.CloseWorkspaceExtenders) + return p +} + +func bindAndGrant(t *testing.T, p *Publisher, volume, replica string) WorkspaceLease { + t.Helper() + if err := p.apply(AssignmentAsk{VolumeID: volume, ReplicaID: replica, DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + l, err := p.RenewWorkspaceLease(context.Background(), volume, replica, 1) + if err != nil { + t.Fatal(err) + } + return l +} + +// waitExtenders joins every admitted extender (tests only; no concurrent +// admission while waiting). +func waitExtenders(t *testing.T, p *Publisher) { + t.Helper() + done := make(chan struct{}) + go func() { p.extWG.Wait(); close(done) }() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("extenders did not finish") + } +} + +// assertLeaseViewMatches checks INV-LEASE-VIEW-001: with p.mu held, every +// volume's view equals derive(published state). +func assertLeaseViewMatches(t *testing.T, p *Publisher, what string) { + t.Helper() + p.mu.Lock() + defer p.mu.Unlock() + vols := map[string]bool{} + for k := range p.state { + vols[k.volumeID] = true + } + for v := range p.workspace { + vols[v] = true + } + for v := range p.workspaceUncertain { + vols[v] = true + } + p.leaseMu.Lock() + for v := range p.leaseViews { + vols[v] = true + } + p.leaseMu.Unlock() + for v := range vols { + want := p.deriveLeaseLocked(v) + p.leaseMu.Lock() + var got leaseDerived + if lv := p.leaseViews[v]; lv != nil { + got = lv.d + } + p.leaseMu.Unlock() + if got != want { + t.Fatalf("%s: INV-LEASE-VIEW-001 broken for %s:\n view %+v\n derive %+v", what, v, got, want) + } + } +} + +func forcedMove(volume, id string) (WorkspaceMoveRequest, WorkspaceHead) { + return WorkspaceMoveRequest{RequestID: id, VolumeID: volume, ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}, + WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42} +} + +// The view equals derive(published) after every writer kind: bind, first +// grant, extension, endpoint refresh, revocation, ACK, clean move issue, a +// move reservation whose issue write fails (uncertain via apply), a failed +// extension (uncertain via persistWorkspaceLocked), reload and close. +func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + check := func(what string) { t.Helper(); assertLeaseViewMatches(t, p, what) } + ctx := context.Background() + check("empty") + for _, v := range []string{"v", "w", "x"} { + if err := p.apply(AssignmentAsk{VolumeID: v, ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + } + check("bind") + if err := p.apply(AssignmentAsk{VolumeID: "x", ReplicaID: "r", DataAddr: "d1", CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err != nil { + t.Fatal(err) + } + check("endpoint refresh, not enrolled") + for _, v := range []string{"v", "w", "x"} { + if _, err := p.RenewWorkspaceLease(ctx, v, "r", 1); err != nil { + t.Fatal(err) + } + } + check("first grants") + firstH := p.WorkspaceState("v").Lease.ExpiresAtNS + c.at(10) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + waitExtenders(t, p) + if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != c.sec(55).UnixNano() || got <= firstH { + t.Fatalf("extension did not publish trigger+1.5*TTL: %d", got) + } + check("extension") + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d2", CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err != nil { + t.Fatal(err) + } + check("endpoint refresh, enrolled") + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + check("revocation") + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil { + t.Fatal(err) + } + check("ack") + clean := WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} + if _, err := p.MoveWorkspace(ctx, clean, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42, Detached: true}); err != nil { + t.Fatal(err) + } + check("clean move issued") + if p.leaseDeadlineLockedForTest("v") != (time.Time{}) { + t.Fatal("move issue kept the old deadline") + } + // w: forced move whose issue write fails after the reservation persisted. + c.at(30 + 15 + 20 + 1) // past w's horizon (45) + skew (20) + hs.setBefore(func(r DurableRecord) error { + if r.VolumeID == "w" && r.Workspace != nil && len(r.Workspace.Moves) > 0 && r.Workspace.Moves[len(r.Workspace.Moves)-1].Issued { + return errors.New("injected issue write failure") + } + return nil + }) + q, h := forcedMove("w", "forced-w") + if _, err := p.MoveWorkspace(ctx, q, h); err == nil { + t.Fatal("injected issue failure ignored") + } + check("move reservation, failed issue (uncertain via apply)") + if st := p.WorkspaceState("w"); len(st.Moves) != 1 || st.Moves[0].Issued { + t.Fatalf("reservation not published: %+v", st) + } + // x: a failed extension latches uncertainty. + c.at(0) + p2Disk, _ := newTempStore(t) + hs2 := &hookStore{AuthorityStore: p2Disk} + p2 := newLeasePublisher(t, hs2, 30*time.Second, c) + bindAndGrant(t, p2, "x", "r") + firstX := p2.WorkspaceState("x").Lease.ExpiresAtNS + hs2.setBefore(func(r DurableRecord) error { + if isExtension(r, "x", firstX) { + return errors.New("injected extension write failure") + } + return nil + }) + c.at(10) + if _, err := p2.RenewWorkspaceLease(ctx, "x", "r", 1); err != nil { + t.Fatal(err) + } + waitExtenders(t, p2) + assertLeaseViewMatches(t, p2, "failed extension (uncertain via persistWorkspaceLocked)") + if !p2.workspaceUncertainForTest("x") { + t.Fatal("failed extension did not latch uncertainty") + } + p.CloseWorkspaceExtenders() + check("close") + reloaded := newLeasePublisher(t, disk, 30*time.Second, c) + assertLeaseViewMatches(t, reloaded, "reload") +} + +func (p *Publisher) leaseDeadlineLockedForTest(v string) time.Time { + p.mu.Lock() + defer p.mu.Unlock() + return p.leaseDeadlineLocked(v) +} + +func (p *Publisher) workspaceUncertainForTest(v string) bool { + p.mu.Lock() + defer p.mu.Unlock() + return p.workspaceUncertain[v] +} + +// Control 1: with the store stalled for good, grants shrink to the durable +// horizon, a renewal that would leave no host validity is refused, and a +// renewal at the horizon is refused. The stall is exercised by the extender +// (puts > 0), so a green cannot bypass it. +func TestWorkspaceLeaseClampsToHorizonUnderStalledStore(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + horizon := p.WorkspaceState("v").Lease.ExpiresAtNS // 1045 + var puts atomic.Int64 + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + hs.setBefore(func(r DurableRecord) error { + if isExtension(r, "v", horizon) { + puts.Add(1) + enterOnce.Do(func() { close(entered) }) + <-release + } + return nil + }) + t.Cleanup(func() { releaseOnce.Do(func() { close(release) }) }) // before Close joins + ctx := context.Background() + c.at(10) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("extender never reached the store") + } + c.at(20) + start := time.Now() + l, err := p.RenewWorkspaceLease(ctx, "v", "r", 1) + if err != nil { + t.Fatal(err) + } + if took := time.Since(start); took > time.Second { + t.Fatalf("renewal waited %s behind the stalled extender", took) + } + if l.ExpiresAtNS > horizon { + t.Fatalf("grant %s beyond the durable horizon %s", time.Unix(0, l.ExpiresAtNS), time.Unix(0, horizon)) + } + if l.ExpiresAtNS != horizon { + t.Fatalf("grant not clamped to the horizon: %s", time.Unix(0, l.ExpiresAtNS)) + } + c.at(35) // horizon - skew/2 = 1035: no positive host validity + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil || !strings.Contains(err.Error(), "no host validity") { + t.Fatalf("renewal without host validity: %v", err) + } + c.at(45) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil { + t.Fatal("renewal at the durable horizon accepted") + } + if puts.Load() == 0 { + t.Fatal("the stall was never exercised by an extender write") + } +} + +// Control 2: a restarted master honours the persisted (extended) horizon in +// the forced barrier: max(horizon, restart+TTL) + skew. +func TestWorkspaceRestartForcedBarrierHonoursHorizon(t *testing.T) { + disk, _ := newTempStore(t) + c := newTestClock() + p := newLeasePublisher(t, disk, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + c.at(10) + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal(err) + } + waitExtenders(t, p) + if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != c.sec(55).UnixNano() { + t.Fatalf("extension not durable: %s", time.Unix(0, got)) + } + p.CloseWorkspaceExtenders() + c.at(12) + r := newLeasePublisher(t, disk, 30*time.Second, c) // reload deadline 1042 < horizon 1055 + q, h := forcedMove("v", "forced") + c.ns.Store(c.sec(75).UnixNano() - 1) + if _, err := r.MoveWorkspace(context.Background(), q, h); err == nil { + t.Fatal("forced move before persisted horizon + skew after restart") + } + c.at(75) + if _, err := r.MoveWorkspace(context.Background(), q, h); err != nil { + t.Fatal("forced move at horizon + skew refused:", err) + } +} + +// Control 3: an extension whose rename landed but whose directory sync +// failed is an unknown write: the volume is uncertain, the next renewal is +// refused (INV-AUTH-UNCERTAIN-001), and a reload finds the landed horizon and +// bars a forced move until that horizon + skew. +func TestWorkspaceAmbiguousExtensionLatchesUncertainty(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + first := p.WorkspaceState("v").Lease.ExpiresAtNS + hs.setAfter(func(r DurableRecord) error { + if isExtension(r, "v", first) { + return errors.New("injected: directory sync failed after rename") + } + return nil + }) + c.at(10) + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal(err) + } + waitExtenders(t, p) + if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != first { + t.Fatalf("an unknown write was published: %s", time.Unix(0, got)) + } + c.at(11) + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil || !strings.Contains(err.Error(), "uncertain") { + t.Fatalf("renewal after an unknown write: %v; want refused as uncertain", err) + } + // INV-AUTH-UNCERTAIN-001: every further authority change of the volume + // is refused until a restart. + if err := p.BeginWorkspaceRevocation(context.Background(), "v", "r", 1); err == nil { + t.Fatal("revocation accepted on an uncertain volume") + } + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d2", CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err == nil { + t.Fatal("authority change accepted on an uncertain volume") + } + p.CloseWorkspaceExtenders() + c.at(12) + r := newLeasePublisher(t, disk, 30*time.Second, c) + landed := r.WorkspaceState("v").Lease.ExpiresAtNS + if landed != c.sec(55).UnixNano() { + t.Fatalf("reload did not find the landed horizon: %s", time.Unix(0, landed)) + } + q, h := forcedMove("v", "forced") + c.ns.Store(time.Unix(0, landed).Add(20*time.Second).UnixNano() - 1) + if _, err := r.MoveWorkspace(context.Background(), q, h); err == nil { + t.Fatal("forced move before the landed horizon + skew") + } + c.ns.Store(time.Unix(0, landed).Add(20 * time.Second).UnixNano()) + if _, err := r.MoveWorkspace(context.Background(), q, h); err != nil { + t.Fatal(err) + } +} + +// Control 4: an extender held inside its Put holds p.mu; a revocation or a +// forced move of the same volume waits, then runs after the extension is +// published, so its record carries the extended horizon (ordered). +func TestWorkspaceExtenderHeldOrdersSameVolumeWriters(t *testing.T) { + for _, op := range []string{"revocation", "forced-move"} { + t.Run(op, func(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + first := p.WorkspaceState("v").Lease.ExpiresAtNS + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + releaseFn := func() { releaseOnce.Do(func() { close(release) }) } + hs.setBefore(func(r DurableRecord) error { + if isExtension(r, "v", first) { + enterOnce.Do(func() { close(entered) }) + <-release + } + return nil + }) + done := make(chan error, 1) + started := false + // Installed before the extender is triggered: on any failure the + // held write is released and the writer settled (bounded) before + // the publisher joins its extenders and the store closes. + t.Cleanup(func() { + releaseFn() + if started { + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("writer did not settle") + } + } + }) + c.at(10) + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal(err) + } + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("extender never reached the store") + } + started = true + if op == "revocation" { + go func() { done <- p.BeginWorkspaceRevocation(context.Background(), "v", "r", 1) }() + } else { + c.at(66) // past the OLD barrier max(1045, 1040) + 20 + q, h := forcedMove("v", "forced") + go func() { _, err := p.MoveWorkspace(context.Background(), q, h); done <- err }() + } + select { + case err := <-done: + done <- err // keep it for the cleanup join + t.Fatalf("%s ran while the extender held p.mu: %v", op, err) + case <-time.After(200 * time.Millisecond): + } + releaseFn() + var err error + select { + case err = <-done: + done <- err + case <-time.After(5 * time.Second): + t.Fatalf("%s did not finish after the extender", op) + } + want := c.sec(55).UnixNano() + st := p.WorkspaceState("v") + if op == "revocation" { + if err != nil || st.Lease == nil || !st.Lease.Revoking || st.Lease.ExpiresAtNS != want { + t.Fatalf("revocation not ordered after the extension: %v %+v", err, st.Lease) + } + } else if err == nil || len(st.Moves) != 0 || st.Lease.ExpiresAtNS != want { + t.Fatalf("forced move did not see the extended horizon: %v %+v", err, st) + } + p.CloseWorkspaceExtenders() + r := newLeasePublisher(t, disk, 30*time.Second, c) + if got := r.WorkspaceState("v").Lease; got.ExpiresAtNS != want || got.Revoking != (op == "revocation") { + t.Fatalf("reload: %+v", got) + } + }) + } +} + +// Control 5: a renewal of the same volume during a held revocation write sees +// the last published state (a grant under the horizon), then the revoking +// lease with the granted expiry and no extension. During a held forced-move +// write (barrier passed) a renewal is refused. +func TestWorkspaceSameVolumeRenewalDuringHeldWrite(t *testing.T) { + t.Run("revocation", func(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + horizon := p.WorkspaceState("v").Lease.ExpiresAtNS + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + releaseFn := func() { releaseOnce.Do(func() { close(release) }) } + hs.setBefore(func(r DurableRecord) error { + if r.VolumeID == "v" && r.Workspace != nil && r.Workspace.Lease != nil && r.Workspace.Lease.Revoking { + enterOnce.Do(func() { close(entered) }) + <-release + } + return nil + }) + done := make(chan error, 1) + go func() { done <- p.BeginWorkspaceRevocation(context.Background(), "v", "r", 1) }() + t.Cleanup(func() { + releaseFn() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("revocation did not settle") + } + }) + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("revocation write never reached the store") + } + c.at(5) + l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1) + if err != nil || l.Revoking || l.ExpiresAtNS != c.sec(35).UnixNano() || l.ExpiresAtNS > horizon { + t.Fatalf("renewal during the held revocation write: %+v %v", l, err) + } + releaseFn() + select { + case err := <-done: + done <- err + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("revocation did not finish after the release") + } + for _, at := range []float64{6, 7} { + c.at(at) + l, err = p.RenewWorkspaceLease(context.Background(), "v", "r", 1) + if err != nil || !l.Revoking || l.ExpiresAtNS != c.sec(35).UnixNano() { + t.Fatalf("revoking renewal at %v: %+v %v; want the granted expiry, never extended", at, l, err) + } + } + }) + t.Run("forced-move", func(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + releaseFn := func() { releaseOnce.Do(func() { close(release) }) } + hs.setBefore(func(r DurableRecord) error { + if r.VolumeID == "v" && r.Workspace != nil && len(r.Workspace.Moves) > 0 && !r.Workspace.Moves[len(r.Workspace.Moves)-1].Issued { + enterOnce.Do(func() { close(entered) }) + <-release + } + return nil + }) + c.at(66) // past horizon 1045 + skew 20 + q, h := forcedMove("v", "forced") + done := make(chan error, 1) + go func() { _, err := p.MoveWorkspace(context.Background(), q, h); done <- err }() + t.Cleanup(func() { + releaseFn() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("forced move did not settle") + } + }) + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("move reservation write never reached the store") + } + start := time.Now() + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil { + t.Fatal("renewal granted during a forced move past the barrier") + } + if took := time.Since(start); took > time.Second { + t.Fatalf("renewal waited %s on the held move", took) + } + releaseFn() + select { + case err := <-done: + done <- err + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("forced move did not finish after the release") + } + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil { + t.Fatal("old-epoch renewal after the move") + } + }) +} + +// Control 7 (run with -race): N volumes renew while apply, revocation, ACK, +// a clean move, a forced move, extenders and Close run. A bounded handshake +// holds the first horizon-extension write inside the store while renewals +// keep succeeding and the writers and Close are in flight (queued on the +// publisher lock behind it); then it is released. Required afterwards: every +// eligible volume had successful grants, at least one extension write was +// observed (classified by content: a raised horizon at the same epoch, not +// an ordinary writer's record), no renewal waited 2 s, nothing deadlocked, +// every live lease keeps disk >= published horizon >= every grant (S1), and +// the view equals derive. +func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { + const n = 8 + vol := func(i int) string { return fmt.Sprintf("v%d", i) } + const forcedVol, cleanVol = 2, 1 + eligible := []int{0, 3, 4, 5, 6, 7} // stay leased throughout; v0 also takes endpoint refreshes + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + + // Extension classification and the overlap hold. + var classMu sync.Mutex + lastH := map[string]int64{} + lastEpoch := map[string]uint64{} + var extensions atomic.Int64 + heldEntered, heldRelease := make(chan struct{}), make(chan struct{}) + var holdOnce, releaseOnce sync.Once + releaseHold := func() { releaseOnce.Do(func() { close(heldRelease) }) } + var classifying atomic.Bool + hs.setBefore(func(r DurableRecord) error { + time.Sleep(5 * time.Millisecond) // a slow store + if !classifying.Load() || r.Workspace == nil || r.Workspace.Lease == nil { + return nil + } + l := r.Workspace.Lease + pending := len(r.Workspace.Moves) > 0 && !r.Workspace.Moves[len(r.Workspace.Moves)-1].Issued + classMu.Lock() + ext := !l.Revoking && !pending && l.Epoch == lastEpoch[r.VolumeID] && l.ExpiresAtNS > lastH[r.VolumeID] + if ext { + lastH[r.VolumeID] = l.ExpiresAtNS + } + classMu.Unlock() + if ext { + extensions.Add(1) + first := false + holdOnce.Do(func() { first = true }) + if first { + close(heldEntered) + <-heldRelease + } + } + return nil + }) + // The publisher clock is real time plus an offset. The forced-move volume + // is granted at offset -10 s, so by offset 0 its horizon + skew barrier has + // passed; the clock only moves forward. + var offNS atomic.Int64 + offNS.Store(int64(-10 * time.Second)) + p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, func() time.Time { return time.Now().Add(time.Duration(offNS.Load())) })) + t.Cleanup(p.CloseWorkspaceExtenders) + ctx := context.Background() + bindAndGrant(t, p, vol(forcedVol), "r") // never renewed again + offNS.Store(0) + for i := 0; i < n; i++ { + if i != forcedVol { + bindAndGrant(t, p, vol(i), "r") + } + } + for i := 0; i < n; i++ { + st := p.WorkspaceState(vol(i)) + lastH[vol(i)], lastEpoch[vol(i)] = st.Lease.ExpiresAtNS, st.Lease.Epoch + } + classifying.Store(true) + + var grants [n]atomic.Int64 + var maxGrant [n]atomic.Int64 + var slowest atomic.Int64 + stop := make(chan struct{}) + var stopOnce sync.Once + stopRenewers := func() { stopOnce.Do(func() { close(stop) }) } + var wg sync.WaitGroup + writersDone := make(chan error, 1) + closed := make(chan struct{}) + writersStarted, closeStarted := false, false + // Bounded cleanup on every path: release the hold, stop renewers, settle + // every worker, and only then let the fixtures close. + t.Cleanup(func() { + releaseHold() + stopRenewers() + settled := make(chan struct{}) + go func() { wg.Wait(); close(settled) }() + select { + case <-settled: + case <-time.After(10 * time.Second): + t.Error("renewers did not settle") + } + if writersStarted { + select { + case <-writersDone: + case <-time.After(10 * time.Second): + t.Error("writers did not settle") + } + } + if closeStarted { + select { + case <-closed: + case <-time.After(10 * time.Second): + t.Error("Close did not settle") + } + } + }) + for _, i := range append(append([]int{}, eligible...), cleanVol) { + wg.Add(1) + go func(i int) { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + start := time.Now() + l, err := p.RenewWorkspaceLease(ctx, vol(i), "r", 1) + if d := int64(time.Since(start)); d > slowest.Load() { + slowest.Store(d) + } + if err == nil && !l.Revoking { + grants[i].Add(1) + if l.ExpiresAtNS > maxGrant[i].Load() { + maxGrant[i].Store(l.ExpiresAtNS) + } + } + time.Sleep(5 * time.Millisecond) + } + }(i) + } + + // Handshake 1: the first extension write is held inside the store. + select { + case <-heldEntered: + case <-time.After(5 * time.Second): + t.Fatal("no horizon-extension write reached the store within 5 s") + } + // Handshake 2: renewals keep succeeding while it is held. + var atHold [n]int64 + for _, i := range eligible { + atHold[i] = grants[i].Load() + } + for wait := time.Now().Add(2 * time.Second); ; time.Sleep(5 * time.Millisecond) { + all := true + for _, i := range eligible { + if grants[i].Load() <= atHold[i] { + all = false + } + } + if all { + break + } + if time.Now().After(wait) { + t.Fatal("renewals did not succeed while an extension write was held") + } + } + // Writers and Close start while the extension write is held. + writersStarted = true + go func() { + for k := 0; k < 5; k++ { + if err := p.apply(AssignmentAsk{VolumeID: vol(0), ReplicaID: "r", DataAddr: fmt.Sprintf("d%d", k), CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err != nil { + writersDone <- fmt.Errorf("endpoint refresh: %w", err) + return + } + } + if err := p.BeginWorkspaceRevocation(ctx, vol(cleanVol), "r", 1); err != nil { + writersDone <- fmt.Errorf("revocation: %w", err) + return + } + if err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil { + writersDone <- fmt.Errorf("ack: %w", err) + return + } + clean := WorkspaceMoveRequest{RequestID: "clean", VolumeID: vol(cleanVol), ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} + if _, err := p.MoveWorkspace(ctx, clean, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42, Detached: true}); err != nil { + writersDone <- fmt.Errorf("clean move: %w", err) + return + } + q, h := forcedMove(vol(forcedVol), "forced") + if _, err := p.MoveWorkspace(ctx, q, h); err != nil { + writersDone <- fmt.Errorf("forced move: %w", err) + return + } + writersDone <- nil + }() + closeStarted = true + go func() { p.CloseWorkspaceExtenders(); close(closed) }() + select { + case err := <-writersDone: + writersDone <- err // keep it for the cleanup join + t.Fatalf("writers finished while the extension write held the publisher lock: %v", err) + case <-closed: + t.Fatal("Close finished while an extension write was held") + case <-time.After(150 * time.Millisecond): + } + releaseHold() + var werr error + select { + case werr = <-writersDone: + writersDone <- werr // keep it for the cleanup join + case <-time.After(20 * time.Second): + t.Fatal("deadlock: writers did not finish after the release") + } + if werr != nil { + t.Fatal("writer:", werr) + } + select { + case <-closed: + case <-time.After(20 * time.Second): + t.Fatal("deadlock: Close did not finish after the release") + } + time.Sleep(50 * time.Millisecond) // renewals continue after Close + stopRenewers() + settled := make(chan struct{}) + go func() { wg.Wait(); close(settled) }() + select { + case <-settled: + case <-time.After(20 * time.Second): + t.Fatal("deadlock: renewers did not finish") + } + + if s := time.Duration(slowest.Load()); s >= 2*time.Second { + t.Fatalf("slowest renewal %s", s) + } + for _, i := range eligible { + if grants[i].Load() == 0 { + t.Fatalf("%s had no successful grant", vol(i)) + } + } + 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" { + 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" { + t.Fatalf("clean move not issued: %+v", st) + } + assertLeaseViewMatches(t, p, "after concurrency") + recs, err := disk.Load() + if err != nil { + t.Fatal(err) + } + onDisk := map[string]int64{} + for _, r := range recs { + if r.Workspace != nil && r.Workspace.Lease != nil { + onDisk[r.VolumeID] = r.Workspace.Lease.ExpiresAtNS + } + } + 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 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()) + } + } + t.Logf("extension writes %d; grants per eligible volume %v", extensions.Load(), func() []int64 { + out := []int64{} + for _, i := range eligible { + out = append(out, grants[i].Load()) + } + return out + }()) +} + +// Control 10a: Close waits for an extender held inside its Put; after Close +// no extension is admitted or written. +func TestWorkspaceCloseJoinsHeldExtender(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + first := p.WorkspaceState("v").Lease.ExpiresAtNS + var puts atomic.Int64 + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + releaseFn := func() { releaseOnce.Do(func() { close(release) }) } + hs.setBefore(func(r DurableRecord) error { + if isExtension(r, "v", first) { + puts.Add(1) + enterOnce.Do(func() { close(entered) }) + <-release + } + return nil + }) + closed := make(chan struct{}) + closeStarted := false + t.Cleanup(func() { // bounded: release, then settle Close before the store closes + releaseFn() + if closeStarted { + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Error("Close did not settle") + } + } + }) + c.at(10) + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal(err) + } + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("extender never reached the store") + } + closeStarted = true + go func() { p.CloseWorkspaceExtenders(); close(closed) }() + select { + case <-closed: + t.Fatal("Close returned while an extender was inside its write") + case <-time.After(200 * time.Millisecond): + } + releaseFn() + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Fatal("Close did not return after the extender finished") + } + before := puts.Load() + c.at(20) // would trigger an extension (horizon 1055 < 1020 + 37.5) + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal(err) + } + waitExtenders(t, p) + if puts.Load() != before { + t.Fatal("an extension was written after Close") + } +} + +// Control 10b: an extender admitted before Close that reaches p.mu after +// closing is set aborts with a known no-write. The test holds p.mu itself, so +// the renewal also shows it never needs p.mu. +func TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + first := p.WorkspaceState("v").Lease.ExpiresAtNS + var puts atomic.Int64 + hs.setBefore(func(r DurableRecord) error { + if isExtension(r, "v", first) { + puts.Add(1) + } + return nil + }) + c.at(10) + p.mu.Lock() + renewed := make(chan error, 1) + go func() { _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); renewed <- err }() + select { + case err := <-renewed: + if err != nil { + p.mu.Unlock() + t.Fatal(err) + } + case <-time.After(2 * time.Second): + p.mu.Unlock() + t.Fatal("renewal waited on p.mu") + } + p.leaseMu.Lock() + admitted := p.leaseViews["v"].extending + p.leaseClosing = true // Close's first step, while the extender waits for p.mu + p.leaseMu.Unlock() + p.mu.Unlock() + if !admitted { + t.Fatal("no extender was admitted") + } + waitExtenders(t, p) + if puts.Load() != 0 || p.WorkspaceState("v").Lease.ExpiresAtNS != first { + t.Fatal("an extender admitted before closing wrote after closing") + } + p.leaseMu.Lock() + extending := p.leaseViews["v"].extending + p.leaseMu.Unlock() + if extending { + t.Fatal("aborted extender left the single-flight flag set") + } +} diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go new file mode 100644 index 0000000000..bed676e893 --- /dev/null +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -0,0 +1,310 @@ +package authority + +import ( + "context" + "fmt" + "log" + "time" +) + +// leaseDerived is the part of a volume's lease view that is a pure function +// of published publisher state (derive). Writers recompute it under +// p.mu -> leaseMu at every point where an input changes, so that whenever +// p.mu is released the view equals derive(published) (INV-LEASE-VIEW-001). +type leaseDerived struct { + bound bool // an authority line exists for the volume + replica string + epoch uint64 + leasePresent bool + revoking bool + movePending bool // the last workspace move is reserved, not issued + uncertain bool // a workspace write of the volume failed (INV-AUTH-UNCERTAIN-001) + storeless bool + horizon int64 // published Lease.ExpiresAtNS: durable upper bound of every grant + maxSkewNS int64 + lease WorkspaceLease // the published (durable) lease +} + +// leaseView is one volume's renewal state. Guarded by Publisher.leaseMu. +// deadline (the latest grant, or the restart rule's now+TTL) and extending +// are owned by the view; d is derived. +type leaseView struct { + d leaseDerived + deadline time.Time + extending bool + clamped bool // a renewal was clamped below now+TTL; logged once per streak +} + +// deriveLeaseLocked computes the derived lease view from published state. +// Caller holds p.mu. +func (p *Publisher) deriveLeaseLocked(volume string) leaseDerived { + d := leaseDerived{uncertain: p.workspaceUncertain[volume], storeless: p.store == nil, maxSkewNS: int64(p.workspaceSkew(nil))} + if _, line, ok := p.workspaceLineLocked(volume); ok { + d.bound, d.replica, d.epoch = true, line.info.ReplicaID, line.info.Epoch + } + if s := p.workspace[volume]; s != nil { + d.movePending = len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued + if s.Lease != nil { + d.leasePresent, d.revoking, d.horizon, d.lease = true, s.Lease.Revoking, s.Lease.ExpiresAtNS, *s.Lease + d.maxSkewNS = int64(p.workspaceSkew(s.Lease)) + } + } + return d +} + +// refreshLeaseViewLocked republishes the derived view of volume. Caller holds +// p.mu; this takes leaseMu (the only p.mu -> leaseMu edge besides deadline +// reads). Called at every mutation of a derive input: the authority line, the +// published workspace state, uncertainty, and closing. +func (p *Publisher) refreshLeaseViewLocked(volume string) { + 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 +} + +// leaseDeadlineLocked reads the granted deadline. Caller holds p.mu. +func (p *Publisher) leaseDeadlineLocked(volume string) time.Time { + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + if lv := p.leaseViews[volume]; lv != nil { + return lv.deadline + } + return time.Time{} +} + +// setLeaseDeadlineLocked replaces the deadline (restart rule, move issue) 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) + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + lv := p.leaseViews[volume] + if lv == nil { + lv = &leaseView{d: d} + p.leaseViews[volume] = lv + } + if !raise || t.After(lv.deadline) { + lv.deadline = t + } +} + +// replyExpiryNS is the expiry reported to a host: never the raw durable +// horizon, only what was granted (min(horizon, deadline)). +func (lv *leaseView) replyExpiryNS() int64 { + if lv.deadline.IsZero() { + return lv.d.horizon // unreachable: a published lease always has a deadline + } + if dl := lv.deadline.UnixNano(); dl < lv.d.horizon { + return dl + } + return lv.d.horizon +} + +// WorkspaceLeaseReply returns the published lease with its expiry clamped to +// what was granted (min(durable horizon, granted deadline)), for replies that +// report a lease to a host or operator. ok is false without a lease. +func (p *Publisher) WorkspaceLeaseReply(volume string) (WorkspaceLease, bool) { + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + lv := p.leaseViews[volume] + if lv == nil || !lv.d.leasePresent { + return WorkspaceLease{}, false + } + l := lv.d.lease + l.ExpiresAtNS = lv.replyExpiryNS() + return l, true +} + +// RenewWorkspaceLease answers a live holder from memory: it takes only the +// leaf leaseMu, does no I/O and never waits on p.mu or the store. The grant +// is min(now+TTL, durable horizon); a background extender (an ordinary p.mu +// writer) pushes the horizon ahead. Only the first grant of a lease writes +// synchronously (firstWorkspaceGrant). +func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { + if err := ctx.Err(); err != nil { + return WorkspaceLease{}, err + } + p.leaseMu.Lock() + now := p.workspaceNow() // read under leaseMu: the forced-barrier argument needs it + lv := p.leaseViews[volume] + if lv == nil || !lv.d.bound || lv.d.replica != holder || lv.d.epoch != epoch { + p.leaseMu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority") + } + if lv.d.movePending { + p.leaseMu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease: move pending") + } + if !lv.d.leasePresent { + p.leaseMu.Unlock() // never re-enter p.mu while holding the leaf + return p.firstWorkspaceGrant(ctx, volume, holder, epoch) + } + if lv.d.revoking { // tell the host to drain; never extend + l := lv.d.lease + l.ExpiresAtNS = lv.replyExpiryNS() + p.leaseMu.Unlock() + return l, nil + } + if now.UnixNano() >= lv.d.horizon || !now.Before(lv.deadline) { + p.leaseMu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease expired or revoking") + } + // Where the synchronous write used to refuse (persistWorkspaceLocked): + // a renewal never bypasses uncertainty (INV-AUTH-UNCERTAIN-001). + if lv.d.storeless || lv.d.uncertain { + p.leaseMu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain") + } + grant := now.Add(p.workspaceTTL).UnixNano() + clamped := grant > lv.d.horizon + if clamped { + grant = lv.d.horizon + } + // A grant without positive host validity (expiry minus half the skew + // bound, leaseFact) would make the host fence on an invalid reply and lose + // its remaining validity; refuse with an error instead. + if grant-lv.d.maxSkewNS/2 <= now.UnixNano() { + p.leaseMu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano)) + } + if g := time.Unix(0, grant); g.After(lv.deadline) { + lv.deadline = g + } + var note string + switch { + case clamped && !lv.clamped: + lv.clamped = true + note = fmt.Sprintf("workspace lease: grants of volume=%s are clamped to the durable horizon %s (%s remaining); extensions are behind", + volume, time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano), time.Duration(lv.d.horizon-now.UnixNano()).Round(time.Millisecond)) + case !clamped && lv.clamped: + lv.clamped = false + note = fmt.Sprintf("workspace lease: grants of volume=%s are no longer clamped (horizon %s)", volume, time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano)) + } + if lv.d.horizon < now.Add(p.workspaceTTL+p.workspaceTTL/4).UnixNano() && !lv.extending && !p.leaseClosing { + lv.extending = true + p.extWG.Add(1) // under leaseMu with !closing: no Add can follow CloseWorkspaceExtenders + go p.extendWorkspaceLease(volume, holder, epoch, now) + } + l := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS} + p.leaseMu.Unlock() + if note != "" { + log.Print(note) + } + return l, nil +} + +// firstWorkspaceGrant creates a lease synchronously under p.mu (one write per +// assignment epoch). 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() + _, line, ok := p.workspaceLineLocked(volume) + if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch { + p.mu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority") + } + s := cloneWorkspace(p.workspace[volume]) + if s == nil { + s = &WorkspaceState{} + } + if len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued { + p.mu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease: move pending") + } + if s.Lease != nil { + // Another writer created the lease after the view was read. Do not + // re-enter the memory path from here (no mutual recursion): the host has + // no deadline yet, so a failed first renewal does not fence it, and its + // retry takes the memory path. + 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} + 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 +} + +// extendWorkspaceLease is an ordinary writer: under p.mu it rechecks the +// lease and writes horizon H = trigger + 1.5*TTL through +// persistWorkspaceLocked, so its write and its publication are one p.mu +// section. Any write error is an unknown write and latches uncertainty +// (INV-AUTH-UNCERTAIN-001); a failed recheck is a known no-write. +func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, trigger time.Time) { + defer p.extWG.Done() + var note string + defer func() { + if note != "" { + log.Print(note) + } + }() + p.mu.Lock() + defer p.mu.Unlock() + defer func() { + p.leaseMu.Lock() + if lv := p.leaseViews[volume]; lv != nil { + lv.extending = false + } + p.leaseMu.Unlock() + }() + p.leaseMu.Lock() + closing := p.leaseClosing + p.leaseMu.Unlock() + if closing { + return + } + _, line, ok := p.workspaceLineLocked(volume) + s := cloneWorkspace(p.workspace[volume]) + if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch || s == nil || s.Lease == nil || s.Lease.Revoking || + s.Lease.ReplicaID != holder || s.Lease.Epoch != epoch || (len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued) || + p.workspaceUncertain[volume] || p.store == nil { + return + } + h := trigger.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano() + old := s.Lease.ExpiresAtNS + if h <= old { + return + } + s.Lease.ExpiresAtNS = h + start := time.Now() + err := p.persistWorkspaceLocked(volume, s) + took := time.Since(start).Round(time.Millisecond) + if err != nil { + if p.extendFailures[volume] == 0 { + note = fmt.Sprintf("workspace lease: extension of volume=%s failed after %s (horizon %s, %s remaining); the volume is now uncertain and its renewals are refused: %v", + volume, took, time.Unix(0, old).UTC().Format(time.RFC3339Nano), time.Until(time.Unix(0, old)).Round(time.Millisecond), err) + } + p.extendFailures[volume]++ + return + } + if n := p.extendFailures[volume]; n > 0 { + note = fmt.Sprintf("workspace lease: extension of volume=%s recovered after %d failures, took %s, horizon now %s", volume, n, took, time.Unix(0, h).UTC().Format(time.RFC3339Nano)) + delete(p.extendFailures, volume) + } +} + +// CloseWorkspaceExtenders stops admitting lease extensions and joins every +// admitted extender. Owners call it before closing the authority store: +// closing is set under p.mu -> leaseMu, so an extender either finished its +// write before or sees closing and does not write. +func (p *Publisher) CloseWorkspaceExtenders() { + p.mu.Lock() + p.leaseMu.Lock() + p.leaseClosing = true + p.leaseMu.Unlock() + p.mu.Unlock() + p.extWG.Wait() +} diff --git a/seaweed-block/core/authority/workspace_renewal_slowstore_test.go b/seaweed-block/core/authority/workspace_renewal_slowstore_test.go new file mode 100644 index 0000000000..6d7ddf652e --- /dev/null +++ b/seaweed-block/core/authority/workspace_renewal_slowstore_test.go @@ -0,0 +1,209 @@ +package authority + +import ( + "context" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" +) + +// slowLeaseStore delays every workspace-lease Put once armed, standing in for +// a master disk whose fsync stalls under heavy I/O (issue #205). +type slowLeaseStore struct { + AuthorityStore + delayNS atomic.Int64 + puts atomic.Int64 // delayed (armed) lease writes: proves the stall was exercised +} + +func (s *slowLeaseStore) Put(r DurableRecord) error { + if d := time.Duration(s.delayNS.Load()); d > 0 && r.Workspace != nil && r.Workspace.Lease != nil { + s.puts.Add(1) + time.Sleep(d) + } + return s.AuthorityStore.Put(r) +} + +// A renewal of a live lease must not wait for the authority store's fsync: +// the host's renewal RPC times out after 2 s, so a slower store write on the +// renewal path turns into a host fence and a volume shutdown (issue #205). +func TestWorkspaceRenewalDoesNotWaitForSlowStore(t *testing.T) { + disk, _ := newTempStore(t) + slow := &slowLeaseStore{AuthorityStore: disk} + var nowNS atomic.Int64 + nowNS.Store(time.Unix(1000, 0).UnixNano()) + p := NewPublisher(nil, WithStore(slow), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })) + t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + first, err := p.RenewWorkspaceLease(context.Background(), "v", "old", 1) + if err != nil { + t.Fatal(err) + } + slow.delayNS.Store(int64(2500 * time.Millisecond)) + t.Cleanup(func() { slow.delayNS.Store(0) }) + nowNS.Add(int64(10 * time.Second)) + start := time.Now() + second, err := p.RenewWorkspaceLease(context.Background(), "v", "old", 1) + took := time.Since(start) + if err != nil { + t.Fatal(err) + } + if second.ExpiresAtNS <= first.ExpiresAtNS { + t.Fatalf("renewal did not extend the grant: first=%d second=%d", first.ExpiresAtNS, second.ExpiresAtNS) + } + if took >= 2*time.Second { + t.Fatalf("renewal of a live lease took %s behind a 2.5 s store write; the host's renewal RPC times out at 2 s", took.Round(time.Millisecond)) + } + t.Logf("renewal took %s", took) + waitExtenders(t, p) + if slow.puts.Load() == 0 { + t.Fatal("no lease write went through the 2.5 s stall: the test did not exercise it") + } +} + +// Renewals of different volumes must not queue behind each other's store +// writes: with six volumes and a 0.5 s write each, serializing them makes the +// last renewal wait about 3 s, past the host's 2 s renewal timeout. +func TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore(t *testing.T) { + disk, _ := newTempStore(t) + slow := &slowLeaseStore{AuthorityStore: disk} + var nowNS atomic.Int64 + nowNS.Store(time.Unix(1000, 0).UnixNano()) + p := NewPublisher(nil, WithStore(slow), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })) + t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes + const n = 6 + for i := 0; i < n; i++ { + v := fmt.Sprintf("v%d", i) + if err := p.apply(AssignmentAsk{VolumeID: v, ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(context.Background(), v, "r", 1); err != nil { + t.Fatal(err) + } + } + slow.delayNS.Store(int64(500 * time.Millisecond)) + t.Cleanup(func() { slow.delayNS.Store(0) }) + nowNS.Add(int64(10 * time.Second)) + var wg sync.WaitGroup + took := make([]time.Duration, n) + errs := make([]error, n) + gate := make(chan struct{}) + for i := 0; i < n; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + <-gate + start := time.Now() + _, errs[i] = p.RenewWorkspaceLease(context.Background(), fmt.Sprintf("v%d", i), "r", 1) + took[i] = time.Since(start) + }(i) + } + close(gate) + wg.Wait() + var slowest time.Duration + for i := 0; i < n; i++ { + if errs[i] != nil { + t.Fatalf("v%d: %v", i, errs[i]) + } + if took[i] > slowest { + slowest = took[i] + } + } + if slowest >= 2*time.Second { + t.Fatalf("slowest of %d concurrent renewals took %s (all: %v); renewals serialize behind each other's store writes", n, slowest.Round(time.Millisecond), took) + } + t.Logf("slowest of %d concurrent renewals took %s", n, slowest) + waitExtenders(t, p) + if slow.puts.Load() == 0 { + t.Fatal("no lease write went through the 0.5 s stall: the test did not exercise it") + } +} + +// heldWriteStore blocks the first Put that matches hold until release closes, +// standing in for one slow synchronous authority write. +type heldWriteStore struct { + AuthorityStore + hold func(DurableRecord) bool + once sync.Once + entered chan struct{} + release chan struct{} +} + +func (s *heldWriteStore) Put(r DurableRecord) error { + if s.hold != nil && s.hold(r) { + held := false + s.once.Do(func() { held = true }) + if held { + close(s.entered) + <-s.release + } + } + return s.AuthorityStore.Put(r) +} + +// A slow synchronous write of one volume (here the revocation of a) must not +// block the renewal of an unrelated volume b: renewal needs no write of its +// own, so it must not wait on a's store I/O (issue #205). +func TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite(t *testing.T) { + disk, _ := newTempStore(t) + held := &heldWriteStore{AuthorityStore: disk, entered: make(chan struct{}), release: make(chan struct{}), + hold: func(r DurableRecord) bool { + return r.VolumeID == "a" && r.Workspace != nil && r.Workspace.Lease != nil && r.Workspace.Lease.Revoking + }} + var nowNS atomic.Int64 + nowNS.Store(time.Unix(1000, 0).UnixNano()) + p := NewPublisher(nil, WithStore(held), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })) + t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes + for _, v := range []string{"a", "b"} { + if err := p.apply(AssignmentAsk{VolumeID: v, ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(context.Background(), v, "r", 1); err != nil { + t.Fatal(err) + } + } + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(held.release) }) } + revoked := make(chan error, 1) + go func() { revoked <- p.BeginWorkspaceRevocation(context.Background(), "a", "r", 1) }() + // Bounded cleanup: release the held write first, then settle the worker. + t.Cleanup(func() { + release() + select { + case <-revoked: + case <-time.After(5 * time.Second): + t.Error("held revocation of a did not settle within 5 s after release") + } + }) + select { + case <-held.entered: + case <-time.After(3 * time.Second): + t.Fatal("revocation of a never reached the store") + } + nowNS.Add(int64(10 * time.Second)) + renewed := make(chan error, 1) + start := time.Now() + go func() { + _, err := p.RenewWorkspaceLease(context.Background(), "b", "r", 1) + renewed <- err + }() + select { + case err := <-renewed: + if err != nil { + t.Fatalf("renewal of b: %v", err) + } + t.Logf("renewal of b took %s while a's write was held", time.Since(start)) + case <-time.After(2 * time.Second): + blocked := time.Since(start).Round(time.Millisecond) + release() + select { + case err := <-renewed: + t.Fatalf("renewal of b was still blocked %s behind the held store write of a (it returned only after a was released, err=%v)", blocked, err) + case <-time.After(5 * time.Second): + t.Fatalf("renewal of b was still blocked %s behind the held store write of a, and did not settle within 5 s after release", blocked) + } + } +} diff --git a/seaweed-block/core/authority/workspace_skew_test.go b/seaweed-block/core/authority/workspace_skew_test.go index 320d43eba8..69b4c733c6 100644 --- a/seaweed-block/core/authority/workspace_skew_test.go +++ b/seaweed-block/core/authority/workspace_skew_test.go @@ -23,7 +23,10 @@ func TestWorkspaceClockSkewPersistsAndProtectsRestart(t *testing.T) { if lease.MaxClockSkewNS != int64(4*time.Second) { t.Fatal("configured margin not in durable grant", lease) } - boundary := start.Add(10 * time.Second) + // The first grant persists the durable horizon start+1.5*TTL (9 s), + // the upper bound of every later grant; the forced barrier is + // horizon + skew, TTL/2 later than the grant itself (#205). + boundary := start.Add(9*time.Second + 4*time.Second) if restart { now = start.Add(7 * time.Second) p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(6*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(time.Second)) diff --git a/seaweed-block/core/authority/workspace_test.go b/seaweed-block/core/authority/workspace_test.go index 4873446164..39473fec1f 100644 --- a/seaweed-block/core/authority/workspace_test.go +++ b/seaweed-block/core/authority/workspace_test.go @@ -35,7 +35,8 @@ func TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant(t *testing.T) { if _, err := p.RenewWorkspaceLease(context.Background(), "v", "old", 1); err != nil { t.Fatal(err) } - now = now.Add(2 * time.Second) + // Past the durable horizon (1.5*TTL) plus skew, not only the grant (#205). + now = now.Add(3 * time.Second) req := WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42} fault.failIssue = true @@ -224,7 +225,8 @@ func TestWorkspaceMoveUsesQualifiedHEADHolder(t *testing.T) { if _, err := p.RenewWorkspaceLease(ctx, "v", "same", 1); err != nil { t.Fatal(err) } - now = now.Add(2 * time.Second) + // Past the durable horizon (1.5*TTL) plus skew, not only the grant (#205). + now = now.Add(3 * time.Second) q := WorkspaceMoveRequest{RequestID: "qualified", VolumeID: "v", ExpectedReplicaID: "same", TargetReplicaID: "same", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} for _, holder := range []string{"same", "other-node/same", "old-node/other"} { if _, err := p.MoveWorkspace(ctx, q, WorkspaceHead{Gen: 7, Epoch: 1, Holder: holder, RemoteLSN: 42}); err == nil { diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index f74dbfae99..76c8e1eb4f 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -480,5 +480,9 @@ func (h *Host) Close(ctx context.Context) error { } h.wg.Wait() + // Join lease extenders (authority writers) before the store closes. + if h.boot != nil && h.boot.Publisher != nil { + h.boot.Publisher.CloseWorkspaceExtenders() + } return h.boot.Close() } diff --git a/seaweed-block/core/host/master/workspace_binding_test.go b/seaweed-block/core/host/master/workspace_binding_test.go index 87f73e1b1d..07b3a67767 100644 --- a/seaweed-block/core/host/master/workspace_binding_test.go +++ b/seaweed-block/core/host/master/workspace_binding_test.go @@ -126,8 +126,14 @@ func workspaceBindingsMove(t *testing.T, forced bool) { t.Fatal(e) } if forced { + // The forced barrier is the durable horizon (>= every grant) plus + // skew, not the reply's grant (#205). + horizon := lease.ExpiresAtNs + if st := h.Publisher().WorkspaceState(vol); st != nil && st.Lease != nil && st.Lease.ExpiresAtNS > horizon { + horizon = st.Lease.ExpiresAtNS + } select { - case <-time.After(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 100*time.Millisecond + 20*time.Millisecond): + case <-time.After(time.Until(time.Unix(0, horizon)) + 100*time.Millisecond + 20*time.Millisecond): case <-ctx.Done(): t.Fatal(ctx.Err()) } diff --git a/seaweed-block/core/host/master/workspace_lease_horizon_test.go b/seaweed-block/core/host/master/workspace_lease_horizon_test.go new file mode 100644 index 0000000000..c0ae355df8 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_lease_horizon_test.go @@ -0,0 +1,207 @@ +package master + +import ( + "context" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// stalledGuardStore blocks every lease write once armed until release +// closes: a store that never comes back (issue #205, control 1). +type stalledGuardStore struct { + authority.AuthorityStore + armed atomic.Bool + puts atomic.Int64 + release chan struct{} +} + +func (s *stalledGuardStore) Put(r authority.DurableRecord) error { + if s.armed.Load() && r.Workspace != nil && r.Workspace.Lease != nil { + s.puts.Add(1) + <-s.release + } + return s.AuthorityStore.Put(r) +} + +// Control 1 (host side): with the master's store stalled for good, a real +// guard keeps serving on clamped grants and fences by the durable horizon +// minus half the skew bound, not earlier and not later than the horizon. +func TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore(t *testing.T) { + disk, err := authority.NewFileAuthorityStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + stall := &stalledGuardStore{AuthorityStore: disk, release: make(chan struct{})} + var inflight sync.WaitGroup + t.Cleanup(func() { + inflight.Wait() + if err := disk.Close(); err != nil { + t.Error(err) + } + }) + dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} + p := authority.NewPublisher(dir, authority.WithStore(stall), authority.WithWorkspaceLeaseConfig(3*time.Second, nil)) + seedSkewPublisher(t, p, dir) + t.Cleanup(p.CloseWorkspaceExtenders) + var releaseOnce sync.Once + t.Cleanup(func() { releaseOnce.Do(func() { close(stall.release) }) }) // runs first: unblock the extender + var stops atomic.Int32 + g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, + deadlineLeaseClient{p: p, inflight: &inflight}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, + func(context.Context) (uint64, error) { stops.Add(1); return 7, nil }, nil) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + runDone := make(chan error, 1) + go func() { runDone <- g.Run(ctx) }() + t.Cleanup(func() { + cancel() + select { + case <-runDone: + case <-time.After(10 * time.Second): + t.Error("guard did not settle") + } + }) + for wait := time.Now().Add(3 * time.Second); !g.Projection().Healthy; time.Sleep(10 * time.Millisecond) { + if time.Now().After(wait) { + t.Fatal("first grant did not arrive") + } + } + lease := p.WorkspaceState("v").Lease + horizon := time.Unix(0, lease.ExpiresAtNS) + halfSkew := time.Duration(lease.MaxClockSkewNS) / 2 + stall.armed.Store(true) + var fencedAt time.Time + for deadline := horizon.Add(2 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { + if !g.Projection().Healthy { + fencedAt = time.Now() + break + } + } + if fencedAt.IsZero() { + t.Fatalf("guard still serving 2 s past the durable horizon %s", horizon.Format(time.RFC3339Nano)) + } + if fencedAt.After(horizon.Add(300 * time.Millisecond)) { + t.Fatalf("guard fenced %s after the durable horizon", fencedAt.Sub(horizon)) + } + if early := horizon.Add(-halfSkew - 500*time.Millisecond); fencedAt.Before(early) { + t.Fatalf("guard fenced %s before horizon - skew/2: grants did not clamp to the horizon", early.Sub(fencedAt)) + } + if stall.puts.Load() == 0 { + t.Fatal("no extender write reached the stalled store") + } + t.Logf("guard fenced %s before the durable horizon (half skew %s)", horizon.Sub(fencedAt).Round(time.Millisecond), halfSkew) +} + +// Control 6a and the reply clamp: through the services layer, QueryWorkspace +// and RevokeWorkspace report the granted expiry, not the durable horizon; a +// renewal during a held reservation write of the SAME volume (revoked and +// ACKed, so deletion is admitted) returns the revoking lease without waiting, +// and once the reservation is published renewals are refused. +func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) { + h, c, ctx := reviewBindingHost(t) + reviewLegacyBind(t, h, c, ctx, "vol-b") + line := waitAuthorityLine(t, h.Publisher(), "vol-b") + svc := &services{host: h} + id := &control.WorkspaceIdentity{VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch} + first, err := svc.RenewWorkspaceLease(ctx, id) + if err != nil { + t.Fatal(err) + } + durable := h.Publisher().WorkspaceState("vol-b").Lease.ExpiresAtNS + if first.ExpiresAtNs >= durable { + t.Fatalf("fixture: grant %d not below the durable horizon %d", first.ExpiresAtNs, durable) + } + q, err := svc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-b"}) + if err != nil || q.Lease == nil || q.Lease.ExpiresAtNs != first.ExpiresAtNs { + t.Fatalf("QueryWorkspace must report the grant %d, got %+v %v", first.ExpiresAtNs, q.GetLease(), err) + } + rv, err := svc.RevokeWorkspace(ctx, id) + if err != nil || !rv.Revoking || rv.ExpiresAtNs != first.ExpiresAtNs { + t.Fatalf("RevokeWorkspace must report the grant %d, got %+v %v", first.ExpiresAtNs, rv, err) + } + if _, err := svc.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil { + t.Fatal(err) + } + deletions := h.Lifecycle().Deletions + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + releaseHook := func() { releaseOnce.Do(func() { close(release) }) } + deletions.SetPersistHookForTest(func() error { + enterOnce.Do(func() { close(entered) }) + <-release + return nil + }) + marked := make(chan error, 1) + go func() { + _, err := svc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "vol-b", Token: "tok"}) + marked <- err + }() + renewed := make(chan *control.WorkspaceLeaseFact, 1) + renewErr := make(chan error, 1) + renewStarted := false + t.Cleanup(func() { // bounded: release, settle both workers, then clear the hook + releaseHook() + settled := true + select { + case <-marked: + case <-time.After(5 * time.Second): + settled = false + t.Error("held reservation write did not settle") + } + if renewStarted { + select { + case <-renewErr: + case <-time.After(5 * time.Second): + settled = false + t.Error("renewal did not settle") + } + } + if settled { + deletions.SetPersistHookForTest(nil) + } + }) + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("reservation write of vol-b never reached the store") + } + renewStarted = true + go func() { + f, err := svc.RenewWorkspaceLease(ctx, id) + renewed <- f + renewErr <- err + }() + select { + case f := <-renewed: + err := <-renewErr + renewErr <- err + if err != nil || !f.Revoking || f.ExpiresAtNs != first.ExpiresAtNs { + t.Fatalf("renewal during the held same-volume reservation: %+v %v; want the revoking lease with the granted expiry", f, err) + } + case <-time.After(2 * time.Second): + t.Fatal("renewal waited on the held reservation write") + } + releaseHook() + select { + case err := <-marked: + marked <- err + if err != nil { + t.Fatal("mark deleting:", err) + } + case <-time.After(5 * time.Second): + t.Fatal("mark deleting did not finish") + } + if _, err := svc.RenewWorkspaceLease(ctx, id); err == nil || !strings.Contains(err.Error(), "being deleted") { + t.Fatalf("renewal after the reservation was published: %v; want refused as being deleted", err) + } +} diff --git a/seaweed-block/core/host/master/workspace_renewal_boundary_test.go b/seaweed-block/core/host/master/workspace_renewal_boundary_test.go index afab27803b..b128642338 100644 --- a/seaweed-block/core/host/master/workspace_renewal_boundary_test.go +++ b/seaweed-block/core/host/master/workspace_renewal_boundary_test.go @@ -99,10 +99,13 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) { case <-ctx.Done(): t.Fatal("renewal did not enter", ctx.Err()) } + // A renewal is answered from memory: the grant is in the reply, and + // the durable lease holds the horizon (>= every grant), so the + // persisted expiry is not the grant any more (#205). renewed := *p.WorkspaceState("v").Lease freshEarly := requestStart.Add(time.Duration(reply.ValidForNs)) - if freshEarly.Sub(oldEarly) < time.Second || renewed.ExpiresAtNS <= oldLease.ExpiresAtNS || renewed.MaxClockSkewNS != int64(4*time.Second) { - t.Fatal("fixture did not extend the real persisted grant", oldLease, renewed) + if freshEarly.Sub(oldEarly) < time.Second || reply.ExpiresAtNs <= client.initial.ExpiresAtNs || renewed.ExpiresAtNS < reply.ExpiresAtNs || renewed.MaxClockSkewNS != int64(4*time.Second) { + t.Fatal("fixture did not extend the grant under the durable horizon", client.initial, reply, oldLease, renewed) } arrival := oldEarly.Add(-time.Second) if late { @@ -135,8 +138,14 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) { } q := authority.WorkspaceMoveRequest{RequestID: "renewed-forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} head := authority.WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42} - boundary := time.Unix(0, renewed.ExpiresAtNS).Add(time.Duration(renewed.MaxClockSkewNS)) - for _, when := range []time.Time{time.Unix(0, oldLease.ExpiresAtNS).Add(4 * time.Second), boundary.Add(-time.Nanosecond)} { + // The barrier is max(durable horizon, renewed grant) + skew; the old + // grant's expiry plus skew is still too early. + barrierBase := renewed.ExpiresAtNS + if reply.ExpiresAtNs > barrierBase { + barrierBase = reply.ExpiresAtNs + } + boundary := time.Unix(0, barrierBase).Add(time.Duration(renewed.MaxClockSkewNS)) + for _, when := range []time.Time{time.Unix(0, client.initial.ExpiresAtNs).Add(4 * time.Second), time.Unix(0, reply.ExpiresAtNs).Add(4 * time.Second), boundary.Add(-time.Nanosecond)} { masterNS.Store(when.UnixNano()) if _, err := p.MoveWorkspace(ctx, q, head); err == nil { t.Fatal("forced move ignored renewed expiry plus persisted margin") diff --git a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go new file mode 100644 index 0000000000..8f86648d5a --- /dev/null +++ b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go @@ -0,0 +1,198 @@ +package master + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" +) + +// slowGuardStore delays every workspace-lease Put once armed (issue #205). +type slowGuardStore struct { + authority.AuthorityStore + delayNS atomic.Int64 + puts atomic.Int64 // delayed (armed) lease writes: proves the stall was exercised +} + +func (s *slowGuardStore) Put(r authority.DurableRecord) error { + if d := time.Duration(s.delayNS.Load()); d > 0 && r.Workspace != nil && r.Workspace.Lease != nil { + s.puts.Add(1) + time.Sleep(d) + } + return s.AuthorityStore.Put(r) +} + +// deadlineLeaseClient calls the publisher through the master's leaseFact and, +// like a gRPC client, returns at the caller's deadline even when the master +// call is still blocked. In-flight calls are joined before the store closes. +type deadlineLeaseClient struct { + p *authority.Publisher + inflight *sync.WaitGroup +} + +func (c deadlineLeaseClient) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity, _ ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + type result struct { + fact *control.WorkspaceLeaseFact + err error + } + done := make(chan result, 1) + c.inflight.Add(1) + go func() { + defer c.inflight.Done() + l, err := c.p.RenewWorkspaceLease(context.Background(), id.VolumeId, id.ReplicaId, id.Epoch) + if err != nil { + done <- result{err: err} + return + } + done <- result{fact: leaseFact(id.VolumeId, l)} + }() + select { + case r := <-done: + return r.fact, r.err + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func (deadlineLeaseClient) AckWorkspaceRevoked(context.Context, *control.WorkspaceRevocationAck, ...grpc.CallOption) (*control.WorkspaceEmpty, error) { + panic("a slow store must not lead to a clean ACK") +} + +// A live host must keep its lease while the master's authority store is slow: +// a store write longer than the host's 2 s renewal timeout must not fence the +// guard and shut the volume down (issue #205). TTL 6 s gives the guard 4 s of +// validity (6 s minus half the default 4 s skew), renewed every ~1.3 s. +func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) { + disk, err := authority.NewFileAuthorityStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + slow := &slowGuardStore{AuthorityStore: disk} + var inflight sync.WaitGroup + t.Cleanup(func() { + slow.delayNS.Store(0) + inflight.Wait() + if err := disk.Close(); err != nil { + t.Error(err) + } + }) + dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} + p := authority.NewPublisher(dir, authority.WithStore(slow), authority.WithWorkspaceLeaseConfig(6*time.Second, nil)) + t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes + seedSkewPublisher(t, p, dir) + var stops atomic.Int32 + g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, + deadlineLeaseClient{p: p, inflight: &inflight}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, + func(context.Context) (uint64, error) { stops.Add(1); return 7, nil }, nil) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + runDone := make(chan error, 1) + go func() { runDone <- g.Run(ctx) }() + t.Cleanup(func() { + cancel() + select { + case <-runDone: + case <-time.After(10 * time.Second): + t.Error("guard did not settle") + } + }) + for wait := time.Now().Add(3 * time.Second); !g.Projection().Healthy; time.Sleep(20 * time.Millisecond) { + if time.Now().After(wait) { + t.Fatal("first grant did not arrive") + } + } + slow.delayNS.Store(int64(2500 * time.Millisecond)) + start := time.Now() + for time.Since(start) < 10*time.Second { + if !g.Projection().Healthy || stops.Load() != 0 { + t.Fatalf("guard fenced %s after the store slowed to 2.5 s per write (stop calls %d)", time.Since(start).Round(time.Millisecond), stops.Load()) + } + time.Sleep(50 * time.Millisecond) + } + if slow.puts.Load() == 0 { + t.Fatal("no lease write went through the 2.5 s stall: the test did not exercise it") + } + t.Logf("guard stayed healthy for 10 s; %d lease writes took 2.5 s each", slow.puts.Load()) +} + +// A durable deletion-reservation write of an unrelated volume must not block +// a lease renewal: the renewal RPC checks Deletions.Reserved and the volume +// record, and both lifecycle stores hold their mutex across file I/O +// (issue #205). +func TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite(t *testing.T) { + h, c, ctx := reviewBindingHost(t) + reviewLegacyBind(t, h, c, ctx, "vol-b") + line := waitAuthorityLine(t, h.Publisher(), "vol-b") + svc := &services{host: h} + id := &control.WorkspaceIdentity{VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch} + if _, err := svc.RenewWorkspaceLease(ctx, id); err != nil { + t.Fatal(err) // first grant + } + deletions := h.Lifecycle().Deletions + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + releaseHook := func() { releaseOnce.Do(func() { close(release) }) } + deletions.SetPersistHookForTest(func() error { + enterOnce.Do(func() { close(entered) }) + <-release + return nil + }) + admitted := make(chan error, 1) + go func() { + _, err := deletions.Admit("vol-x", "tok") // an unrelated volume, a real durable write + admitted <- err + }() + renewed := make(chan error, 1) + renewStarted := false + // Bounded cleanup: release the hook first, settle BOTH workers, and only + // then clear the hook. Never call the setter after a timed-out join: the + // store mutex may still be held. + t.Cleanup(func() { + releaseHook() + settled := true + select { + case <-admitted: + case <-time.After(5 * time.Second): + settled = false + t.Error("held reservation write did not settle within 5 s after release") + } + if renewStarted { + select { + case <-renewed: + case <-time.After(5 * time.Second): + settled = false + t.Error("renewal did not settle within 5 s after release") + } + } + if settled { + deletions.SetPersistHookForTest(nil) + } + }) + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("reservation write never reached the store") + } + start := time.Now() + renewStarted = true + go func() { _, err := svc.RenewWorkspaceLease(ctx, id); renewed <- err }() + select { + case err := <-renewed: + renewed <- err // keep it for the cleanup join + if err != nil { + t.Fatalf("renewal of vol-b: %v", err) + } + t.Logf("renewal RPC of vol-b took %s while vol-x's reservation write was held", time.Since(start)) + case <-time.After(2 * time.Second): + t.Fatalf("renewal RPC of vol-b was still blocked %s behind the held reservation write of vol-x", time.Since(start).Round(time.Millisecond)) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 0a4da5644a..f8a068cff9 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -28,6 +28,29 @@ func (s *services) workspaceVolume(volume string) error { return nil } +// workspaceVolumeForRenewal is workspaceVolume for lease renewal: it reads +// the published snapshots of the lifecycle stores instead of taking their +// mutexes, which writers hold across file I/O. A renewal during an in-flight +// lifecycle write sees the last published state; deletion admission itself +// stays in the publisher (RecordWorkspaceDeletion needs a clean revocation +// ACK for a live authority line). +func (s *services) workspaceVolumeForRenewal(volume string) error { + if !s.host.cfg.WorkspaceRPC { + return status.Error(codes.FailedPrecondition, "workspace RPC disabled") + } + if s.host.lifecycle == nil { + return status.Error(codes.FailedPrecondition, "lifecycle store unavailable") + } + r, ok := s.host.lifecycle.Volumes.GetVolumeSnapshot(volume) + if !ok || r.Spec.ReplicationFactor != 1 { + return status.Error(codes.FailedPrecondition, "workspace move requires an existing RF1 volume") + } + if s.host.lifecycle.Deletions.ReservedSnapshot(volume) { + return status.Error(codes.FailedPrecondition, "workspace: volume is being deleted") + } + return nil +} + func workspaceError(err error) error { if err == nil { return nil @@ -61,7 +84,7 @@ func leaseFact(volume string, l authority.WorkspaceLease) *control.WorkspaceLeas } func (s *services) RenewWorkspaceLease(ctx context.Context, q *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) { - if err := s.workspaceVolume(q.GetVolumeId()); err != nil { + if err := s.workspaceVolumeForRenewal(q.GetVolumeId()); err != nil { return nil, err } l, err := s.host.Publisher().RenewWorkspaceLease(ctx, q.GetVolumeId(), q.GetReplicaId(), q.GetEpoch()) @@ -78,11 +101,12 @@ func (s *services) RevokeWorkspace(ctx context.Context, q *control.WorkspaceIden if err := s.host.Publisher().BeginWorkspaceRevocation(ctx, q.GetVolumeId(), q.GetReplicaId(), q.GetEpoch()); err != nil { return nil, workspaceError(err) } - state := s.host.Publisher().WorkspaceState(q.GetVolumeId()) - if state == nil || state.Lease == nil { + // Report what was granted, never the durable horizon. + lease, ok := s.host.Publisher().WorkspaceLeaseReply(q.GetVolumeId()) + if !ok { return nil, status.Error(codes.FailedPrecondition, "workspace moved during revocation") } - return leaseFact(q.GetVolumeId(), *state.Lease), nil + return leaseFact(q.GetVolumeId(), lease), nil } func (s *services) AckWorkspaceRevoked(ctx context.Context, q *control.WorkspaceRevocationAck) (*control.WorkspaceEmpty, error) { @@ -174,8 +198,8 @@ func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolum if state == nil { return out, nil } - if state.Lease != nil { - out.Lease = leaseFact(q.GetVolumeId(), *state.Lease) + if lease, ok := s.host.Publisher().WorkspaceLeaseReply(q.GetVolumeId()); ok { + out.Lease = leaseFact(q.GetVolumeId(), lease) // granted expiry, not the durable horizon } if state.Ack != nil { out.RevocationAck = &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: q.GetVolumeId(), ReplicaId: state.Ack.ReplicaID, Epoch: state.Ack.Epoch}, HeadGen: state.Ack.HeadGen} diff --git a/seaweed-block/core/lifecycle/deletion_reservations.go b/seaweed-block/core/lifecycle/deletion_reservations.go index 75cd4f381d..a27cda7245 100644 --- a/seaweed-block/core/lifecycle/deletion_reservations.go +++ b/seaweed-block/core/lifecycle/deletion_reservations.go @@ -8,6 +8,7 @@ import ( "path/filepath" "sort" "sync" + "sync/atomic" ) // Deletion reservations (review of #152 r2): the master-side exclusion of a @@ -51,11 +52,26 @@ type DeletionReservationStore struct { mu sync.Mutex dir string records map[string]DeletionReservation + // snap mirrors records as an immutable copy, republished at every + // assignment of records, for lock-free renewal-path reads. + snap atomic.Pointer[map[string]DeletionReservation] // Test seams for persistence faults (nil in production). failWrite, failRename, failDirSync func() error } +// SetPersistHookForTest installs (nil clears) a callback that each later +// reservation write of this store runs under the store mutex, after its +// temporary file is created and before the write. A non-nil error fails that +// write with nothing replaced. Tests only: install it before any concurrent +// writer starts; the callback must not call back into the store or into this +// setter. Never call it while a write may still be held by the callback. +func (s *DeletionReservationStore) SetPersistHookForTest(hook func() error) { + s.mu.Lock() + defer s.mu.Unlock() + s.failWrite = hook +} + // OpenDeletionReservationStore opens or creates the store in dir. func OpenDeletionReservationStore(dir string) (*DeletionReservationStore, error) { return openDeletionReservationStore(dir, syncBindingParent) @@ -77,6 +93,7 @@ func openDeletionReservationStore(dir string, syncParent func(string) error) (*D b, err := os.ReadFile(filepath.Join(dir, reservationsFile)) switch { case errors.Is(err, os.ErrNotExist): + s.publishLocked() return s, nil case err != nil: return nil, fmt.Errorf("lifecycle: read deletion reservations: %w", err) @@ -89,9 +106,34 @@ func openDeletionReservationStore(dir string, syncParent func(string) error) (*D return nil, fmt.Errorf("lifecycle: deletion reservation %q is invalid", v) } } + s.publishLocked() return s, nil } +// publishLocked republishes the immutable snapshot of records (token slices +// copied). Called wherever records is assigned; caller holds mu or owns s. +func (s *DeletionReservationStore) publishLocked() { + m := make(map[string]DeletionReservation, len(s.records)) + for k, r := range s.records { + r.Tokens = append([]string(nil), r.Tokens...) + m[k] = r + } + s.snap.Store(&m) +} + +// ReservedSnapshot is Reserved without the store mutex, for the lease +// renewal path: it reads the last published records (after a durable write, +// or a protective change kept in memory on an unknown outcome), never waiting +// on a write in flight. +func (s *DeletionReservationStore) ReservedSnapshot(vol string) bool { + m := s.snap.Load() + if m == nil { + return false + } + _, ok := (*m)[vol] + return ok +} + // Get returns vol's reservation. func (s *DeletionReservationStore) Get(vol string) (DeletionReservation, bool) { s.mu.Lock() @@ -194,6 +236,7 @@ func (s *DeletionReservationStore) update(vol string, protective bool, change fu return r, err } s.records = next + s.publishLocked() return r, nil } @@ -225,6 +268,7 @@ func (s *DeletionReservationStore) persist(next map[string]DeletionReservation, unknown := func(err error) error { if protective { s.records = next // may be on disk: keep the exclusion + s.publishLocked() } return fmt.Errorf("lifecycle: deletion reservation outcome unknown: %w", err) } diff --git a/seaweed-block/core/lifecycle/renewal_snapshot_test.go b/seaweed-block/core/lifecycle/renewal_snapshot_test.go new file mode 100644 index 0000000000..7ae59cdda1 --- /dev/null +++ b/seaweed-block/core/lifecycle/renewal_snapshot_test.go @@ -0,0 +1,217 @@ +package lifecycle + +import ( + "errors" + "fmt" + "sync" + "testing" + "time" +) + +// The reservation snapshot mirrors records at every assignment: after a +// durable write, on a protective change kept in memory on an unknown outcome +// (fail closed), never on a known no-write, and at load. Snapshots are +// immutable, token slices included (issue #205). +func TestDeletionReservationSnapshotFollowsRecords(t *testing.T) { + fail := errors.New("injected") + dir := t.TempDir() + s := reopen(t, dir) + same := func(what string, st *DeletionReservationStore, vols ...string) { + t.Helper() + for _, v := range vols { + if st.ReservedSnapshot(v) != st.Reserved(v) { + t.Fatalf("%s: snapshot of %q = %t, records = %t", what, v, st.ReservedSnapshot(v), st.Reserved(v)) + } + } + } + if s.ReservedSnapshot("v") { + t.Fatal("empty store reports a reservation") + } + if _, err := s.Admit("v", "d1"); err != nil { + t.Fatal(err) + } + if !s.ReservedSnapshot("v") { + t.Fatal("durable admission not visible to the snapshot") + } + s.failWrite = func() error { return fail } + if _, err := s.Admit("w", "d1"); !errors.Is(err, fail) || s.ReservedSnapshot("w") { + t.Fatalf("known no-write: %v; snapshot must not show it", err) + } + s.failWrite = nil + s.failRename = func() error { return fail } + if _, err := s.Admit("r", "d1"); !errors.Is(err, fail) || !s.ReservedSnapshot("r") { + t.Fatalf("unknown outcome of a protective change: %v; the snapshot must keep the exclusion (fail closed)", err) + } + s.failRename = nil + s.failDirSync = func() error { return fail } + if _, err := s.Admit("y", "d1"); !errors.Is(err, fail) || !s.ReservedSnapshot("y") { + t.Fatalf("unknown outcome (directory sync): %v; the snapshot must keep the exclusion", err) + } + s.failDirSync = nil + same("after faults", s, "v", "w", "r", "y") + + // Immutability: a published snapshot does not change when records do. + before := s.snap.Load() + tokens := append([]string(nil), (*before)["v"].Tokens...) + if _, err := s.Admit("v", "d2"); err != nil { + t.Fatal(err) + } + if got := (*before)["v"].Tokens; fmt.Sprint(got) != fmt.Sprint(tokens) { + t.Fatalf("an earlier snapshot changed: %v, was %v", got, tokens) + } + after := s.snap.Load() + (*after)["v"].Tokens[0] = "mutated" + if got, _ := s.Get("v"); got.Tokens[0] == "mutated" { + t.Fatal("snapshot token slice aliases the records") + } + if _, err := s.Abort("v", "d1"); err != nil { + t.Fatal(err) + } + if _, err := s.Abort("v", "d2"); err != nil || s.ReservedSnapshot("v") { + t.Fatalf("release of the last token: %v; snapshot must drop the reservation", err) + } + same("after release", s, "v", "w", "r", "y") + r := reopen(t, dir) // load publishes too + same("after reopen", r, "v", "w", "r", "y") +} + +// The Volumes snapshot follows every change of records, including load and +// the memory-first delete. +func TestFileStoreSnapshotFollowsRecords(t *testing.T) { + dir := t.TempDir() + s, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + if _, ok := s.GetVolumeSnapshot("a"); ok { + t.Fatal("empty store reports a volume") + } + if _, err := s.CreateVolume(VolumeSpec{VolumeID: "a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + if rec, ok := s.GetVolumeSnapshot("a"); !ok || rec.Spec.ReplicationFactor != 1 { + t.Fatalf("create not visible: %+v %t", rec, ok) + } + if _, err := s.AttachVolume("a", "n1"); err != nil { + t.Fatal(err) + } + if rec, _ := s.GetVolumeSnapshot("a"); rec.AttachedTo != "n1" { + t.Fatalf("attach not visible: %+v", rec) + } + if _, err := s.DetachVolume("a", "n1"); err != nil { + t.Fatal(err) + } + if rec, _ := s.GetVolumeSnapshot("a"); rec.AttachedTo != "" { + t.Fatalf("detach not visible: %+v", rec) + } + r, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + if _, ok := r.GetVolumeSnapshot("a"); !ok { + t.Fatal("load did not publish") + } + if err := s.DeleteVolume("a"); err != nil { + t.Fatal(err) + } + if _, ok := s.GetVolumeSnapshot("a"); ok { + t.Fatal("delete not visible") + } +} + +// Snapshot reads never take the store mutex that writers hold across file +// I/O: they return while the mutex is held. +func TestLifecycleSnapshotReadsDoNotTakeStoreMutex(t *testing.T) { + vols, err := OpenFileStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if _, err := vols.CreateVolume(VolumeSpec{VolumeID: "a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + res := reopen(t, t.TempDir()) + if _, err := res.Admit("x", "d"); err != nil { + t.Fatal(err) + } + vols.mu.Lock() + res.mu.Lock() + done := make(chan bool, 1) + go func() { + _, okV := vols.GetVolumeSnapshot("a") + done <- okV && res.ReservedSnapshot("x") + }() + select { + case ok := <-done: + res.mu.Unlock() + vols.mu.Unlock() + if !ok { + t.Fatal("snapshot read returned the wrong state") + } + case <-time.After(2 * time.Second): + res.mu.Unlock() + vols.mu.Unlock() + <-done + t.Fatal("snapshot read waited on the store mutex") + } +} + +// Snapshot readers run concurrently with every writer kind (run with -race). +func TestLifecycleSnapshotConcurrentWriters(t *testing.T) { + vols, err := OpenFileStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + res := reopen(t, t.TempDir()) + stop := make(chan struct{}) + var wg sync.WaitGroup + wg.Add(3) + go func() { + defer wg.Done() + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + v := fmt.Sprintf("v%d", i%4) + _, _ = vols.CreateVolume(VolumeSpec{VolumeID: v, SizeBytes: 1 << 20, ReplicationFactor: 1}) + _ = vols.DeleteVolume(v) + } + }() + go func() { + defer wg.Done() + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + v := fmt.Sprintf("r%d", i%4) + _, _ = res.Admit(v, "d1") + _, _ = res.Admit(v, "d2") + _, _ = res.Abort(v, "d1") + if i%3 == 0 { + _, _ = res.Commit(v, "d2") + } else { + _, _ = res.Abort(v, "d2") + } + } + }() + go func() { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + for i := 0; i < 4; i++ { + _, _ = vols.GetVolumeSnapshot(fmt.Sprintf("v%d", i)) + _ = res.ReservedSnapshot(fmt.Sprintf("r%d", i)) + } + } + }() + time.Sleep(300 * time.Millisecond) + close(stop) + wg.Wait() +} diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index 1de3e090e2..68b7243cb4 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -15,6 +15,7 @@ import ( "regexp" "sort" "sync" + "sync/atomic" ) var ( @@ -52,6 +53,31 @@ type FileStore struct { mu sync.Mutex dir string records map[string]VolumeRecord + // snap mirrors records as an immutable copy, republished at every change + // of records, for lock-free renewal-path reads. + snap atomic.Pointer[map[string]VolumeRecord] +} + +// publishLocked republishes the immutable snapshot of records. Caller holds +// mu or owns s. +func (s *FileStore) publishLocked() { + m := make(map[string]VolumeRecord, len(s.records)) + for k, r := range s.records { + m[k] = r + } + s.snap.Store(&m) +} + +// GetVolumeSnapshot is GetVolume without the store mutex, for the lease +// renewal path: it reads the last published records, never waiting on a +// write in flight. +func (s *FileStore) GetVolumeSnapshot(volumeID string) (VolumeRecord, bool) { + m := s.snap.Load() + if m == nil { + return VolumeRecord{}, false + } + rec, ok := (*m)[volumeID] + return rec, ok } // OpenFileStore opens or creates a lifecycle intent store. @@ -69,6 +95,7 @@ func OpenFileStore(dir string) (*FileStore, error) { if err := s.load(); err != nil { return nil, err } + s.publishLocked() return s, nil } @@ -92,6 +119,7 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { return VolumeRecord{}, err } s.records[spec.VolumeID] = merged + s.publishLocked() return merged, nil } return existing, nil @@ -101,6 +129,7 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { return VolumeRecord{}, err } s.records[spec.VolumeID] = rec + s.publishLocked() return rec, nil } @@ -140,6 +169,7 @@ func (s *FileStore) DeleteVolume(volumeID string) error { s.mu.Lock() defer s.mu.Unlock() delete(s.records, volumeID) + s.publishLocked() if err := os.Remove(s.path(volumeID)); err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("lifecycle: remove %s: %w", volumeID, err) } @@ -169,6 +199,7 @@ func (s *FileStore) AttachVolume(volumeID, nodeID string) (VolumeRecord, error) return VolumeRecord{}, err } s.records[volumeID] = rec + s.publishLocked() return rec, nil } @@ -192,6 +223,7 @@ func (s *FileStore) DetachVolume(volumeID, nodeID string) (VolumeRecord, error) return VolumeRecord{}, err } s.records[volumeID] = rec + s.publishLocked() return rec, nil } diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index a52be4776e..e9bbb93f41 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -223,9 +223,11 @@ The attempt path is never removed, so a late create can never land after a delet **Host guard** (`core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard`, enabled with `blockvolume --workspace-lease`; see [workspace lease](../workspace-lease.md)): frontend I/O and cuts are admitted only with a granted, unexpired lease for the exact `{volume, replica, epoch}`. Validity is anchored to the renewal request's start time, and blockmaster's `ValidForNs` already subtracts half the clock-skew bound (`core/host/master/workspace_service.go` `leaseFact`). A late reply cannot extend admission. A fenced guard never reopens. The lease is 30 s (`core/authority/authority.go`, `workspaceTTL`); the skew bound defaults to 20 s (`blockmaster --workspace-max-clock-skew`). +**Master side of a renewal** (`core/authority/workspace_lease_view.go`): blockmaster answers a renewal of an established lease from memory, under a small leaf lock, with no disk write and without waiting for other authority writes. The grant is min(now + TTL, durable horizon), where the horizon is the lease expiry stored on disk; a background extension, an ordinary authority write, keeps the horizon about 1.5·TTL ahead of the last renewal that triggered it. Only the first grant of a lease is written synchronously. If extensions fall behind, grants shrink and the host fences by the horizon minus half the skew bound; a failed extension write makes the volume uncertain and refuses renewals that would issue a new or extended grant (a Revoking lease still gets its bounded drain reply). + **CLEAN move:** Detach publishes the final cut with `State = detached` in one CAS → revoke → the host drains frontend, replication and provider and acknowledges the stored detached HEAD generation → blockmaster checks the detached HEAD and the matching acknowledgement → new epoch → the new host claims HEAD. -**FORCED move:** blockmaster waits until both the stored expiry and its 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. +**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. **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. @@ -267,11 +269,11 @@ Lease states: stateDiagram-v2 state "Lease (blockmaster)" as L { [*] --> Granted: Renew - Granted --> Granted: Renew before expiry + 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: expiry + Granted --> Expired: horizon or deadline passes Expired --> Moved: FORCED move after expiry + skew bound } ``` diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d99cd88210..4067e09c38 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -77,20 +77,20 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Bound | Bound (endpoint version + 1) | `IntentRefreshEndpoint`; same epoch; a no-op when the addresses are unchanged | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | | Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` | | any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | -| any (workspace) | Uncertain | a failed workspace authority write; later changes for that volume are refused until restart | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked` | `INV-AUTH-UNCERTAIN-001` | +| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | | Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | **Workspace lease and move, in blockmaster.** | From | To | Event and guard | Enforced in | Protects | |---|---|---|---|---| -| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending | `core/authority/workspace.go` `RenewWorkspaceLease` | `INV-WS-LEASE-001` | -| Granted | Granted | renew before the stored expiry and the restart deadline | `core/authority/workspace.go` `RenewWorkspaceLease` | `INV-WS-LEASE-001` | -| Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`, `RenewWorkspaceLease` | `INV-WS-CLEAN-MOVE-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 | `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` | -| Granted or Revoking | Expired | the stored expiry passes | `core/authority/workspace.go` `RenewWorkspaceLease`, `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | -| Expired | Moved (forced) | explicit force; the stored expiry plus the clock-skew bound and the restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `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` | ### M3 Replica role and peer state @@ -292,12 +292,18 @@ 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-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. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked` | — | `ControlPlane` `UniqueEpoch` | STUB | +| `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-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 | Notes: -- `INV-AUTH-UNCERTAIN-001`: The guard is in the code; no Go test asserts the refusal. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. +- `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. +- `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). +- `INV-WS-RENEW-NONBLOCKING-001`: The cited tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace. ### B.3 Core: replication and replica roles @@ -331,7 +337,7 @@ Notes: | `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-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 stored lease expiry and the restart deadline, each plus the clock-skew bound; the lease reported to the host excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `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`) | — | 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 | Notes: diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 46329abee0..8803d2342c 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -108,7 +108,7 @@ length of TLC's shortest counterexample. | # | Spec | What it models | Key invariants | Results | Code (at `5c7c1a7f`) | |---|---|---|---|---|---| | S1 | `ChunkLifecycleFixed` (+ historical `ChunkLifecycle`) | Chunk HEAD, capture intents, snapshots (name record + attempt path), fork claims, tombstones, GC mark+sweep, and volume delete with a blockmaster deletion reservation. Actors: host, 0-2 snapshot callers, a fork, explicit DeleteSnapshot callers, 1-3 volume deleters with reruns, CreateVolume, GC. Filer semantics: conditional write on HEAD gen, exclusive create, conditional update/delete, uncancellable late create. | `GCSafe`, `SnapOnlyExplicitDelete`, `CommitClean`, `NoPublishAfterCommit`, `AckedChunksSurvive`, `NoIdReuse`, `GiveBackReleases`, temporal `HeadMonotone` | **Fixed design, all pass:** `Fix_P1` 51,375,412; `Fix_P2_aba` 46,245,848; `Fix_mix_small` 29,194,420; `Fix_token` 41,256; `Fix_create` 100. `Fix_mix` no violation in 138M states (20-min limit, incomplete). All `Fix_reach_*` reached. **Historical (pre-fix) counterexamples:** `Bug_P1_mark` (18-step), `Bug_P1_giveback` (23), `Bug_P1_data` (25: GC reclaims an acked snapshot's chunk), `Bug_P2_aba` (22), `Bug_token` (16), `Bug_create` (7). | `core/frontend/chunkstore/volume_delete.go:106` DeleteVolume (incarnation loop `:150`), `:269` markHeadDeleting, `:400` snapshotsBlock, `:314` revertHeadDeleting, `:347` commitHeadPurging; `catalog.go:824` CreateSnapshot (gate `:863`), `:943` claimName, `:771` createResolved, `:1058` DeleteSnapshot, `:1157` Fork, `:1337` claimForkParent, `:709` AbortSnapshot, `:1438` AbortFork; `retention.go:448` markDeleting, `:570` liveClaims; `gc.go:108` Collector.run; `chunk_remote.go:404` CASHead refuses delete states; `core/host/master/services.go:53` CreateVolume (holds workspaceMu `:64`), `:132` MarkVolumeDeleting; `core/lifecycle/deletion_reservations.go:111` Admit; `cmd/sw-block/chunk_volume_delete.go:32` `--request-id` | -| S2 | `WorkspaceTakeover` | A workspace volume moving from host A (epoch 1) to host B by a clean move (detach, revoke, ACK, assign) or a forced move (lease expiry). Blockmaster clock, host clock lag up to `Drift`, lossy and reordered messages, master restart, each host's cut as one remote call per step, takeover CAS, GC intent expiry. Code pinned at `5c293821`. | `NoDualServing`, `NoOldCasAfterTakeover`, `NoLateChunkReachable`, `GCSafe`, `NoLiveIntentExpired`, `CleanNoLoss`, `ForcedLossBounded`, `SeedMatchesTakeover`, temporal `HeadMonotone` | **Pass:** `W4_clean` 6,048,496; `W4_forced` 22,619,644; `W4_drift_heads` 56,242,345; `W4_clean_large` 590,137,925 (depth 70). `W4_forced_large`: no violation in 910,907,693 states (time limit, incomplete). **RED:** `RED_early_assign` NoDualServing (12-step); `RED_gc_ageonly` GCSafe (12); `RED_epoch` NoOldCasAfterTakeover (22-24); `RED_lsn` HeadMonotone (24). `RED_epoch_storeonly`/`_hostonly` pass (438,406 / 827,500): either epoch check alone suffices. `RED_lsn_storeonly` passes (28,389,024). **Findings:** `W4_drift` NoDualServing (13-step, fixed by #158, see below); `W4_forced_exact` ForcedLossExact (16-step, benign, open). | `core/frontend/chunkstore/chunk_remote.go:390` CASHead (epoch guard `:391`, gen/epoch/LSN guard `:409`, conditional update `:420`); `core/host/volume/workspace_lease.go:57` permits, `:70` Refresh (anchor `:73`, accept `:117`); `core/authority/workspace.go:95` RenewWorkspaceLease, `:222` BeginWorkspaceRevocation, `:237` AckWorkspaceRevocation, `:309` prepareWorkspaceMoveLocked (forced-move margin `:316-320`); `core/host/master/workspace_service.go:109` MoveWorkspace (HEAD read `:116`); `core/authority/authority.go:251` reloadFromStore (deadline reset `:261`); `core/frontend/durable/provider_chunk.go:289` PrepareRestore, `:309` ClaimChunkHead; `core/storage/chunk_restore.go:14`; `core/storage/chunk_layer.go:680` captureLocked (admit `:695`, lsn_behind `:800`, PutIntent `:853`, re-admit `:911`, supersededBy `:916`, CAS `:926`, settle `:972`); `core/frontend/chunkstore/gc.go:221` intent-expiry epoch rule | +| S2 | `WorkspaceTakeover` | A workspace volume moving from host A (epoch 1) to host B by a clean move (detach, revoke, ACK, assign) or a forced move (lease expiry). Blockmaster clock, host clock lag up to `Drift`, lossy and reordered messages, master restart, each host's cut as one remote call per step, takeover CAS, GC intent expiry. Code pinned at `5c293821`. | `NoDualServing`, `NoOldCasAfterTakeover`, `NoLateChunkReachable`, `GCSafe`, `NoLiveIntentExpired`, `CleanNoLoss`, `ForcedLossBounded`, `SeedMatchesTakeover`, temporal `HeadMonotone` | **Rerun with the durable lease horizon (#205, PR #209; model `7074febd`, 2026-11-18; TLC 2.19, 27 configurations, BFS).** **Pass:** `W4_clean` 18,378,104 (depth 63); `W4_forced` 33,690,232 (54); `W4_drift_heads` 82,446,907 (55); `W4_hz_clean` 25,464,387 (63) and `W4_hz_forced` 47,511,490 (54), with failing extension writes (landed or not), one restart, and the new `HostWithinHorizon`, `DiskCoversMemory`; `RED_hz_noclamp_safety` 25,511,482 (no clamp, split-brain invariants: passes, the restart rule covers grants). **Time limit, no violation (incomplete):** `W4_clean_large` 592,158,353 and `W4_forced_large` 592,791,914 (100 min each); `W4_both` 124,916,894 and `W4_hz_both` 132,152,744 (40 min each). **RED:** `RED_hz_noclamp` HostWithinHorizon (9-step: a renewal without the clamp grants validity past the durable horizon); `RED_early_assign` NoDualServing (13); `RED_gc_ageonly` GCSafe (12); `RED_epoch` NoOldCasAfterTakeover (23); `RED_lsn` HeadMonotone (25). `RED_epoch_storeonly`/`_hostonly` pass (213,607 / 322,067); `RED_lsn_storeonly` passes (33,690,232). **Witnesses (expected violated):** `W4_reach_clean`, `W4_reach_forced`, `W4_reach_bcut`, `W4_reach_restart`, `W4_hz_reach_ext` (an extension raises the horizon), `W4_hz_reach_landed` (a failed extension lands on disk), `W4_hz_reach_uncertain_restart`. **Findings (unchanged):** `W4_drift` NoDualServing (17-step: the model's forced move has no clock-skew margin; the code adds it, #158); `W4_forced_exact` ForcedLossExact (17-step, benign, open). Earlier results (before #205): `W4_clean` 6,048,496; `W4_forced` 22,619,644; `W4_drift_heads` 56,242,345; `W4_clean_large` 590,137,925 (depth 70); `W4_forced_large` no violation in 910,907,693 (incomplete). | `core/frontend/chunkstore/chunk_remote.go:390` CASHead (epoch guard `:391`, gen/epoch/LSN guard `:409`, conditional update `:420`); `core/host/volume/workspace_lease.go:57` permits, `:70` Refresh (anchor `:73`, accept `:117`); `core/authority/workspace.go:95` RenewWorkspaceLease, `:222` BeginWorkspaceRevocation, `:237` AckWorkspaceRevocation, `:309` prepareWorkspaceMoveLocked (forced-move margin `:316-320`); `core/host/master/workspace_service.go:109` MoveWorkspace (HEAD read `:116`); `core/authority/authority.go:251` reloadFromStore (deadline reset `:261`); `core/frontend/durable/provider_chunk.go:289` PrepareRestore, `:309` ClaimChunkHead; `core/storage/chunk_restore.go:14`; `core/storage/chunk_layer.go:680` captureLocked (admit `:695`, lsn_behind `:800`, PutIntent `:853`, re-admit `:911`, supersededBy `:916`, CAS `:926`, settle `:972`); `core/frontend/chunkstore/gc.go:221` intent-expiry epoch rule | | S3 | `WALRecovery`, `SmartWALRecovery`, `WALReplica` | Local WAL crash recovery. **walstore:** a ring of K pages, 1-2 page records, page cache written back in any order, Sync, flusher checkpoint, crash at any point with optionally one corrupted record page; recovery is a pure function of the durable image, with a selectable `Rule`. **smartwal:** in-place extent write plus a metadata ring slot, written back in any order, torn slots. **Replica:** RF=2 classification and promotion eligibility, BASE jump. | `I1` every synced write is recovered (or superseded) or recovery fails closed; `I2` a crash without corruption never reports corruption; `ReplayLastWriter`; `I0Prefix`; `I1Frontier`; `NoForgedReplay`; `I3` the promoted node has every acked write | **walstore, current main** (rule `rootLww`, reuse bounded by the persisted tail): `S3r_rootLww_I1_crashonly`/`_I2`/`_replay` pass (849,003); with an in-memory rebuild jump `S3r_rebuild_rootLww_*` pass (1,460,772). **Pre-fix code:** `S3_wal_current_I1_crashonly` I1 violated (synced write lost after a plain crash, #156); `S3v_code_lww_I1_crashonly` I1 violated (LWW replay alone is not enough, #159). **Open:** one corrupted synced record `S3v1_root_lww_I1` violated; Sync-persisted watermark `S3m_*` pass (1,320,984 / 3,955,400); `S3f_*` NoForgedReplay violated (confirmed on main, see Open items). **smartwal, current:** `S3_sw_current_I2` violated (false `wal_corrupt`), `_I1`, `_I1frontier` violated; proposal `S3_sw2_ordered_marker_repair_I2` pass (65,401), `_I1slot` pass (345,084). **Replica:** `S3_rep_c1_I2` pass (29,196), `S3_rep_c1_g2_I2` pass (12,712), `S3_rep_c1_g1_I3` pass (74,527); RED `S3_rep_c2_I2`, `S3_rep_c1_g2jump_I2`, `S3_rep_nogate_I3` violated. | `core/storage/recovery.go:43` recoverWAL (head==tail scan from its position `:63-73`, defensive scan `:74-90`, a range stops at its first bad entry `:141`, `:154`, hole warning `:437`), LWW replay `:193` via `core/storage/dirty_map.go:56` putAtIfNewer; `core/storage/wal_writer.go:41` durableTail, `:70` spaceUsed, `:443` tailPersisted; `core/storage/walstore.go:390` checkpoint release, `:933` Sync, `:1065` AdvanceFrontier, `:1167` ApplyEntry; `core/storage/smartwal/store.go:297` writeAt (extent `:304`, then ring `:313`), `:345` Sync; `smartwal/recovery.go:47` runRecoveryCounting (fail closed `:99-100`); `smartwal/ring.go:45` appendAt, `:69` scanSlots; `core/replication/volume.go:680` RebaseShipLSN | | S4 | `CutCapture`, `CutPipeline` | Which chunks the next cut must upload: the dirty bitmap vs a per-chunk last-write-LSN map, across RF=1 restart, crash mid-cut and RF=2 failover; dirty state persisted before a checkpoint passes WAL entries. Then the pipeline: precopy tagged with a per-chunk mutation generation, two-level manifest segments, root CAS, and `reconciling` after a restart without a bound bitmap. | `HeadImage` (HEAD is the exact image of the lineage at HEAD.lsn), `HeadLeDurable`, `SegConsistent` | **Pass:** `S4_rf1_bitmap` 47,670, `S4_rf1_lsnmap` 46,934, `S4_rf2_bitmapHash` 7,166,376, `S4_rf2_lsnmap` 8,226,004, `S4_rf2_lsnmap_base` 901,390; `S4b_design` 69,645, `S4b_design_big` 1,515,837. **RED:** `S4_rf2_bitmap` (failover without hashMode, 7-step), `S4_rf2_lsnmap_localCut` (6), `S4_rf1_*_noPersist` (7), `S4_rf1_bitmap_clearEarly` (8); `S4b_red_noGen`, `S4b_red_cutWhileRec` HeadImage; `S4b_red_segReuse` SegConsistent. | `core/storage/chunk_layer.go:356` BeforeCheckpointAdvance, `:299` OnExtentWrite, `:95` hashMode (set on attach `:184-230`), `:111` chunkMut, `:324` noteMutation, `:762` and `:1435` staged upload reused only if its generation is unchanged, `:702-704` cut refused while reconciling, `:877-881` PrepareManifest, `:1542` finishCut; `core/frontend/chunkstore/manifest.go:101` segment reused only if its chunk refs are unchanged | | S4c | `CutCOW` | Copy-before-write in the cut window (proposed): today's barrier cut against COW, where the barrier only fixes the cut point H and the candidate set D, the first write to an uncopied candidate saves its at-H content to a local side store, a write to a chunk being copied waits, the copier reads the side store or the live chunk, and the side store is dropped at the CAS and on crash. A chunk copy is two steps (`CopyStart`, `CopyFinish`); read-visible content and the extent are separate; one crash. | `HeadImage`, `BufFrozen` (every uploaded chunk equals the image at H), `SideFrozen`, `SideOnlyInCut`, `ReadsNewest`, `HeadLeSynced` | `S4c_cow_safe` pass (34,342,214), `S4c_barrier_safe` pass (5,070,320), MaxLSN 6, 2 cuts. **RED**, each violates `BufFrozen`: `noChunkLock` (6,814), `noCopy` (6,617), and on the atomic-copy predecessor `copyAfter` (2,493), `earlyRelease` (1,067), `copyAtFlush` (2,191), `sideReuse` (272,908); those four carry over because every atomic-copy behaviour is a two-step behaviour with the steps adjacent. Witnesses reachable: `WriteInWindow` (508), `CASAfterWindowWrite`, `CrashDroppedSide` (atomic-copy runs). Atomic-copy COW at MaxLSN 8, 3 cuts: clean through depth 22 (605M states, time cap). | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `captureMu` (at `c5eb5819`) | diff --git a/seaweed-block/docs/spec/WorkspaceTakeover.tla b/seaweed-block/docs/spec/WorkspaceTakeover.tla index ec08859aca..0814350020 100644 --- a/seaweed-block/docs/spec/WorkspaceTakeover.tla +++ b/seaweed-block/docs/spec/WorkspaceTakeover.tla @@ -9,6 +9,17 @@ (* each host's clock may lag it by at most Drift ticks (bounded rate *) (* drift). Messages live in a set: delayed, reordered or lost. *) (* Code at seaweed-block main 5c293821; mapping in README.md (S2). *) +(* *) +(* #205, durable lease horizon (PR #209): lease.exp is the PUBLISHED *) +(* horizon (the blockmaster's in-memory copy of the durable record), dhz *) +(* the horizon on DISK, deadline the latest grant (memory only). A renewal *) +(* of a live lease writes nothing: grant = min(now + TTL, lease.exp). An *) +(* extension is an ordinary serialized writer that raises the horizon to *) +(* trigger + TTL + HSlack; its write may fail without landing or fail *) +(* after landing (unknown outcome). Any failed write latches `uncertain`: *) +(* renewals and other writes are refused until a restart reloads the disk. *) +(* Nondecreasing `now` (Tick/SlowTick only advance it) is an ASSUMPTION of *) +(* this model, not a property of the deployment's clocks. *) (***************************************************************************) EXTENDS Integers, FiniteSets, Sequences, TLC @@ -29,19 +40,28 @@ CONSTANTS LayerLsnCheck, \* layer refuses a cut below HEAD.remote_lsn (lsn_behind) chunk_layer.go:800 SeedFromObserved,\* B seeds its WAL from the HEAD its takeover CAS protects chunk_restore.go:38-43 GCEpochRule, \* GC expires an intent only when the remote HEAD epoch > intent epoch gc.go:221 - WaitLeaseExpiry \* forced move waits for the lease to expire authority/workspace.go:314-318 + WaitLeaseExpiry,\* forced move waits for the lease to expire authority/workspace.go:314-318 + Clamp, \* #205: a renewal's grant is clamped to the published horizon (FALSE: unsafe memory-only renewal) + ExtFail \* #205: an extension write may fail, landed or not (unknown outcome -> uncertain) Hosts == {"A", "B"} NoRec == [gen |-> 0, epoch |-> 0, holder |-> "-", st |-> "-", dgen |-> 0, lsn |-> 0, img |-> <<"-", 0>>] Head0 == [gen |-> 1, epoch |-> 1, holder |-> "A", st |-> "active", dgen |-> 0, lsn |-> 0, img |-> <<"A", 0>>] Other(h) == IF h = "A" THEN "B" ELSE "A" +Min(a, b) == IF a < b THEN a ELSE b +Max(a, b) == IF a > b THEN a ELSE b +\* #205 horizon geometry (workspace_lease_view.go): an extension writes H = trigger + TTL + HSlack; a renewal +\* triggers one when the published horizon is closer than TTL + Margin. Code: TTL/2 and TTL/4; at least one tick here. +HSlack == Max(1, TTL \div 2) +Margin == Max(1, TTL \div 4) VARIABLES now, lag, \* clocks head, stored, intents, \* remote store: HEAD, chunk bodies, intents msgs, \* in-flight messages - asg, lease, ack, journal, maxEpoch, \* blockmaster durable state (authority store) - deadline, restarts, \* blockmaster in-memory lease deadline (reset on restart) + asg, lease, ack, journal, maxEpoch, \* blockmaster published state (= the authority store unless uncertain) + deadline, restarts, \* blockmaster in-memory lease deadline (the latest grant; reset on restart) + dhz, uncertain, extReq, \* #205: horizon on disk; a write outcome is unknown; pending extension trigger time (-1: none) mv, \* operator's move in progress host, \* per-host state cut, \* per-host chunk-layer cut in progress @@ -49,7 +69,7 @@ VARIABLES hist \* history (never read by the protocol) vars == <> + deadline, restarts, dhz, uncertain, extReq, mv, host, cut, bpc, bobs, hist>> HNow(h) == now - lag[h] @@ -73,11 +93,13 @@ Init == /\ head = Head0 /\ stored = {<<"A", 0>>} /\ intents = {} /\ msgs = {} /\ asg = [holder |-> "A", epoch |-> 1] - /\ lease = [holder |-> "A", epoch |-> 1, exp |-> TTL, revoking |-> FALSE, none |-> FALSE] + \* A's first grant: horizon now + TTL + HSlack on disk, grant (deadline, A's validity) now + TTL + /\ lease = [holder |-> "A", epoch |-> 1, exp |-> TTL + HSlack, revoking |-> FALSE, none |-> FALSE] /\ ack = [gen |-> 0, holder |-> "-", epoch |-> 0] /\ journal = [kind |-> "-", gen |-> 0, lsn |-> 0, newEpoch |-> 0] /\ maxEpoch = 1 /\ deadline = TTL /\ restarts = 0 + /\ dhz = TTL + HSlack /\ uncertain = FALSE /\ extReq = -1 /\ mv = [st |-> "none", kind |-> "-", h |-> NoRec] /\ host = [h \in Hosts |-> IF h = "A" THEN [epoch |-> 1, until |-> TTL, fenced |-> FALSE, revoked |-> FALSE, stopIO |-> FALSE, @@ -94,25 +116,25 @@ Init == (* clocks and the VM *) Tick == /\ now < MaxT /\ now' = now + 1 - /\ UNCHANGED <> + /\ UNCHANGED <> \* the master clock advances, A's does not (bounded drift) SlowTick == /\ now < MaxT /\ lag["A"] < Drift /\ now' = now + 1 /\ lag' = [lag EXCEPT !["A"] = @ + 1] - /\ UNCHANGED <> + /\ UNCHANGED <> \* a VM write accepted by a serving host (WAL LSN + 1) VMWrite(h) == /\ Serving(h) /\ host[h].lsn < MaxLSN /\ host' = [host EXCEPT ![h].lsn = @ + 1] /\ hist' = [hist EXCEPT !.acked[h] = host[h].lsn + 1, !.bServeT = IF h = "B" /\ hist.bServeT < 0 THEN now ELSE hist.bServeT] - /\ UNCHANGED <> + /\ UNCHANGED <> LoseMsg == \E m \in msgs : /\ msgs' = msgs \ {m} /\ host' = IF m.t = "renew" \/ m.t = "lease" THEN [host EXCEPT ![m.h].renewing = FALSE] ELSE host - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- -(* workspace lease (core/host/volume/workspace_lease.go, core/authority/workspace.go) *) +(* workspace lease (core/host/volume/workspace_lease.go, core/authority/workspace_lease_view.go) *) \* Refresh: validity anchored to the request START (workspace_lease.go:68-127) SendRenew(h) == @@ -122,23 +144,51 @@ SendRenew(h) == /\ msgs' = msgs ELSE /\ host' = [host EXCEPT ![h].renewing = TRUE] /\ msgs' = msgs \cup {[t |-> "renew", h |-> h, e |-> host[h].epoch, s |-> HNow(h)]} - /\ UNCHANGED <> + /\ UNCHANGED <> -\* Publisher.RenewWorkspaceLease (authority/workspace.go:73-106), reply validFor = exp - now (workspace_service.go:41-52) +\* Publisher.RenewWorkspaceLease (#205, workspace_lease_view.go), reply validFor = expiry - now (workspace_service.go leaseFact). +\* - Revoking: the drain reply, expiry min(horizon, deadline); never extends (allowed while uncertain, as before). +\* - No lease yet: the FIRST grant, a synchronous durable write (refused while uncertain): horizon now + TTL + HSlack. +\* - Live lease: memory only. grant = min(now + TTL, horizon) (Clamp); refused while uncertain or when it leaves no +\* validity; deadline = max(deadline, grant); triggers an extension when the horizon is closer than TTL + Margin. MasterRenew == \E m \in msgs : /\ m.t = "renew" /\ LET okLine == asg.holder = m.h /\ asg.epoch = m.e - live == lease.none \/ (now < lease.exp /\ now < deadline) + Reply(ok, v, rv) == [t |-> "lease", h |-> m.h, s |-> m.s, ok |-> ok, valid |-> v, revoking |-> rv] + grant == IF Clamp THEN Min(now + TTL, lease.exp) ELSE now + TTL IN IF okLine /\ ~lease.none /\ lease.revoking - THEN /\ msgs' = (msgs \ {m}) \cup {[t |-> "lease", h |-> m.h, s |-> m.s, ok |-> TRUE, valid |-> lease.exp - now, revoking |-> TRUE]} - /\ UNCHANGED <> - ELSE IF okLine /\ live - THEN /\ lease' = [holder |-> m.h, epoch |-> m.e, exp |-> now + TTL, revoking |-> FALSE, none |-> FALSE] + THEN /\ msgs' = (msgs \ {m}) \cup {Reply(TRUE, Min(lease.exp, deadline) - now, TRUE)} + /\ UNCHANGED <> + ELSE IF okLine /\ lease.none /\ ~uncertain + THEN /\ lease' = [holder |-> m.h, epoch |-> m.e, exp |-> now + TTL + HSlack, revoking |-> FALSE, none |-> FALSE] + /\ dhz' = now + TTL + HSlack /\ deadline' = now + TTL - /\ msgs' = (msgs \ {m}) \cup {[t |-> "lease", h |-> m.h, s |-> m.s, ok |-> TRUE, valid |-> TTL, revoking |-> FALSE]} - ELSE /\ msgs' = (msgs \ {m}) \cup {[t |-> "lease", h |-> m.h, s |-> m.s, ok |-> FALSE, valid |-> 0, revoking |-> FALSE]} - /\ UNCHANGED <> - /\ UNCHANGED <> + /\ msgs' = (msgs \ {m}) \cup {Reply(TRUE, TTL, FALSE)} + /\ extReq' = extReq + ELSE IF okLine /\ ~lease.none /\ now < lease.exp /\ now < deadline /\ ~uncertain /\ grant > now + THEN /\ deadline' = Max(deadline, grant) + /\ extReq' = IF lease.exp < now + TTL + Margin /\ extReq < 0 THEN now ELSE extReq + /\ msgs' = (msgs \ {m}) \cup {Reply(TRUE, grant - now, FALSE)} + /\ UNCHANGED <> + ELSE /\ msgs' = (msgs \ {m}) \cup {Reply(FALSE, 0, FALSE)} + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* the extender (#205, workspace_lease_view.go extendWorkspaceLease): an ordinary writer serialized with every other +\* write; it rechecks the lease and writes H = trigger + TTL + HSlack. Success publishes H. A failed write latches +\* uncertain whether or not it landed on disk (ExtFail). A failed recheck is a known no-write. +MasterExtend == + /\ extReq >= 0 + /\ LET H == extReq + TTL + HSlack + ok == /\ ~lease.none /\ ~lease.revoking /\ ~uncertain + /\ lease.holder = asg.holder /\ lease.epoch = asg.epoch /\ H > lease.exp + IN IF ok + THEN \/ /\ lease' = [lease EXCEPT !.exp = H] /\ dhz' = H /\ uncertain' = uncertain + \/ /\ ExtFail /\ lease' = lease /\ dhz' = dhz /\ uncertain' = TRUE \* failed, nothing landed + \/ /\ ExtFail /\ lease' = lease /\ dhz' = H /\ uncertain' = TRUE \* landed, reply lost + ELSE UNCHANGED <> + /\ extReq' = -1 + /\ UNCHANGED <> \* the host applies a reply (workspace_lease.go:88-127): the OLD deadline is checked first HostLease == \E m \in msgs : @@ -153,7 +203,7 @@ HostLease == \E m \in msgs : ![h].until = IF m.ok /\ ~fence /\ ~host[h].fenced THEN m.s + m.valid ELSE @] /\ msgs' = msgs \ {m} /\ hist' = [hist EXCEPT !.aStopT = IF m.h = "A" /\ hist.aStopT < 0 /\ m.revoking THEN now ELSE hist.aStopT] - /\ UNCHANGED <> + /\ UNCHANGED <> \* drain then clean ACK with the last committed HEAD gen, only while the lease is valid (:129-160) SendAck == @@ -161,35 +211,39 @@ SendAck == /\ host["A"].until > HNow("A") /\ host["A"].lh.gen # 0 /\ ~\E m \in msgs : m.t = "ack" /\ msgs' = msgs \cup {[t |-> "ack", h |-> "A", e |-> host["A"].epoch, gen |-> host["A"].lh.gen]} - /\ UNCHANGED <> + /\ UNCHANGED <> -\* Publisher.AckWorkspaceRevocation (authority/workspace.go:215-235) +\* Publisher.AckWorkspaceRevocation (authority/workspace.go:215-235): a durable write (refused while uncertain) MasterAck == \E m \in msgs : /\ m.t = "ack" /\ msgs' = msgs \ {m} /\ IF asg.holder = m.h /\ asg.epoch = m.e /\ m.gen # 0 /\ ~lease.none /\ lease.revoking - /\ now < lease.exp /\ now < deadline + /\ now < lease.exp /\ now < deadline /\ ~uncertain THEN ack' = [gen |-> m.gen, holder |-> m.h, epoch |-> m.e] ELSE ack' = ack - /\ UNCHANGED <> + /\ UNCHANGED <> -\* operator: BeginWorkspaceRevocation (authority/workspace.go:200-213) +\* operator: BeginWorkspaceRevocation (authority/workspace.go:200-213): a durable write (refused while uncertain) Revoke == /\ "clean" \in Kinds /\ ~lease.none /\ ~lease.revoking /\ lease.holder = asg.holder /\ asg.holder = "A" + /\ ~uncertain /\ lease' = [lease EXCEPT !.revoking = TRUE] - /\ UNCHANGED <> + /\ UNCHANGED <> \* operator / orchestrator: stop guest I/O on A before the final cut StopGuest == /\ "clean" \in Kinds /\ ~host["A"].stopIO /\ host' = [host EXCEPT !["A"].stopIO = TRUE] /\ hist' = [hist EXCEPT !.aStopT = IF hist.aStopT < 0 THEN now ELSE hist.aStopT] - /\ UNCHANGED <> + /\ UNCHANGED <> -\* blockmaster restart: durable state kept; the in-memory deadline conservatively -\* covers a full TTL again (authority.go:256-261) +\* blockmaster restart: the published state is reloaded from disk (so the published horizon becomes dhz), the +\* in-memory deadline conservatively covers a full TTL again (authority.go reloadFromStore), uncertainty and any +\* pending extension are gone MasterRestart == /\ restarts < MaxRestarts /\ restarts' = restarts + 1 /\ deadline' = now + TTL - /\ UNCHANGED <> + /\ lease' = IF lease.none THEN lease ELSE [lease EXCEPT !.exp = dhz] + /\ uncertain' = FALSE /\ extReq' = -1 + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* the move (workspace_service.go:100-145, authority/workspace.go:157-198, 287-335) *) @@ -197,15 +251,17 @@ MasterRestart == /\ restarts < MaxRestarts \* the HEAD is read before the publisher lock (workspace_service.go:104-109) MoveRead == /\ mv.st = "none" /\ asg.holder = "A" /\ \E k \in Kinds : mv' = [st |-> "read", kind |-> k, h |-> head] - /\ UNCHANGED <> + /\ UNCHANGED <> +\* a durable write (refused while uncertain, authority.go apply); the forced barrier reads the published horizon +\* and the in-memory deadline MovePrepare == /\ mv.st = "read" /\ LET q == mv.h headOK == q.gen # 0 /\ q.epoch = asg.epoch /\ q.holder = asg.holder cleanOK == q.st = "detached" /\ ~lease.none /\ lease.revoking /\ ack.gen = q.gen /\ ack.epoch = asg.epoch forcedOK == ~WaitLeaseExpiry \/ (now >= lease.exp /\ now >= deadline) - ok == headOK /\ ~lease.none /\ IF mv.kind = "clean" THEN cleanOK ELSE forcedOK + ok == headOK /\ ~lease.none /\ ~uncertain /\ IF mv.kind = "clean" THEN cleanOK ELSE forcedOK IN IF ok THEN /\ maxEpoch' = maxEpoch + 1 /\ journal' = [kind |-> mv.kind, gen |-> q.gen, lsn |-> q.lsn, newEpoch |-> maxEpoch + 1] @@ -216,7 +272,7 @@ MovePrepare == /\ mv' = [mv EXCEPT !.st = "done"] ELSE /\ mv' = [st |-> "none", kind |-> "-", h |-> NoRec] \* refused; may be retried /\ UNCHANGED <> - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* B: VOLUME hook -> attach -> seed -> takeover CAS -> serve @@ -229,23 +285,23 @@ BAssign == \E m \in msgs : /\ msgs' = msgs \ {m} /\ host' = [host EXCEPT !["B"].epoch = m.e] /\ bpc' = "hook" - /\ UNCHANGED <> + /\ UNCHANGED <> BHook == /\ bpc = "hook" /\ bpc' = "attach" /\ Step("hook") \* EnsureVolume / attach check (provider_chunk.go:240-247) - /\ UNCHANGED <> + /\ UNCHANGED <> BAttach == /\ bpc = "attach" \* ClaimChunkHead: GetHead (chunk_restore.go:30-36) /\ IF head.epoch > host["B"].epoch THEN /\ bpc' = "failed" /\ bobs' = bobs /\ hist' = hist ELSE /\ bpc' = "seed" /\ bobs' = head /\ Step("attach") - /\ UNCHANGED <> + /\ UNCHANGED <> BSeed == /\ bpc = "seed" \* PrepareRestore -> SeedChunkFrontier (provider_chunk.go:286-307) /\ LET L == IF SeedFromObserved THEN bobs.lsn ELSE journal.lsn IN /\ host' = [host EXCEPT !["B"].lsn = L] /\ hist' = [hist EXCEPT !.steps = Append(hist.steps, "seed"), !.bSeed = L] /\ bpc' = "claim" - /\ UNCHANGED <> + /\ UNCHANGED <> BClaim == /\ bpc = "claim" \* the takeover CAS (chunk_restore.go:55-79) /\ LET next == [bobs EXCEPT !.gen = bobs.gen + 1, !.epoch = host["B"].epoch, !.holder = "B", @@ -257,7 +313,7 @@ BClaim == /\ bpc = "claim" \* the takeover /\ hist' = [hist EXCEPT !.steps = Append(hist.steps, "claim"), !.takeover = TRUE, !.bFirst = next] ELSE /\ bpc' = "attach" \* not installed: the attach is retried /\ UNCHANGED <> - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* the chunk layer's cut on host h (chunk_layer.go:680-988) *) @@ -271,20 +327,20 @@ CutStart(h, det) == /\ LayerLsnCheck => host[h].lsn >= host[h].lh.lsn \* lsn_behind (:800) /\ cut' = [cut EXCEPT ![h] = [pc |-> "intent", n |-> @.n, base |-> host[h].lh, lsn |-> host[h].lsn, img |-> <>, detach |-> det]] - /\ UNCHANGED <> + /\ UNCHANGED <> CutIntent(h) == \* PutIntent before any upload (:853, :1489) /\ cut[h].pc = "intent" /\ intents' = intents \cup {[own |-> h, n |-> cut[h].n + 1, epoch |-> host[h].epoch, key |-> cut[h].img, created |-> now]} /\ cut' = [cut EXCEPT ![h].pc = "upload"] - /\ UNCHANGED <> + /\ UNCHANGED <> CutUpload(h) == /\ cut[h].pc = "upload" /\ stored' = stored \cup {cut[h].img} /\ hist' = [hist EXCEPT !.late = IF h = "A" /\ hist.takeover THEN @ \cup {cut[h].img} ELSE @] /\ cut' = [cut EXCEPT ![h].pc = "admit"] - /\ UNCHANGED <> + /\ UNCHANGED <> DropOwn(h) == {i \in intents : ~(i.own = h /\ i.n = cut[h].n + 1)} @@ -293,7 +349,7 @@ CutAdmit(h) == \* admis /\ IF Permits(h) /\ (~HostFence \/ ~SupersededBy(h, host[h].lh)) THEN /\ cut' = [cut EXCEPT ![h].pc = "cas"] /\ intents' = intents ELSE /\ cut' = [cut EXCEPT ![h].pc = "idle", ![h].n = @ + 1] /\ intents' = DropOwn(h) - /\ UNCHANGED <> + /\ UNCHANGED <> CutCAS(h) == \* CASHead (:926), then settle by re-read (:957-987) /\ cut[h].pc = "cas" @@ -312,13 +368,13 @@ CutCAS(h) == \* CASHe ELSE [host EXCEPT ![h].lh = head] /\ hist' = hist /\ cut' = [cut EXCEPT ![h].pc = "drop"] - /\ UNCHANGED <> + /\ UNCHANGED <> CutDrop(h) == \* DeleteIntent after settling (:1378-1421) /\ cut[h].pc = "drop" /\ intents' = DropOwn(h) /\ cut' = [cut EXCEPT ![h].pc = "idle", ![h].n = @ + 1] - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* GC (core/frontend/chunkstore/gc.go:108-300) *) @@ -330,20 +386,20 @@ GCExpire == \E i \in intents : /\ GCEpochRule => (maxEpoch > i.epoch /\ head.epoch > i.epoch /\ head.epoch <= maxEpoch) /\ intents' = intents \ {i} /\ hist' = [hist EXCEPT !.badExpire = @ \/ (i.epoch = head.epoch /\ i.own = head.holder)] - /\ UNCHANGED <> + /\ UNCHANGED <> \* mark + sweep, atomic: roots are HEAD and live intents (grace abstracted, as in ChunkLifecycle) GCCollect == LET roots == {head.img} \cup {i.key : i \in intents} IN /\ stored \ roots # {} /\ stored' = stored \cap roots - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- Next == \/ Tick \/ SlowTick \/ LoseMsg \/ \E h \in Hosts : VMWrite(h) \/ SendRenew(h) \/ CutStart(h, FALSE) \/ CutStart(h, TRUE) \/ CutIntent(h) \/ CutUpload(h) \/ CutAdmit(h) \/ CutCAS(h) \/ CutDrop(h) - \/ MasterRenew \/ HostLease \/ SendAck \/ MasterAck \/ Revoke \/ StopGuest \/ MasterRestart + \/ MasterRenew \/ MasterExtend \/ HostLease \/ SendAck \/ MasterAck \/ Revoke \/ StopGuest \/ MasterRestart \/ MoveRead \/ MovePrepare \/ BAssign \/ BHook \/ BAttach \/ BSeed \/ BClaim \/ GCExpire \/ GCCollect @@ -388,11 +444,21 @@ SeedMatchesTakeover == hist.bFirst # NoRec => hist.bSeed = hist.bFirst.lsn \* HEAD epoch and remote_lsn never decrease HeadMonotone == [][head'.epoch >= head.epoch /\ head'.lsn >= head.lsn]_vars +\* #205 (S1, scoped to the active lease): the current holder's validity never exceeds the published horizon, and the +\* published horizon never exceeds the disk; they are equal unless a write outcome is unknown +HostWithinHorizon == ~lease.none => + \A h \in Hosts : (h = lease.holder /\ host[h].epoch = lease.epoch) => host[h].until <= lease.exp +DiskCoversMemory == ~lease.none => (lease.exp <= dhz /\ (~uncertain => lease.exp = dhz)) + \* reachability witnesses (each is EXPECTED to be violated) W_NoCleanServe == ~(journal.kind = "clean" /\ Serving("B") /\ hist.acked["A"] > 0) W_NoForcedServe == ~(journal.kind = "forced" /\ Serving("B") /\ hist.acked["A"] > 0) W_NoBCut == ~(head.holder = "B" /\ hist.bFirst # NoRec /\ head.gen > hist.bFirst.gen) W_NoRestartMove == ~(restarts > 0 /\ hist.takeover) +W_NoExtension == ~(~lease.none /\ lease.epoch = 1 /\ lease.exp > TTL + HSlack) \* an extension raised A's horizon +W_NoExtLanded == ~(~lease.none /\ dhz > lease.exp) \* a failed extension landed on disk +W_NoUncertain == ~uncertain TypeOK == /\ now \in 0..MaxT /\ head.gen \in Nat /\ stored \subseteq (Hosts \X (0..MaxCuts)) + /\ uncertain \in BOOLEAN /\ extReq \in -1..MaxT ============================================================================= diff --git a/seaweed-block/docs/spec/cfg/RED_early_assign.cfg b/seaweed-block/docs/spec/cfg/RED_early_assign.cfg index c2789b527e..9ca9fc16d6 100644 --- a/seaweed-block/docs/spec/cfg/RED_early_assign.cfg +++ b/seaweed-block/docs/spec/cfg/RED_early_assign.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = FALSE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing diff --git a/seaweed-block/docs/spec/cfg/RED_epoch.cfg b/seaweed-block/docs/spec/cfg/RED_epoch.cfg index c4947609dd..55b77b11b9 100644 --- a/seaweed-block/docs/spec/cfg/RED_epoch.cfg +++ b/seaweed-block/docs/spec/cfg/RED_epoch.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoOldCasAfterTakeover diff --git a/seaweed-block/docs/spec/cfg/RED_epoch_hostonly.cfg b/seaweed-block/docs/spec/cfg/RED_epoch_hostonly.cfg index 4884ce7a5f..627215a43f 100644 --- a/seaweed-block/docs/spec/cfg/RED_epoch_hostonly.cfg +++ b/seaweed-block/docs/spec/cfg/RED_epoch_hostonly.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoOldCasAfterTakeover NoLateChunkReachable diff --git a/seaweed-block/docs/spec/cfg/RED_epoch_storeonly.cfg b/seaweed-block/docs/spec/cfg/RED_epoch_storeonly.cfg index 163650f5d2..16cf2005e8 100644 --- a/seaweed-block/docs/spec/cfg/RED_epoch_storeonly.cfg +++ b/seaweed-block/docs/spec/cfg/RED_epoch_storeonly.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoOldCasAfterTakeover NoLateChunkReachable diff --git a/seaweed-block/docs/spec/cfg/RED_gc_ageonly.cfg b/seaweed-block/docs/spec/cfg/RED_gc_ageonly.cfg index 7181fb20b7..7a33af37c6 100644 --- a/seaweed-block/docs/spec/cfg/RED_gc_ageonly.cfg +++ b/seaweed-block/docs/spec/cfg/RED_gc_ageonly.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = FALSE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK GCSafe diff --git a/seaweed-block/docs/spec/cfg/RED_hz_noclamp.cfg b/seaweed-block/docs/spec/cfg/RED_hz_noclamp.cfg new file mode 100644 index 0000000000..60d5d9620a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RED_hz_noclamp.cfg @@ -0,0 +1,22 @@ +\* RED_hz_noclamp: #205 RED (EXPECTED violated): renewal answered from memory WITHOUT the horizon clamp grants validity beyond the durable horizon (run from docs/spec: ./run.sh RED_hz_noclamp) +SPECIFICATION Spec +CONSTANTS + Kinds = {"forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = FALSE + ExtFail = FALSE +INVARIANT TypeOK HostWithinHorizon diff --git a/seaweed-block/docs/spec/cfg/RED_hz_noclamp_safety.cfg b/seaweed-block/docs/spec/cfg/RED_hz_noclamp_safety.cfg new file mode 100644 index 0000000000..ffbc8c68a0 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RED_hz_noclamp_safety.cfg @@ -0,0 +1,23 @@ +\* RED_hz_noclamp_safety: #205 control: without the clamp the restart rule still covers grants (expected to pass: the clamp is for S1 and fail-closed, not split-brain) (run from docs/spec: ./run.sh RED_hz_noclamp_safety) +SPECIFICATION Spec +CONSTANTS + Kinds = {"forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = FALSE + ExtFail = FALSE +INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable ForcedLossBounded GCSafe +PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/RED_lsn.cfg b/seaweed-block/docs/spec/cfg/RED_lsn.cfg index 146314a001..37a1b25034 100644 --- a/seaweed-block/docs/spec/cfg/RED_lsn.cfg +++ b/seaweed-block/docs/spec/cfg/RED_lsn.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = FALSE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK TypeOK PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/RED_lsn_storeonly.cfg b/seaweed-block/docs/spec/cfg/RED_lsn_storeonly.cfg index ee6c562e7b..a959a95480 100644 --- a/seaweed-block/docs/spec/cfg/RED_lsn_storeonly.cfg +++ b/seaweed-block/docs/spec/cfg/RED_lsn_storeonly.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_both.cfg b/seaweed-block/docs/spec/cfg/W4_both.cfg index defb4bbe28..5ebc51c670 100644 --- a/seaweed-block/docs/spec/cfg/W4_both.cfg +++ b/seaweed-block/docs/spec/cfg/W4_both.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_clean.cfg b/seaweed-block/docs/spec/cfg/W4_clean.cfg index a96f132365..75787a5b90 100644 --- a/seaweed-block/docs/spec/cfg/W4_clean.cfg +++ b/seaweed-block/docs/spec/cfg/W4_clean.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_clean_large.cfg b/seaweed-block/docs/spec/cfg/W4_clean_large.cfg index ed97a39b60..7cc398a976 100644 --- a/seaweed-block/docs/spec/cfg/W4_clean_large.cfg +++ b/seaweed-block/docs/spec/cfg/W4_clean_large.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_drift.cfg b/seaweed-block/docs/spec/cfg/W4_drift.cfg index 5a3f44b966..bafbe79583 100644 --- a/seaweed-block/docs/spec/cfg/W4_drift.cfg +++ b/seaweed-block/docs/spec/cfg/W4_drift.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing diff --git a/seaweed-block/docs/spec/cfg/W4_drift_heads.cfg b/seaweed-block/docs/spec/cfg/W4_drift_heads.cfg index 78d42cea93..a7d97c0ed3 100644 --- a/seaweed-block/docs/spec/cfg/W4_drift_heads.cfg +++ b/seaweed-block/docs/spec/cfg/W4_drift_heads.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoOldCasAfterTakeover NoLateChunkReachable ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_forced.cfg b/seaweed-block/docs/spec/cfg/W4_forced.cfg index d29d30835b..4bc6d011bb 100644 --- a/seaweed-block/docs/spec/cfg/W4_forced.cfg +++ b/seaweed-block/docs/spec/cfg/W4_forced.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_forced_exact.cfg b/seaweed-block/docs/spec/cfg/W4_forced_exact.cfg index 24ff032104..81b5759336 100644 --- a/seaweed-block/docs/spec/cfg/W4_forced_exact.cfg +++ b/seaweed-block/docs/spec/cfg/W4_forced_exact.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK ForcedLossExact diff --git a/seaweed-block/docs/spec/cfg/W4_forced_large.cfg b/seaweed-block/docs/spec/cfg/W4_forced_large.cfg index 7888ba01b0..cc517ff834 100644 --- a/seaweed-block/docs/spec/cfg/W4_forced_large.cfg +++ b/seaweed-block/docs/spec/cfg/W4_forced_large.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_hz_both.cfg b/seaweed-block/docs/spec/cfg/W4_hz_both.cfg new file mode 100644 index 0000000000..65971e9d11 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/W4_hz_both.cfg @@ -0,0 +1,23 @@ +\* W4_hz_both: #205 durable horizon, both move kinds, failing extensions, one restart (run from docs/spec: ./run.sh W4_hz_both) +SPECIFICATION Spec +CONSTANTS + Kinds = {"clean", "forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = TRUE +INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover HostWithinHorizon DiskCoversMemory +PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_hz_clean.cfg b/seaweed-block/docs/spec/cfg/W4_hz_clean.cfg new file mode 100644 index 0000000000..7173d26318 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/W4_hz_clean.cfg @@ -0,0 +1,23 @@ +\* W4_hz_clean: #205 durable horizon, clean move, extension writes may fail landed or not, one restart (run from docs/spec: ./run.sh W4_hz_clean) +SPECIFICATION Spec +CONSTANTS + Kinds = {"clean"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = TRUE +INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover HostWithinHorizon DiskCoversMemory +PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_hz_forced.cfg b/seaweed-block/docs/spec/cfg/W4_hz_forced.cfg new file mode 100644 index 0000000000..63720fa5f9 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/W4_hz_forced.cfg @@ -0,0 +1,23 @@ +\* W4_hz_forced: #205 durable horizon, forced move, extension writes may fail landed or not, one restart (run from docs/spec: ./run.sh W4_hz_forced) +SPECIFICATION Spec +CONSTANTS + Kinds = {"forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = TRUE +INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover HostWithinHorizon DiskCoversMemory +PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_hz_reach_ext.cfg b/seaweed-block/docs/spec/cfg/W4_hz_reach_ext.cfg new file mode 100644 index 0000000000..4b2ae416f2 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/W4_hz_reach_ext.cfg @@ -0,0 +1,22 @@ +\* W4_hz_reach_ext: #205 witness (EXPECTED violated): an extension raises the holder's horizon (run from docs/spec: ./run.sh W4_hz_reach_ext) +SPECIFICATION Spec +CONSTANTS + Kinds = {"forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE +INVARIANT TypeOK W_NoExtension diff --git a/seaweed-block/docs/spec/cfg/W4_hz_reach_landed.cfg b/seaweed-block/docs/spec/cfg/W4_hz_reach_landed.cfg new file mode 100644 index 0000000000..aa1264372e --- /dev/null +++ b/seaweed-block/docs/spec/cfg/W4_hz_reach_landed.cfg @@ -0,0 +1,22 @@ +\* W4_hz_reach_landed: #205 witness (EXPECTED violated): a failed extension lands on disk above the published horizon (run from docs/spec: ./run.sh W4_hz_reach_landed) +SPECIFICATION Spec +CONSTANTS + Kinds = {"forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = TRUE +INVARIANT TypeOK W_NoExtLanded diff --git a/seaweed-block/docs/spec/cfg/W4_hz_reach_uncertain_restart.cfg b/seaweed-block/docs/spec/cfg/W4_hz_reach_uncertain_restart.cfg new file mode 100644 index 0000000000..22a4b4f678 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/W4_hz_reach_uncertain_restart.cfg @@ -0,0 +1,22 @@ +\* W4_hz_reach_uncertain_restart: #205 witness (EXPECTED violated): with failing extensions a restart followed by a takeover is still reachable (run from docs/spec: ./run.sh W4_hz_reach_uncertain_restart) +SPECIFICATION Spec +CONSTANTS + Kinds = {"forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = TRUE +INVARIANT TypeOK W_NoRestartMove diff --git a/seaweed-block/docs/spec/cfg/W4_reach_bcut.cfg b/seaweed-block/docs/spec/cfg/W4_reach_bcut.cfg index 3201dfe6cf..b8515809cb 100644 --- a/seaweed-block/docs/spec/cfg/W4_reach_bcut.cfg +++ b/seaweed-block/docs/spec/cfg/W4_reach_bcut.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK W_NoBCut diff --git a/seaweed-block/docs/spec/cfg/W4_reach_clean.cfg b/seaweed-block/docs/spec/cfg/W4_reach_clean.cfg index dcc1ec1e69..95f11e83dc 100644 --- a/seaweed-block/docs/spec/cfg/W4_reach_clean.cfg +++ b/seaweed-block/docs/spec/cfg/W4_reach_clean.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK W_NoCleanServe diff --git a/seaweed-block/docs/spec/cfg/W4_reach_forced.cfg b/seaweed-block/docs/spec/cfg/W4_reach_forced.cfg index 58436d68e6..e810bc52e6 100644 --- a/seaweed-block/docs/spec/cfg/W4_reach_forced.cfg +++ b/seaweed-block/docs/spec/cfg/W4_reach_forced.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK W_NoForcedServe diff --git a/seaweed-block/docs/spec/cfg/W4_reach_restart.cfg b/seaweed-block/docs/spec/cfg/W4_reach_restart.cfg index 991eb9dca9..160fb8d535 100644 --- a/seaweed-block/docs/spec/cfg/W4_reach_restart.cfg +++ b/seaweed-block/docs/spec/cfg/W4_reach_restart.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK W_NoRestartMove diff --git a/seaweed-block/docs/workspace-lease.md b/seaweed-block/docs/workspace-lease.md index e310ecbda9..bb089340fe 100644 --- a/seaweed-block/docs/workspace-lease.md +++ b/seaweed-block/docs/workspace-lease.md @@ -35,9 +35,38 @@ mutex then guard state mutex. Canceled renewal replies cannot publish a grant. renewal intervals for the 30s lease). Set a positive bound below 60s that covers the deployment's clock drift. The bound is persisted with each lease; a restart or smaller setting cannot shorten an outstanding grant's bound. -The master grants a FORCED move only after both the stored expiry and its -conservative restart deadline plus the full bound. `ValidForNs` in lease +The master grants a FORCED move only after both the persisted lease horizon +and the granted or conservative restart deadline plus the full bound. `ValidForNs` in lease replies excludes half the bound. Hosts anchor that shortened duration to request start, self-fencing early without comparing remote wall-clock times. Delayed replies cannot extend admission. The bound is an operational clock assumption; arbitrarily stopped or unbounded clocks are not covered. + +## Master-side renewal + +Blockmaster answers a renewal of an established lease from memory: it takes +only a small leaf lock, writes nothing and never waits for another authority +write or a lifecycle store write. The grant is the smaller of now plus the TTL +and the durable horizon, the lease expiry stored on disk. A grant that would +leave the host no validity (grant minus half the skew bound not after now) is +refused with an error, so the host keeps its remaining validity instead of +fencing on an invalid reply. + +Only the first grant of a lease is written synchronously; it stores a horizon +of now plus 1.5 times the TTL. When a renewal finds the horizon less than +1.25 times the TTL ahead, it starts one background extension for that volume. +The extension is an ordinary authority write under the publisher lock and +stores the renewal time plus 1.5 times the TTL. A failed extension write is +an unknown outcome: the volume becomes uncertain, renewals that would issue a +new or extended grant are refused, and its host fences within its current +validity. A Revoking lease still gets its bounded drain reply, never extended. A restart reloads the stored +horizon, and a FORCED move waits for that horizon plus the skew bound. + +All authority writes stay serialized. With N live leases and store write time +P, extensions stay ahead without shortening grants only while N·P is below +TTL/4 minus one host renewal interval r (about (TTL − skew/2)/3), and hosts +stay unfenced while N·P stays below 1.25·TTL − skew/2 − 2r (about 14 s at the +defaults). Beyond that, grants shrink and hosts fence: the design fails +closed. Blockmaster logs one warning per failure streak, with the write's +latency and the remaining horizon, when an extension fails, and one when +grants start to be clamped to the horizon, and a line when either recovers.