From dc877aa4b51302853b512ec4c4a7521c6254b10a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 03:48:38 -0800 Subject: [PATCH 1/4] volume: RED: a workspace lease fence must name its cause Issue #205: under sustained write load a volume fenced because its lease renewals kept failing until the lease expired, and nothing said so. The shutdown path logged nothing; the only trace was the raw RPC error printed at closeout. The fence itself is correct. Two tests fail on main: - a renewal that times out past the lease deadline fences (as today), but the returned error must say the lease expired and keep the RPC error, and the fence and its cause must be logged; - a renewal that fails while the lease is still valid must be logged with its latency (it does not fence). Co-Authored-By: Claude Opus 5.5 --- .../host/volume/workspace_lease_cause_test.go | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 seaweed-block/core/host/volume/workspace_lease_cause_test.go diff --git a/seaweed-block/core/host/volume/workspace_lease_cause_test.go b/seaweed-block/core/host/volume/workspace_lease_cause_test.go new file mode 100644 index 0000000000..647a5df8c7 --- /dev/null +++ b/seaweed-block/core/host/volume/workspace_lease_cause_test.go @@ -0,0 +1,118 @@ +package volume + +import ( + "bytes" + "context" + "errors" + "log" + "strings" + "sync" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// lockedBuffer collects log output from the guard (log.Printf may be called +// from more than one goroutine in other tests of this package). +type lockedBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (l *lockedBuffer) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.Write(p) +} + +func (l *lockedBuffer) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.String() +} + +func captureLog(t *testing.T) *lockedBuffer { + t.Helper() + buf := &lockedBuffer{} + prevOut, prevFlags := log.Writer(), log.Flags() + log.SetOutput(buf) + t.Cleanup(func() { log.SetOutput(prevOut); log.SetFlags(prevFlags) }) + return buf +} + +// Issue #205: under sustained write load a volume fenced because its lease +// renewals kept failing until the lease expired, and nothing said so: the +// shutdown path logged nothing and the only trace was the raw RPC error at +// closeout. The fence is correct; it must name its cause. +func TestWorkspaceLeaseRenewalTimeoutFenceNamesItsCause(t *testing.T) { + logs := captureLog(t) + now := time.Unix(1000, 0) + calls, stops := 0, 0 + client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + calls++ + if calls == 1 { + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(time.Second)}, nil + } + // A slow master: the renewal RPC runs past the lease deadline and times out. + now = now.Add(3 * time.Second) + return nil, context.DeadlineExceeded + }} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { stops++; return 7, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + err = g.Refresh(context.Background()) + if err == nil { + t.Fatal("a renewal that failed past the deadline did not fence") + } + if stops != 1 { + t.Fatalf("fence did not stop the volume: stops=%d", stops) + } + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("the renewal error was lost: %v", err) + } + if !strings.Contains(err.Error(), "workspace lease expired") { + t.Fatalf("the returned error does not name the cause: %q", err) + } + out := logs.String() + if !strings.Contains(out, "workspace lease: fenced") || !strings.Contains(out, "renewal failed") { + t.Fatalf("the fence and its cause were not logged; log=%q", out) + } +} + +// A renewal that fails while the lease is still valid does not fence, but it +// must be visible with its latency: a run of these is the early warning. +func TestWorkspaceLeaseRenewalFailureIsLoggedWithLatency(t *testing.T) { + logs := captureLog(t) + now := time.Unix(1000, 0) + calls := 0 + client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + calls++ + if calls == 1 { + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(10 * time.Second)}, nil + } + now = now.Add(2 * time.Second) + return nil, context.DeadlineExceeded + }} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err == nil { + t.Fatal("the failed renewal was not reported to the caller") + } + if !g.Projection().Healthy { + t.Fatal("a failed renewal inside the lease fenced the volume") + } + out := logs.String() + if !strings.Contains(out, "renewal failed after 2s") { + t.Fatalf("the failed renewal and its latency were not logged; log=%q", out) + } +} From 6896463a4474fa855de4e95ce813d90e7f351068 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 03:50:08 -0800 Subject: [PATCH 2/4] volume: name the cause when the workspace lease guard fences The guard fenced silently: when renewals kept failing until the lease expired, it drained the volume through blockvolume's lease-stop path, which logged nothing, and returned the raw RPC error (issue #205). - Every fence records its first cause: lease expired without a successful renewal, expired after a failed renewal (with the renewal's latency and error), an invalid reply, a reply that arrived after the deadline, revocation by the master, or shutdown. The guard logs it once as "workspace lease: fenced ...", FenceCause() returns it, and the non-ACK drain error carries it. - Every failed renewal is logged with its latency and the lease deadline, also when the lease is still valid: a run of them is the warning before an expiry fence. - An expiry after a failed renewal returns "workspace lease expired: renewal failed after : ", wrapping the RPC error. - blockvolume logs when it stops because the guard requested the drain. The fence behaviour itself is unchanged. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/main.go | 3 + .../core/host/volume/workspace_lease.go | 68 ++++++++++++++++--- 2 files changed, 62 insertions(+), 9 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index e1fefb3756..96935591bd 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -1168,6 +1168,9 @@ func run(f flags) int { select { case <-shutdownCtx.Done(): case request := <-leaseRequests: + // The lease guard fenced and asks for the drain; it logs its cause as + // "workspace lease: fenced ...". Say here that this is why we stop (#205). + fmt.Fprintln(os.Stderr, "blockvolume: stopping: the workspace lease guard fenced and requested the drain") leaseStop = &request case err := <-leaseDone: fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err) diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index dad21b65fb..22a8bd671b 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -3,6 +3,7 @@ package volume import ( "context" "fmt" + "log" "sync" "time" @@ -34,6 +35,38 @@ type WorkspaceLeaseGuard struct { stopped bool headGen uint64 revoked bool + // cause says why the guard fenced (the first reason wins); logged once, + // because the shutdown it triggers is otherwise silent (issue #205). + cause string + logged bool +} + +// fenceLocked latches the fence and records its first cause. Caller holds mu. +func (g *WorkspaceLeaseGuard) fenceLocked(cause string) { + g.fenced = true + if g.cause == "" { + g.cause = cause + } +} + +// FenceCause is why the guard fenced, or "" while it has not. +func (g *WorkspaceLeaseGuard) FenceCause() string { + g.mu.Lock() + defer g.mu.Unlock() + return g.cause +} + +// logFence logs the fence and its cause once. Never called with mu held. +func (g *WorkspaceLeaseGuard) logFence() { + g.mu.Lock() + if !g.fenced || g.logged { + g.mu.Unlock() + return + } + g.logged = true + cause := g.cause + g.mu.Unlock() + log.Printf("workspace lease: fenced volume=%s replica=%s epoch=%d: %s", g.id.VolumeId, g.id.ReplicaId, g.id.Epoch, cause) } func NewWorkspaceLeaseGuard(base frontend.ProjectionView, client WorkspaceLeaseClient, id *control.WorkspaceIdentity, stop func(context.Context) (uint64, error), now func() time.Time) (*WorkspaceLeaseGuard, error) { @@ -58,7 +91,7 @@ func (g *WorkspaceLeaseGuard) permits(p frontend.Projection) bool { g.mu.Lock() defer g.mu.Unlock() if !g.until.IsZero() && !g.now().Before(g.until) { - g.fenced = true + g.fenceLocked(fmt.Sprintf("lease expired at %s without a successful renewal", g.until.UTC().Format(time.RFC3339Nano))) } return !g.fenced && !g.until.IsZero() && p.VolumeID == g.id.VolumeId && p.ReplicaID == g.id.ReplicaId && p.Epoch == g.id.Epoch } @@ -73,11 +106,12 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { start := g.now() g.mu.Lock() if !g.until.IsZero() && !start.Before(g.until) { - g.fenced = true + g.fenceLocked(fmt.Sprintf("lease expired at %s without a successful renewal", g.until.UTC().Format(time.RFC3339Nano))) } fenced, until := g.fenced, g.until g.mu.Unlock() if fenced { + g.logFence() return g.drain(ctx, g.revoked) } rpcCtx, cancel := context.WithTimeout(ctx, 2*time.Second) @@ -89,40 +123,52 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { defer cancel() reply, err := g.client.RenewWorkspaceLease(rpcCtx, &g.id) if err != nil { + elapsed := g.now().Sub(start).Round(time.Millisecond) g.mu.Lock() expired := !g.until.IsZero() && !g.now().Before(g.until) if expired { - g.fenced = true + g.fenceLocked(fmt.Sprintf("lease expired after a failed renewal (renewal failed after %s: %v)", elapsed, err)) } g.mu.Unlock() + // Every failed renewal is visible with its latency: a run of them is the + // warning before an expiry fence (issue #205). + log.Printf("workspace lease: renewal failed after %s volume=%s epoch=%d (lease valid until %s): %v", + elapsed, g.id.VolumeId, g.id.Epoch, until.UTC().Format(time.RFC3339Nano), err) if expired { + g.logFence() _ = g.drain(ctx, false) + return fmt.Errorf("workspace lease expired: renewal failed after %s: %w", elapsed, err) } return err } if reply.GetVolumeId() != g.id.VolumeId || reply.GetReplicaId() != g.id.ReplicaId || reply.GetEpoch() != g.id.Epoch || reply.GetValidForNs() <= 0 || reply.GetValidForNs() > int64(30*time.Second) { g.mu.Lock() - g.fenced = true + g.fenceLocked(fmt.Sprintf("invalid lease reply (volume=%q replica=%q epoch=%d validForNs=%d)", reply.GetVolumeId(), reply.GetReplicaId(), reply.GetEpoch(), reply.GetValidForNs())) g.mu.Unlock() + g.logFence() _ = g.drain(ctx, false) return fmt.Errorf("invalid workspace lease reply") } g.mu.Lock() // Check the OLD deadline before accepting a newer grant. In particular a // reply received after expiry cannot undo a fence latched by a frontend. - if ctx.Err() != nil || rpcCtx.Err() != nil || (!g.until.IsZero() && !g.now().Before(g.until)) || !g.now().Before(start.Add(time.Duration(reply.ValidForNs))) { - g.fenced = true + switch { + case ctx.Err() != nil: + g.fenceLocked("shutdown while a renewal was in flight") + case rpcCtx.Err() != nil || (!g.until.IsZero() && !g.now().Before(g.until)) || !g.now().Before(start.Add(time.Duration(reply.ValidForNs))): + g.fenceLocked(fmt.Sprintf("renewal reply arrived after the lease deadline (renewal took %s)", g.now().Sub(start).Round(time.Millisecond))) } if !g.fenced { g.until = start.Add(time.Duration(reply.ValidForNs)) } if reply.Revoking { - g.fenced = true + g.fenceLocked("revoked by the master") g.revoked = true } closed := g.fenced g.mu.Unlock() if closed { + g.logFence() return g.drain(ctx, reply.Revoking) } return nil @@ -159,7 +205,10 @@ func (g *WorkspaceLeaseGuard) drain(parent context.Context, ack bool) error { _, err := g.client.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: &g.id, HeadGen: g.headGen}) return err } - return fmt.Errorf("workspace lease fenced") + g.mu.Lock() + cause := g.cause + g.mu.Unlock() + return fmt.Errorf("workspace lease fenced: %s", cause) } // Run owns renewal and physical close. Projection independently checks expiry, @@ -189,8 +238,9 @@ func (g *WorkspaceLeaseGuard) Run(ctx context.Context) error { case <-ctx.Done(): g.operation.Lock() g.mu.Lock() - g.fenced = true + g.fenceLocked("shutdown requested (context cancelled)") g.mu.Unlock() + g.logFence() err := g.drain(ctx, false) g.operation.Unlock() return err From aa6b0cecc88636b6ab858460b1dc694c5945c3b1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 04:02:23 -0800 Subject: [PATCH 3/4] volume: say which limit a failed renewal reached; keep the cause on a failed stop Review fold for #207: - A failed renewal now logs whether the call reached the lease deadline, the 2s per-call timeout, or neither, so a slow master is told apart from a lease that ran out. - A stop that fails after a fence returns an error that names the fence cause and wraps the stop error; after a renewal expiry or an invalid reply both the renewal error and the stop error are kept (errors.Is). - Tests assert the first cause wins, the fence is logged once, the cause carries the exact deadline, and a late revoking reply keeps the late-reply cause. - The #205 test comment states the renewal-failure trigger as a hypothesis that matches the code path, not a diagnosis the logs proved. Co-Authored-By: Claude Opus 5.5 --- .../core/host/volume/workspace_lease.go | 61 ++++++-- .../host/volume/workspace_lease_cause_test.go | 134 +++++++++++++++++- 2 files changed, 178 insertions(+), 17 deletions(-) diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index 22a8bd671b..6515cc2a2f 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -114,7 +114,7 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { g.logFence() return g.drain(ctx, g.revoked) } - rpcCtx, cancel := context.WithTimeout(ctx, 2*time.Second) + rpcCtx, cancel := context.WithTimeout(ctx, renewalRPCTimeout) if !until.IsZero() { var c context.CancelFunc rpcCtx, c = context.WithDeadline(rpcCtx, until) @@ -123,21 +123,23 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { defer cancel() reply, err := g.client.RenewWorkspaceLease(rpcCtx, &g.id) if err != nil { - elapsed := g.now().Sub(start).Round(time.Millisecond) + end := g.now() + elapsed := end.Sub(start).Round(time.Millisecond) + hit := renewalLimitHit(start, end, until) g.mu.Lock() - expired := !g.until.IsZero() && !g.now().Before(g.until) + expired := !g.until.IsZero() && !end.Before(g.until) if expired { - g.fenceLocked(fmt.Sprintf("lease expired after a failed renewal (renewal failed after %s: %v)", elapsed, err)) + g.fenceLocked(fmt.Sprintf("lease expired after a failed renewal (renewal failed after %s, %s: %v)", elapsed, hit, err)) } g.mu.Unlock() - // Every failed renewal is visible with its latency: a run of them is the - // warning before an expiry fence (issue #205). - log.Printf("workspace lease: renewal failed after %s volume=%s epoch=%d (lease valid until %s): %v", - elapsed, g.id.VolumeId, g.id.Epoch, until.UTC().Format(time.RFC3339Nano), err) + // Every failed renewal is visible with its latency and with which limit, + // if any, the call reached: a run of them is the warning before an expiry + // fence (issue #205). + log.Printf("workspace lease: renewal failed after %s volume=%s epoch=%d (%s; lease valid until %s): %v", + elapsed, g.id.VolumeId, g.id.Epoch, hit, until.UTC().Format(time.RFC3339Nano), err) if expired { g.logFence() - _ = g.drain(ctx, false) - return fmt.Errorf("workspace lease expired: renewal failed after %s: %w", elapsed, err) + return g.drainAfterFence(ctx, fmt.Errorf("workspace lease expired: renewal failed after %s (%s): %w", elapsed, hit, err)) } return err } @@ -146,8 +148,7 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { g.fenceLocked(fmt.Sprintf("invalid lease reply (volume=%q replica=%q epoch=%d validForNs=%d)", reply.GetVolumeId(), reply.GetReplicaId(), reply.GetEpoch(), reply.GetValidForNs())) g.mu.Unlock() g.logFence() - _ = g.drain(ctx, false) - return fmt.Errorf("invalid workspace lease reply") + return g.drainAfterFence(ctx, fmt.Errorf("invalid workspace lease reply")) } g.mu.Lock() // Check the OLD deadline before accepting a newer grant. In particular a @@ -174,13 +175,47 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { return nil } +// renewalRPCTimeout bounds one renewal call; the lease deadline may bound it +// sooner (Refresh). +const renewalRPCTimeout = 2 * time.Second + +// renewalLimitHit says which limit a failed renewal call had reached when it +// returned, on the guard's clock: the lease deadline (when it came before the +// per-call timeout), the 2 s per-call timeout, or neither (the call failed +// for another reason). It separates a slow master from a dead lease. +func renewalLimitHit(start, end, until time.Time) string { + callLimit := start.Add(renewalRPCTimeout) + switch { + case !until.IsZero() && until.Before(callLimit) && !end.Before(until): + return "the call reached the lease deadline" + case !end.Before(callLimit): + return "the call reached the 2s renewal timeout" + default: + return "the call failed before any deadline" + } +} + +// drainAfterFence drains after a fence and returns err. If the stop itself +// failed, its error (which names the fence cause) is kept next to err. +// Caller holds operation. +func (g *WorkspaceLeaseGuard) drainAfterFence(ctx context.Context, err error) error { + derr := g.drain(ctx, false) + if !g.stopped { + return fmt.Errorf("%w; %w", err, derr) + } + return err +} + func (g *WorkspaceLeaseGuard) drain(parent context.Context, ack bool) error { if !g.stopped { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) gen, err := g.stop(ctx) cancel() if err != nil { - return err + g.mu.Lock() + cause := g.cause + g.mu.Unlock() + return fmt.Errorf("workspace lease fenced (%s): stop failed: %w", cause, err) } g.headGen, g.stopped = gen, true } diff --git a/seaweed-block/core/host/volume/workspace_lease_cause_test.go b/seaweed-block/core/host/volume/workspace_lease_cause_test.go index 647a5df8c7..7885221127 100644 --- a/seaweed-block/core/host/volume/workspace_lease_cause_test.go +++ b/seaweed-block/core/host/volume/workspace_lease_cause_test.go @@ -41,10 +41,11 @@ func captureLog(t *testing.T) *lockedBuffer { return buf } -// Issue #205: under sustained write load a volume fenced because its lease -// renewals kept failing until the lease expired, and nothing said so: the -// shutdown path logged nothing and the only trace was the raw RPC error at -// closeout. The fence is correct; it must name its cause. +// Issue #205: under sustained write load a volume stopped and nothing said +// why: the shutdown path logged nothing and the only trace was a raw +// DeadlineExceeded at closeout. Renewals failing until the lease expired is a +// hypothesis that matches the code path, not something the logs proved. A +// fence must name its cause so the next occurrence settles it. func TestWorkspaceLeaseRenewalTimeoutFenceNamesItsCause(t *testing.T) { logs := captureLog(t) now := time.Unix(1000, 0) @@ -82,6 +83,14 @@ func TestWorkspaceLeaseRenewalTimeoutFenceNamesItsCause(t *testing.T) { if !strings.Contains(out, "workspace lease: fenced") || !strings.Contains(out, "renewal failed") { t.Fatalf("the fence and its cause were not logged; log=%q", out) } + // The lease (1s) ended before the 2s per-call timeout: the log must say the + // call ran into the lease deadline, not that the RPC timed out on its own. + if !strings.Contains(out, "reached the lease deadline") || strings.Contains(out, "2s renewal timeout") { + t.Fatalf("the log does not say which limit the call reached; log=%q", out) + } + if !strings.Contains(g.FenceCause(), "lease expired after a failed renewal") { + t.Fatalf("FenceCause = %q", g.FenceCause()) + } } // A renewal that fails while the lease is still valid does not fence, but it @@ -115,4 +124,121 @@ func TestWorkspaceLeaseRenewalFailureIsLoggedWithLatency(t *testing.T) { if !strings.Contains(out, "renewal failed after 2s") { t.Fatalf("the failed renewal and its latency were not logged; log=%q", out) } + // The lease (10s) outlives the call: this failure is the 2s per-call + // timeout, a slow master, not a lease that ran out. + if !strings.Contains(out, "reached the 2s renewal timeout") || strings.Contains(out, "lease deadline") { + t.Fatalf("the log does not say the 2s call timeout was reached; log=%q", out) + } + if g.FenceCause() != "" { + t.Fatalf("a failure inside the lease recorded a fence cause: %q", g.FenceCause()) + } +} + +// The first cause wins and is logged once: a frontend that notices expiry +// latches the cause with the exact deadline; the later drain, and a second +// Refresh, keep it and do not log the fence again. +func TestWorkspaceLeaseFirstFenceCauseWinsAndIsLoggedOnce(t *testing.T) { + logs := captureLog(t) + now := time.Unix(1000, 0) + renewals, stops := 0, 0 + client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + renewals++ + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(time.Second)}, nil + }} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { stops++; return 7, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + now = now.Add(2 * time.Second) + if g.Projection().Healthy { + t.Fatal("expired lease served") + } + const first = "lease expired at 1970-01-01T00:16:41Z without a successful renewal" + if got := g.FenceCause(); got != first { + t.Fatalf("FenceCause = %q, want %q", got, first) + } + err = g.Refresh(context.Background()) + if err == nil || !strings.Contains(err.Error(), first) { + t.Fatalf("drain error does not carry the first cause: %v", err) + } + if err := g.Refresh(context.Background()); err == nil { + t.Fatal("fenced guard reopened") + } + if got := g.FenceCause(); got != first { + t.Fatalf("the first cause was replaced: %q", got) + } + if renewals != 1 || stops != 1 { + t.Fatalf("renewals=%d stops=%d, want 1 and 1", renewals, stops) + } + if n := strings.Count(logs.String(), "workspace lease: fenced"); n != 1 { + t.Fatalf("fence logged %d times, want once; log=%q", n, logs.String()) + } +} + +// A late reply that also carries a revocation keeps the first cause (the late +// reply), not the revocation that arrived with it. +func TestWorkspaceLeaseLateRevokingReplyKeepsTheFirstCause(t *testing.T) { + captureLog(t) + now := time.Unix(1000, 0) + renewals := 0 + client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + renewals++ + if renewals > 1 { + now = now.Add(3 * time.Second) // the reply arrives after the 1s lease ended + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(time.Second), Revoking: true}, nil + } + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(time.Second)}, nil + }, ack: func() error { t.Fatal("an expired lease must not ACK"); return nil }} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err == nil { + t.Fatal("a late reply did not fence") + } + if got := g.FenceCause(); !strings.HasPrefix(got, "renewal reply arrived after the lease deadline") { + t.Fatalf("FenceCause = %q, want the late reply", got) + } +} + +// A stop that fails after a fence must not hide the cause: the returned error +// names the cause and keeps both the stop error and the renewal error. +func TestWorkspaceLeaseFailedStopKeepsTheCause(t *testing.T) { + captureLog(t) + errStop := errors.New("frontend close failed") + now := time.Unix(1000, 0) + calls := 0 + client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + calls++ + if calls == 1 { + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(time.Second)}, nil + } + now = now.Add(3 * time.Second) + return nil, context.DeadlineExceeded + }} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 0, errStop }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + err = g.Refresh(context.Background()) + if !errors.Is(err, errStop) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("the stop or renewal error was lost: %v", err) + } + if !strings.Contains(err.Error(), "stop failed") || !strings.Contains(err.Error(), "lease expired after a failed renewal") { + t.Fatalf("the error does not name the cause and the failed stop: %q", err) + } + // The next Refresh retries the stop through the fenced path: same cause. + err = g.Refresh(context.Background()) + if !errors.Is(err, errStop) || !strings.Contains(err.Error(), "lease expired after a failed renewal") { + t.Fatalf("the retried stop lost the cause: %v", err) + } } From c902547a448b444f6fa2f4f78f98939796add9fa Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 04:12:40 -0800 Subject: [PATCH 4/4] volume: name which limit a late renewal reply missed Review fold for #207: a valid reply that lands after the renewal call's context ended, while the old lease and the new grant are still valid, was recorded as "arrived after the lease deadline". The refusal is unchanged; the cause now says which limit the reply missed: the lease deadline, its own grant, or the call's context (with the lease's remaining validity). Adds a bounded regression where the reply lands just after the 2s call timeout with a 20s lease. Co-Authored-By: Claude Opus 5.5 --- .../core/host/volume/workspace_lease.go | 8 ++- .../host/volume/workspace_lease_cause_test.go | 68 +++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index 6515cc2a2f..cf99b03c73 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -156,8 +156,14 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { switch { case ctx.Err() != nil: g.fenceLocked("shutdown while a renewal was in flight") - case rpcCtx.Err() != nil || (!g.until.IsZero() && !g.now().Before(g.until)) || !g.now().Before(start.Add(time.Duration(reply.ValidForNs))): + // A late reply is refused in all three cases; the cause names which limit + // it missed, so a valid lease is not reported as an expired one. + case !g.until.IsZero() && !g.now().Before(g.until): g.fenceLocked(fmt.Sprintf("renewal reply arrived after the lease deadline (renewal took %s)", g.now().Sub(start).Round(time.Millisecond))) + case !g.now().Before(start.Add(time.Duration(reply.ValidForNs))): + g.fenceLocked(fmt.Sprintf("renewal reply arrived after its own grant ended (renewal took %s)", g.now().Sub(start).Round(time.Millisecond))) + case rpcCtx.Err() != nil: + g.fenceLocked(fmt.Sprintf("renewal reply arrived after the renewal call's context ended (renewal took %s; lease still valid until %s)", g.now().Sub(start).Round(time.Millisecond), g.until.UTC().Format(time.RFC3339Nano))) } if !g.fenced { g.until = start.Add(time.Duration(reply.ValidForNs)) diff --git a/seaweed-block/core/host/volume/workspace_lease_cause_test.go b/seaweed-block/core/host/volume/workspace_lease_cause_test.go index 7885221127..59f3e27714 100644 --- a/seaweed-block/core/host/volume/workspace_lease_cause_test.go +++ b/seaweed-block/core/host/volume/workspace_lease_cause_test.go @@ -11,6 +11,7 @@ import ( "time" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" ) // lockedBuffer collects log output from the guard (log.Printf may be called @@ -242,3 +243,70 @@ func TestWorkspaceLeaseFailedStopKeepsTheCause(t *testing.T) { t.Fatalf("the retried stop lost the cause: %v", err) } } + +// ctxLeaseClient answers a renewal only once the call's context has ended, +// like a reply that lands just after the 2s per-call timeout. +type ctxLeaseClient struct{ validFor time.Duration } + +func (c ctxLeaseClient) RenewWorkspaceLease(ctx context.Context, _ *control.WorkspaceIdentity, _ ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + if ctx.Err() == nil { + select { + case <-ctx.Done(): + case <-time.After(5 * time.Second): // bound: the 2s call timeout ends it first + } + } + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(c.validFor)}, nil +} + +func (ctxLeaseClient) AckWorkspaceRevoked(context.Context, *control.WorkspaceRevocationAck, ...grpc.CallOption) (*control.WorkspaceEmpty, error) { + return &control.WorkspaceEmpty{}, nil +} + +// A valid reply that arrives after the renewal call's 2s context ended, while +// the old lease and the new grant are both still valid, is still refused, but +// its cause must say the call's context ended, not that the lease expired. +func TestWorkspaceLeaseReplyAfterCallTimeoutIsNotCalledAnExpiry(t *testing.T) { + captureLog(t) + first := true + slow := ctxLeaseClient{validFor: 20 * time.Second} + renew := func(ctx context.Context, id *control.WorkspaceIdentity, o ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + if first { + first = false + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(20 * time.Second)}, nil + } + return slow.RenewWorkspaceLease(ctx, id, o...) + } + stops := 0 + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, funcLeaseClient(renew), &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { stops++; return 7, nil }, nil) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + began := time.Now() + if err := g.Refresh(context.Background()); err == nil { + t.Fatal("a reply after the call's context ended was accepted") + } + if took := time.Since(began); took > 4*time.Second { + t.Fatalf("the late call was not bounded by the 2s timeout: %s", took) + } + if stops != 1 { + t.Fatalf("stops=%d, want 1 (the refusal is unchanged)", stops) + } + cause := g.FenceCause() + if !strings.HasPrefix(cause, "renewal reply arrived after the renewal call's context ended") || strings.Contains(cause, "lease deadline") { + t.Fatalf("FenceCause = %q, want the call-context cause, not an expiry", cause) + } +} + +// funcLeaseClient adapts a function to WorkspaceLeaseClient (renewals only). +type funcLeaseClient func(context.Context, *control.WorkspaceIdentity, ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) + +func (f funcLeaseClient) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity, o ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + return f(ctx, id, o...) +} + +func (funcLeaseClient) AckWorkspaceRevoked(context.Context, *control.WorkspaceRevocationAck, ...grpc.CallOption) (*control.WorkspaceEmpty, error) { + return &control.WorkspaceEmpty{}, nil +}