From 48b4a36bfe54607c099bc9bd897e16ce8e27eaac Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 20:26:53 -0800 Subject: [PATCH 01/34] test: master link must reconnect within 2 s after a long outage (red) Co-Authored-By: Claude Opus 5.5 --- .../core/host/volume/master_reconnect_test.go | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 seaweed-block/core/host/volume/master_reconnect_test.go diff --git a/seaweed-block/core/host/volume/master_reconnect_test.go b/seaweed-block/core/host/volume/master_reconnect_test.go new file mode 100644 index 0000000000..296871e02d --- /dev/null +++ b/seaweed-block/core/host/volume/master_reconnect_test.go @@ -0,0 +1,78 @@ +package volume + +import ( + "context" + "io" + "log" + "net" + "testing" + "time" + + "google.golang.org/grpc" + + "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +type heartbeatSink struct { + control.UnimplementedObservationServiceServer + got chan struct{} +} + +func (s *heartbeatSink) ReportHeartbeat(context.Context, *control.HeartbeatReport) (*control.HeartbeatAck, error) { + select { + case s.got <- struct{}{}: + default: + } + return &control.HeartbeatAck{}, nil +} + +// A volume process now waits for an unreachable master instead of exiting, +// so its one master channel lives through the whole outage. With gRPC's +// default reconnect back-off (1 s growing x1.6 to 120 s) the step is +// already about 17 s after a 45 s outage, and the first heartbeat after +// the master returns can lag by that much. The master link must reconnect +// within about 2 s of the master's return, however long the outage was. +func TestMasterLinkReconnectsWithinTwoSeconds(t *testing.T) { + if testing.Short() { + t.Skip("45 s outage") + } + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().String() + _ = l.Close() // the master is down: connects are refused + + h, err := New(Config{MasterAddr: addr, ServerID: "s1", VolumeID: "v1", ReplicaID: "r1", + DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304", + HeartbeatInterval: 200 * time.Millisecond, Logger: log.New(io.Discard, "", 0)}) + if err != nil { + t.Fatal(err) + } + h.Start() + t.Cleanup(func() { _ = h.Close() }) + + time.Sleep(45 * time.Second) // let the connect failures run up the back-off + + l, err = net.Listen("tcp", addr) + if err != nil { + t.Fatalf("relisten %s: %v", addr, err) + } + srv := grpc.NewServer() + sink := &heartbeatSink{got: make(chan struct{}, 1)} + control.RegisterObservationServiceServer(srv, sink) + back := time.Now() + go func() { _ = srv.Serve(l) }() + t.Cleanup(srv.Stop) + + select { + case <-sink.got: + lag := time.Since(back) + t.Logf("first heartbeat %v after the master returned", lag.Round(10*time.Millisecond)) + if lag > 2400*time.Millisecond { + t.Fatalf("master link reconnected %v after the master returned; want <= 2.4 s", lag.Round(10*time.Millisecond)) + } + case <-time.After(60 * time.Second): + t.Fatal("no heartbeat within 60 s of the master's return") + } +} From 630451644fa15460c8daa68bdda20659a1e94fa0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 20:45:57 -0800 Subject: [PATCH 02/34] fix: cap the blockmaster link's reconnect back-off at 2 s A volume process will wait through a master outage on one channel, so gRPC's default back-off (to 120 s) would delay the first call after the master returns by up to two minutes. Only the two blockmaster dials change; MinConnectTimeout stays 5 s for the handshake. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/chunk_maintenance.go | 2 +- seaweed-block/core/host/volume/host.go | 2 +- .../core/host/volume/master_reconnect_test.go | 5 +++-- seaweed-block/core/rpc/link/link.go | 18 ++++++++++++++++++ 4 files changed, 23 insertions(+), 4 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance.go b/seaweed-block/cmd/blockvolume/chunk_maintenance.go index 943619d0dd..766e6dd30f 100644 --- a/seaweed-block/cmd/blockvolume/chunk_maintenance.go +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance.go @@ -26,7 +26,7 @@ func newChunkMaintenance(cat *chunkstore.Catalog, blobs chunkstore.BlobDeleter, if defaultChunkGCGrace <= max(defaultChunkCutTimeout, chunkstore.DefaultOpDeadline)+defaultChunkMaintenanceTimeout { return nil, closeFn, errors.New("automatic GC grace does not cover cut/copy and mark bounds") } - conn, err := link.Dial(master) + conn, err := link.Dial(master, link.MasterReconnect()) if err != nil { return nil, closeFn, err } diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 78b5613748..0e1797403b 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -267,7 +267,7 @@ func New(cfg Config) (*Host, error) { lg = log.Default() } - conn, err := link.Dial(cfg.MasterAddr) + conn, err := link.Dial(cfg.MasterAddr, link.MasterReconnect()) if err != nil { return nil, fmt.Errorf("volume.New: dial master %q: %w", cfg.MasterAddr, err) } diff --git a/seaweed-block/core/host/volume/master_reconnect_test.go b/seaweed-block/core/host/volume/master_reconnect_test.go index 296871e02d..26ae72814c 100644 --- a/seaweed-block/core/host/volume/master_reconnect_test.go +++ b/seaweed-block/core/host/volume/master_reconnect_test.go @@ -69,8 +69,9 @@ func TestMasterLinkReconnectsWithinTwoSeconds(t *testing.T) { case <-sink.got: lag := time.Since(back) t.Logf("first heartbeat %v after the master returned", lag.Round(10*time.Millisecond)) - if lag > 2400*time.Millisecond { - t.Fatalf("master link reconnected %v after the master returned; want <= 2.4 s", lag.Round(10*time.Millisecond)) + // 2 s cap + 20 % jitter, plus one 200 ms heartbeat tick once connected. + if lag > 2600*time.Millisecond { + t.Fatalf("master link reconnected %v after the master returned; want <= 2.6 s", lag.Round(10*time.Millisecond)) } case <-time.After(60 * time.Second): t.Fatal("no heartbeat within 60 s of the master's return") diff --git a/seaweed-block/core/rpc/link/link.go b/seaweed-block/core/rpc/link/link.go index b67617a799..d115893da8 100644 --- a/seaweed-block/core/rpc/link/link.go +++ b/seaweed-block/core/rpc/link/link.go @@ -6,7 +6,10 @@ package link import ( + "time" + "google.golang.org/grpc" + "google.golang.org/grpc/backoff" "google.golang.org/grpc/credentials/insecure" ) @@ -45,3 +48,18 @@ func NewServer(cfg ServerConfig, opts ...grpc.ServerOption) *grpc.Server { all = append(all, opts...) return grpc.NewServer(all...) } + +// MasterReconnect caps the reconnect back-off of a long-lived link to +// blockmaster. A volume process waits for an unreachable master instead of +// exiting, so one channel can live through a long outage; with gRPC's default +// back-off (base 1 s, x1.6, jitter 0.2, max 120 s: grpc@v1.80.0 +// backoff/backoff.go:48-51) the first call after the master returns could lag +// by up to two minutes. Capped at 2 s, the lag stays about 2 s. The connect +// timeout must be set: WithConnectParams otherwise makes it equal to the +// back-off step (dialoptions.go:313-314), too short for a TLS handshake. +func MasterReconnect() grpc.DialOption { + return grpc.WithConnectParams(grpc.ConnectParams{ + Backoff: backoff.Config{BaseDelay: time.Second, Multiplier: 1.6, Jitter: 0.2, MaxDelay: 2 * time.Second}, + MinConnectTimeout: 5 * time.Second, + }) +} From 4d9f2426402182760c5bcc4e1ba19535c69d4847 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 20:59:55 -0800 Subject: [PATCH 03/34] feat: typed kind on lease renewal refusals RenewWorkspaceLease refusals carry a WorkspaceLeaseRefusal status detail (code and text unchanged): BARRIER with the time left until the forced-move barrier passes, MOVED only when the published line names another replica or a newer epoch owned by another known server, DELETED only for a committed deletion. Everything else carries none (OTHER). The barrier comes from a typed error, never from the text. Co-Authored-By: Claude Opus 5.5 --- .../core/authority/workspace_lease_view.go | 21 +- .../workspace_lease_refusal_kind_test.go | 159 ++++++++++ .../core/host/master/workspace_service.go | 43 ++- .../core/lifecycle/deletion_reservations.go | 11 + .../core/rpc/control/workspace.pb.go | 277 +++++++++++++----- seaweed-block/core/rpc/proto/workspace.proto | 9 + 6 files changed, 439 insertions(+), 81 deletions(-) create mode 100644 seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index b4c08095cf..617b93e927 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -374,9 +374,10 @@ func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder st if p.store == nil || p.workspaceUncertain[volume] { return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain") } - _, now, err := p.forcedMoveBarrierLocked(volume, s.Lease) + lostUntil, now, err := p.forcedMoveBarrierLocked(volume, s.Lease) if err != nil { - return WorkspaceLease{}, err + until := time.Unix(0, lostUntil) + return WorkspaceLease{}, &LeaseBarrierError{Until: until, RetryAfter: max(until.Sub(now), 0), err: err} } lease, grant := p.newWorkspaceLease(holder, epoch, now) lease.ExpiresAtNS = max(lease.ExpiresAtNS, s.Lease.ExpiresAtNS) @@ -472,3 +473,19 @@ func (p *Publisher) CloseWorkspaceExtenders() { p.mu.Unlock() p.extWG.Wait() } + +// LeaseBarrierError is an expired re-grant refused because the forced-move +// barrier has not passed. Until is when it passes (master wall time) and +// RetryAfter is Until minus the master's time at the refusal, so a client +// can anchor it to its own request start. The text keeps the barrier's. +type LeaseBarrierError struct { + Until time.Time + RetryAfter time.Duration + err error +} + +func (e *LeaseBarrierError) Error() string { + return fmt.Sprintf("%v (re-grant refused until %s, in %s)", e.err, e.Until.UTC().Format(time.RFC3339Nano), e.RetryAfter.Round(time.Millisecond)) +} + +func (e *LeaseBarrierError) Unwrap() error { return e.err } diff --git a/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go b/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go new file mode 100644 index 0000000000..d3b71ead19 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go @@ -0,0 +1,159 @@ +package master + +import ( + "context" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// refusalOf returns the FailedPrecondition refusal's text and its typed +// detail (nil when the refusal carries none, which a client reads as OTHER). +func refusalOf(t *testing.T, stage string, err error) (string, *control.WorkspaceLeaseRefusal) { + t.Helper() + st, ok := status.FromError(err) + if err == nil || !ok || st.Code() != codes.FailedPrecondition { + t.Fatalf("%s: %v; want a FailedPrecondition refusal", stage, err) + } + for _, d := range st.Details() { + if r, ok := d.(*control.WorkspaceLeaseRefusal); ok { + return st.Message(), r + } + } + return st.Message(), nil +} + +// Each renewal refusal carries its typed kind as a status detail with the +// code and text unchanged: BARRIER (with the time left until the barrier +// passes) for an expired re-grant before the barrier; MOVED only when the +// line names another replica; DELETED only for a committed deletion. The +// same owner at a newer epoch and an admitted (abortable) deletion carry no +// detail (OTHER): a bounded wait, never an early 78. +func TestLeaseRefusalKinds(t *testing.T) { + var nowNS, headEpoch, headGen atomic.Int64 + nowNS.Store(time.Now().UnixNano()) + headEpoch.Store(1) + headGen.Store(9) + const ttl = 30 * time.Second + h, conn, _ := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: uint64(headGen.Load()), Epoch: uint64(headEpoch.Load()), Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil + }, func(h *Host) { + authority.WithWorkspaceLeaseConfig(ttl, func() time.Time { return time.Unix(0, nowNS.Load()) })(h.Publisher()) + }) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + t.Cleanup(cancel) + reviewCreate(t, conn, ctx, "v") + ws := control.NewWorkspaceServiceClient(conn) + b := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "v", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + reviewHeartbeat(t, conn, ctx, "v", "node-a", b.DataAddr, b.CtrlAddr) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + line := waitAuthorityLine(t, h.Publisher(), "v") + id := func(replica string, epoch uint64) *control.WorkspaceIdentity { + return &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: replica, Epoch: epoch, ServerId: "node-a"} + } + e1 := id("r1", line.Epoch) + if _, err := ws.RenewWorkspaceLease(ctx, e1); err != nil { + t.Fatal("first grant:", err) + } + + // BARRIER: past the grant (TTL) but before the horizon (1.5 TTL) plus + // the default skew (2/3 TTL), i.e. 65 s after the grant. + nowNS.Add(int64(40 * time.Second)) + text, r := refusalOf(t, "expired re-grant before the barrier", func() error { _, err := ws.RenewWorkspaceLease(ctx, e1); return err }()) + if r == nil || r.GetKind() != control.WorkspaceLeaseRefusal_BARRIER { + t.Fatalf("re-grant before the barrier: detail %v; want BARRIER", r) + } + if left := time.Duration(r.GetRetryAfterNs()); left < 24*time.Second || left > 26*time.Second { + t.Fatalf("BARRIER retry_after %v; want 25 s (the barrier 65 s after the grant, now +40 s)", left) + } + if !strings.HasPrefix(text, "workspace forced move lease expiry plus clock-skew margin has not elapsed") || !strings.Contains(text, "re-grant refused until") { + t.Fatalf("BARRIER text %q: want the barrier text with its time", text) + } + nowNS.Add(int64(2 * time.Minute)) + if _, err := ws.RenewWorkspaceLease(ctx, e1); err != nil { + t.Fatal("re-grant after the barrier:", err) + } + + // cleanMove revokes and ACKs the current holder, then moves the line on + // the same host to replica. + cleanMove := func(req string, from *control.WorkspaceIdentity, replica string) uint64 { + t.Helper() + if _, err := ws.RevokeWorkspace(ctx, from); err != nil { + t.Fatal(err) + } + headEpoch.Store(int64(from.GetEpoch())) + headGen.Add(1) + if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: from, HeadGen: uint64(headGen.Load())}); err != nil { + t.Fatal(err) + } + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + g, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: req, VolumeId: "v", ExpectedReplicaId: from.GetReplicaId(), ExpectedEpoch: from.GetEpoch(), + TargetReplicaId: replica, TargetServerId: "node-a", TargetDataAddr: b.DataAddr, TargetCtrlAddr: b.CtrlAddr, Kind: "clean"}) + if err != nil { + t.Fatal(err) + } + return g.GetNewEpoch() + } + + // OTHER: the same owner at a newer epoch (a clean move back to this host). + e2 := id("r1", cleanMove("same-replica", e1, "r1")) + text, r = refusalOf(t, "same owner, newer epoch", func() error { _, err := ws.RenewWorkspaceLease(ctx, e1); return err }()) + if r != nil || text != "workspace lease: server identity does not match the current holder" { + t.Fatalf("same owner at a newer epoch: %q detail %v; want the unchanged text, no detail", text, r) + } + if _, err := ws.RenewWorkspaceLease(ctx, e2); err != nil { + t.Fatal("grant at the newer epoch:", err) + } + + // MOVED: the line names another replica. + e3 := id("r2", cleanMove("other-replica", e2, "r2")) + text, r = refusalOf(t, "line names another replica", func() error { _, err := ws.RenewWorkspaceLease(ctx, e2); return err }()) + if r == nil || r.GetKind() != control.WorkspaceLeaseRefusal_MOVED || text != "workspace lease: server identity does not match the current holder" { + t.Fatalf("line names another replica: %q detail %v; want MOVED with the unchanged text", text, r) + } + + // An admitted deletion is OTHER; a committed one is DELETED. + if _, err := ws.RenewWorkspaceLease(ctx, e3); err != nil { + t.Fatal("grant to the moved replica:", err) + } + if _, err := ws.RevokeWorkspace(ctx, e3); err != nil { + t.Fatal(err) + } + headEpoch.Store(int64(e3.GetEpoch())) + headGen.Add(1) + if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: e3, HeadGen: uint64(headGen.Load())}); err != nil { + t.Fatal(err) + } + res, err := control.NewLifecycleServiceClient(conn).MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-1"}) + if err != nil || res.GetState() != lifecycle.ReservationAdmitted { + t.Fatalf("admit the delete: %+v %v", res, err) + } + text, r = refusalOf(t, "admitted deletion", func() error { _, err := ws.RenewWorkspaceLease(ctx, e3); return err }()) + if r != nil || text != "workspace: volume is being deleted" { + t.Fatalf("admitted deletion: %q detail %v; want the unchanged text, no detail", text, r) + } + if _, err := h.lifecycle.Deletions.Commit("v", "del-1"); err != nil { + t.Fatal(err) + } + text, r = refusalOf(t, "committed deletion", func() error { _, err := ws.RenewWorkspaceLease(ctx, e3); return err }()) + if r == nil || r.GetKind() != control.WorkspaceLeaseRefusal_DELETED || text != "workspace: volume is being deleted" { + t.Fatalf("committed deletion: %q detail %v; want DELETED with the unchanged text", text, r) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 04981c09fa..5022645205 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -49,11 +49,44 @@ func (s *services) workspaceVolumeForRenewal(volume string) error { return status.Error(codes.FailedPrecondition, "workspace move requires an existing RF1 volume") } if s.host.lifecycle.Deletions.ReservedSnapshot(volume) { + if s.host.lifecycle.Deletions.CommittedSnapshot(volume) { + return leaseRefusal("workspace: volume is being deleted", control.WorkspaceLeaseRefusal_DELETED, 0) + } return status.Error(codes.FailedPrecondition, "workspace: volume is being deleted") } return nil } +// leaseRefusal is a renewal refusal with its typed kind as a status detail +// (code FailedPrecondition and text as before). Only BARRIER, MOVED and +// DELETED are sent; a refusal without a detail is OTHER. +func leaseRefusal(text string, kind control.WorkspaceLeaseRefusal_Kind, retryAfter time.Duration) error { + st := status.New(codes.FailedPrecondition, text) + if d, err := st.WithDetails(&control.WorkspaceLeaseRefusal{Kind: kind, RetryAfterNs: int64(retryAfter)}); err == nil { + st = d + } + return st.Err() +} + +// renewalMoved reports whether a holder mismatch is a permanent, known move: +// the published line names another replica, or a newer epoch of this replica +// owned by another known server. An unknown owner, the same owner at a newer +// epoch, or no line is not (OTHER: a bounded wait, then exit 75). +func (s *services) renewalMoved(volume, replica, server string, epoch uint64) bool { + line, ok := s.host.Publisher().PublishedAuthorityLine(volume) + if !ok || server == "" { + return false + } + if line.ReplicaID != replica { + return true + } + if line.Epoch <= epoch { + return false + } + owner := s.host.workspaceLineOwner(line, volume, line.ReplicaID, line.Epoch) + return owner != "" && owner != server +} + // isWorkspaceVolume reports whether volume is a workspace volume (workspace RPC on, an existing RF1 volume), from the // lock-free lifecycle snapshot. Unlike workspaceVolumeForRenewal it ignores a deletion reservation: a volume being // deleted is still a workspace volume, and its assignment stream keeps the holder host check. @@ -105,9 +138,17 @@ func (s *services) RenewWorkspaceLease(ctx context.Context, q *control.Workspace if ok, err := s.holderMatches(ctx, q.GetVolumeId(), q.GetReplicaId(), q.GetServerId(), q.GetEpoch()); err != nil { return nil, status.Error(codes.FailedPrecondition, err.Error()) } else if !ok { - return nil, status.Error(codes.FailedPrecondition, "workspace lease: server identity does not match the current holder") + const text = "workspace lease: server identity does not match the current holder" + if s.renewalMoved(q.GetVolumeId(), q.GetReplicaId(), q.GetServerId(), q.GetEpoch()) { + return nil, leaseRefusal(text, control.WorkspaceLeaseRefusal_MOVED, 0) + } + return nil, status.Error(codes.FailedPrecondition, text) } l, err := s.host.Publisher().RenewWorkspaceLease(ctx, q.GetVolumeId(), q.GetReplicaId(), q.GetEpoch()) + var barrier *authority.LeaseBarrierError + if errors.As(err, &barrier) { + return nil, leaseRefusal(err.Error(), control.WorkspaceLeaseRefusal_BARRIER, barrier.RetryAfter) + } if err != nil { return nil, workspaceError(err) } diff --git a/seaweed-block/core/lifecycle/deletion_reservations.go b/seaweed-block/core/lifecycle/deletion_reservations.go index a27cda7245..86994e7a67 100644 --- a/seaweed-block/core/lifecycle/deletion_reservations.go +++ b/seaweed-block/core/lifecycle/deletion_reservations.go @@ -134,6 +134,17 @@ func (s *DeletionReservationStore) ReservedSnapshot(vol string) bool { return ok } +// CommittedSnapshot is ReservedSnapshot for a committed (permanent) +// deletion only: an admitted reservation can still be aborted. +func (s *DeletionReservationStore) CommittedSnapshot(vol string) bool { + m := s.snap.Load() + if m == nil { + return false + } + r, ok := (*m)[vol] + return ok && r.State == ReservationCommitted +} + // Get returns vol's reservation. func (s *DeletionReservationStore) Get(vol string) (DeletionReservation, bool) { s.mu.Lock() diff --git a/seaweed-block/core/rpc/control/workspace.pb.go b/seaweed-block/core/rpc/control/workspace.pb.go index 92d006c675..a0c969e4b0 100644 --- a/seaweed-block/core/rpc/control/workspace.pb.go +++ b/seaweed-block/core/rpc/control/workspace.pb.go @@ -21,6 +21,58 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +type WorkspaceLeaseRefusal_Kind int32 + +const ( + WorkspaceLeaseRefusal_OTHER WorkspaceLeaseRefusal_Kind = 0 + WorkspaceLeaseRefusal_BARRIER WorkspaceLeaseRefusal_Kind = 1 + WorkspaceLeaseRefusal_MOVED WorkspaceLeaseRefusal_Kind = 2 + WorkspaceLeaseRefusal_DELETED WorkspaceLeaseRefusal_Kind = 3 +) + +// Enum value maps for WorkspaceLeaseRefusal_Kind. +var ( + WorkspaceLeaseRefusal_Kind_name = map[int32]string{ + 0: "OTHER", + 1: "BARRIER", + 2: "MOVED", + 3: "DELETED", + } + WorkspaceLeaseRefusal_Kind_value = map[string]int32{ + "OTHER": 0, + "BARRIER": 1, + "MOVED": 2, + "DELETED": 3, + } +) + +func (x WorkspaceLeaseRefusal_Kind) Enum() *WorkspaceLeaseRefusal_Kind { + p := new(WorkspaceLeaseRefusal_Kind) + *p = x + return p +} + +func (x WorkspaceLeaseRefusal_Kind) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (WorkspaceLeaseRefusal_Kind) Descriptor() protoreflect.EnumDescriptor { + return file_workspace_proto_enumTypes[0].Descriptor() +} + +func (WorkspaceLeaseRefusal_Kind) Type() protoreflect.EnumType { + return &file_workspace_proto_enumTypes[0] +} + +func (x WorkspaceLeaseRefusal_Kind) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use WorkspaceLeaseRefusal_Kind.Descriptor instead. +func (WorkspaceLeaseRefusal_Kind) EnumDescriptor() ([]byte, []int) { + return file_workspace_proto_rawDescGZIP(), []int{4, 0} +} + type WorkspaceIdentity struct { state protoimpl.MessageState `protogen:"open.v1"` VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` @@ -253,6 +305,62 @@ func (x *WorkspaceLeaseFact) GetRevoking() bool { return false } +// The typed reason of a RenewWorkspaceLease refusal, carried as a gRPC status +// detail (code and text unchanged). A refusal without it is OTHER. MOVED and +// DELETED are set only on a permanent, known fact; every doubtful case is +// OTHER. retry_after_ns (BARRIER only) is relative to the request's start. +type WorkspaceLeaseRefusal struct { + state protoimpl.MessageState `protogen:"open.v1"` + Kind WorkspaceLeaseRefusal_Kind `protobuf:"varint,1,opt,name=kind,proto3,enum=seaweedfs.block.control.WorkspaceLeaseRefusal_Kind" json:"kind,omitempty"` + RetryAfterNs int64 `protobuf:"varint,2,opt,name=retry_after_ns,json=retryAfterNs,proto3" json:"retry_after_ns,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkspaceLeaseRefusal) Reset() { + *x = WorkspaceLeaseRefusal{} + mi := &file_workspace_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkspaceLeaseRefusal) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkspaceLeaseRefusal) ProtoMessage() {} + +func (x *WorkspaceLeaseRefusal) ProtoReflect() protoreflect.Message { + mi := &file_workspace_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkspaceLeaseRefusal.ProtoReflect.Descriptor instead. +func (*WorkspaceLeaseRefusal) Descriptor() ([]byte, []int) { + return file_workspace_proto_rawDescGZIP(), []int{4} +} + +func (x *WorkspaceLeaseRefusal) GetKind() WorkspaceLeaseRefusal_Kind { + if x != nil { + return x.Kind + } + return WorkspaceLeaseRefusal_OTHER +} + +func (x *WorkspaceLeaseRefusal) GetRetryAfterNs() int64 { + if x != nil { + return x.RetryAfterNs + } + return 0 +} + type WorkspaceRevocationAck struct { state protoimpl.MessageState `protogen:"open.v1"` Identity *WorkspaceIdentity `protobuf:"bytes,1,opt,name=identity,proto3" json:"identity,omitempty"` @@ -263,7 +371,7 @@ type WorkspaceRevocationAck struct { func (x *WorkspaceRevocationAck) Reset() { *x = WorkspaceRevocationAck{} - mi := &file_workspace_proto_msgTypes[4] + mi := &file_workspace_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -275,7 +383,7 @@ func (x *WorkspaceRevocationAck) String() string { func (*WorkspaceRevocationAck) ProtoMessage() {} func (x *WorkspaceRevocationAck) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[4] + mi := &file_workspace_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -288,7 +396,7 @@ func (x *WorkspaceRevocationAck) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceRevocationAck.ProtoReflect.Descriptor instead. func (*WorkspaceRevocationAck) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{4} + return file_workspace_proto_rawDescGZIP(), []int{5} } func (x *WorkspaceRevocationAck) GetIdentity() *WorkspaceIdentity { @@ -323,7 +431,7 @@ type WorkspaceMove struct { func (x *WorkspaceMove) Reset() { *x = WorkspaceMove{} - mi := &file_workspace_proto_msgTypes[5] + mi := &file_workspace_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -335,7 +443,7 @@ func (x *WorkspaceMove) String() string { func (*WorkspaceMove) ProtoMessage() {} func (x *WorkspaceMove) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[5] + mi := &file_workspace_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -348,7 +456,7 @@ func (x *WorkspaceMove) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceMove.ProtoReflect.Descriptor instead. func (*WorkspaceMove) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{5} + return file_workspace_proto_rawDescGZIP(), []int{6} } func (x *WorkspaceMove) GetRequestId() string { @@ -446,7 +554,7 @@ type WorkspaceGrant struct { func (x *WorkspaceGrant) Reset() { *x = WorkspaceGrant{} - mi := &file_workspace_proto_msgTypes[6] + mi := &file_workspace_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -458,7 +566,7 @@ func (x *WorkspaceGrant) String() string { func (*WorkspaceGrant) ProtoMessage() {} func (x *WorkspaceGrant) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[6] + mi := &file_workspace_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -471,7 +579,7 @@ func (x *WorkspaceGrant) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceGrant.ProtoReflect.Descriptor instead. func (*WorkspaceGrant) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{6} + return file_workspace_proto_rawDescGZIP(), []int{7} } func (x *WorkspaceGrant) GetRequestId() string { @@ -594,7 +702,7 @@ type WorkspaceLostRange struct { func (x *WorkspaceLostRange) Reset() { *x = WorkspaceLostRange{} - mi := &file_workspace_proto_msgTypes[7] + mi := &file_workspace_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -606,7 +714,7 @@ func (x *WorkspaceLostRange) String() string { func (*WorkspaceLostRange) ProtoMessage() {} func (x *WorkspaceLostRange) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[7] + mi := &file_workspace_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -619,7 +727,7 @@ func (x *WorkspaceLostRange) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceLostRange.ProtoReflect.Descriptor instead. func (*WorkspaceLostRange) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{7} + return file_workspace_proto_rawDescGZIP(), []int{8} } func (x *WorkspaceLostRange) GetRequestId() string { @@ -702,7 +810,7 @@ type WorkspaceLostRangeQuery struct { func (x *WorkspaceLostRangeQuery) Reset() { *x = WorkspaceLostRangeQuery{} - mi := &file_workspace_proto_msgTypes[8] + mi := &file_workspace_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -714,7 +822,7 @@ func (x *WorkspaceLostRangeQuery) String() string { func (*WorkspaceLostRangeQuery) ProtoMessage() {} func (x *WorkspaceLostRangeQuery) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[8] + mi := &file_workspace_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -727,7 +835,7 @@ func (x *WorkspaceLostRangeQuery) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceLostRangeQuery.ProtoReflect.Descriptor instead. func (*WorkspaceLostRangeQuery) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{8} + return file_workspace_proto_rawDescGZIP(), []int{9} } func (x *WorkspaceLostRangeQuery) GetVolumeId() string { @@ -753,7 +861,7 @@ type WorkspaceLostRanges struct { func (x *WorkspaceLostRanges) Reset() { *x = WorkspaceLostRanges{} - mi := &file_workspace_proto_msgTypes[9] + mi := &file_workspace_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -765,7 +873,7 @@ func (x *WorkspaceLostRanges) String() string { func (*WorkspaceLostRanges) ProtoMessage() {} func (x *WorkspaceLostRanges) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[9] + mi := &file_workspace_proto_msgTypes[10] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -778,7 +886,7 @@ func (x *WorkspaceLostRanges) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceLostRanges.ProtoReflect.Descriptor instead. func (*WorkspaceLostRanges) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{9} + return file_workspace_proto_rawDescGZIP(), []int{10} } func (x *WorkspaceLostRanges) GetRanges() []*WorkspaceLostRange { @@ -810,7 +918,7 @@ type WorkspaceMovePreview struct { func (x *WorkspaceMovePreview) Reset() { *x = WorkspaceMovePreview{} - mi := &file_workspace_proto_msgTypes[10] + mi := &file_workspace_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -822,7 +930,7 @@ func (x *WorkspaceMovePreview) String() string { func (*WorkspaceMovePreview) ProtoMessage() {} func (x *WorkspaceMovePreview) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[10] + mi := &file_workspace_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -835,7 +943,7 @@ func (x *WorkspaceMovePreview) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceMovePreview.ProtoReflect.Descriptor instead. func (*WorkspaceMovePreview) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{10} + return file_workspace_proto_rawDescGZIP(), []int{11} } func (x *WorkspaceMovePreview) GetAdmitted() bool { @@ -934,7 +1042,7 @@ type WorkspaceStatus struct { func (x *WorkspaceStatus) Reset() { *x = WorkspaceStatus{} - mi := &file_workspace_proto_msgTypes[11] + mi := &file_workspace_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -946,7 +1054,7 @@ func (x *WorkspaceStatus) String() string { func (*WorkspaceStatus) ProtoMessage() {} func (x *WorkspaceStatus) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[11] + mi := &file_workspace_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -959,7 +1067,7 @@ func (x *WorkspaceStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceStatus.ProtoReflect.Descriptor instead. func (*WorkspaceStatus) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{11} + return file_workspace_proto_rawDescGZIP(), []int{12} } func (x *WorkspaceStatus) GetLease() *WorkspaceLeaseFact { @@ -1003,7 +1111,7 @@ type WorkspaceBinding struct { func (x *WorkspaceBinding) Reset() { *x = WorkspaceBinding{} - mi := &file_workspace_proto_msgTypes[12] + mi := &file_workspace_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1015,7 +1123,7 @@ func (x *WorkspaceBinding) String() string { func (*WorkspaceBinding) ProtoMessage() {} func (x *WorkspaceBinding) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[12] + mi := &file_workspace_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1028,7 +1136,7 @@ func (x *WorkspaceBinding) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceBinding.ProtoReflect.Descriptor instead. func (*WorkspaceBinding) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{12} + return file_workspace_proto_rawDescGZIP(), []int{13} } func (x *WorkspaceBinding) GetVolumeId() string { @@ -1077,7 +1185,7 @@ type WorkspacePlacement struct { func (x *WorkspacePlacement) Reset() { *x = WorkspacePlacement{} - mi := &file_workspace_proto_msgTypes[13] + mi := &file_workspace_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1089,7 +1197,7 @@ func (x *WorkspacePlacement) String() string { func (*WorkspacePlacement) ProtoMessage() {} func (x *WorkspacePlacement) ProtoReflect() protoreflect.Message { - mi := &file_workspace_proto_msgTypes[13] + mi := &file_workspace_proto_msgTypes[14] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1102,7 +1210,7 @@ func (x *WorkspacePlacement) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspacePlacement.ProtoReflect.Descriptor instead. func (*WorkspacePlacement) Descriptor() ([]byte, []int) { - return file_workspace_proto_rawDescGZIP(), []int{13} + return file_workspace_proto_rawDescGZIP(), []int{14} } func (x *WorkspacePlacement) GetVolumeId() string { @@ -1148,7 +1256,15 @@ const file_workspace_proto_rawDesc = "" + "\rexpires_at_ns\x18\x04 \x01(\x03R\vexpiresAtNs\x12 \n" + "\fvalid_for_ns\x18\x05 \x01(\x03R\n" + "validForNs\x12\x1a\n" + - "\brevoking\x18\x06 \x01(\bR\brevoking\"{\n" + + "\brevoking\x18\x06 \x01(\bR\brevoking\"\xbe\x01\n" + + "\x15WorkspaceLeaseRefusal\x12G\n" + + "\x04kind\x18\x01 \x01(\x0e23.seaweedfs.block.control.WorkspaceLeaseRefusal.KindR\x04kind\x12$\n" + + "\x0eretry_after_ns\x18\x02 \x01(\x03R\fretryAfterNs\"6\n" + + "\x04Kind\x12\t\n" + + "\x05OTHER\x10\x00\x12\v\n" + + "\aBARRIER\x10\x01\x12\t\n" + + "\x05MOVED\x10\x02\x12\v\n" + + "\aDELETED\x10\x03\"{\n" + "\x16WorkspaceRevocationAck\x12F\n" + "\bidentity\x18\x01 \x01(\v2*.seaweedfs.block.control.WorkspaceIdentityR\bidentity\x12\x19\n" + "\bhead_gen\x18\x02 \x01(\x04R\aheadGen\"\xf6\x02\n" + @@ -1261,54 +1377,58 @@ func file_workspace_proto_rawDescGZIP() []byte { return file_workspace_proto_rawDescData } -var file_workspace_proto_msgTypes = make([]protoimpl.MessageInfo, 14) +var file_workspace_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_workspace_proto_msgTypes = make([]protoimpl.MessageInfo, 15) var file_workspace_proto_goTypes = []any{ - (*WorkspaceIdentity)(nil), // 0: seaweedfs.block.control.WorkspaceIdentity - (*WorkspaceVolume)(nil), // 1: seaweedfs.block.control.WorkspaceVolume - (*WorkspaceEmpty)(nil), // 2: seaweedfs.block.control.WorkspaceEmpty - (*WorkspaceLeaseFact)(nil), // 3: seaweedfs.block.control.WorkspaceLeaseFact - (*WorkspaceRevocationAck)(nil), // 4: seaweedfs.block.control.WorkspaceRevocationAck - (*WorkspaceMove)(nil), // 5: seaweedfs.block.control.WorkspaceMove - (*WorkspaceGrant)(nil), // 6: seaweedfs.block.control.WorkspaceGrant - (*WorkspaceLostRange)(nil), // 7: seaweedfs.block.control.WorkspaceLostRange - (*WorkspaceLostRangeQuery)(nil), // 8: seaweedfs.block.control.WorkspaceLostRangeQuery - (*WorkspaceLostRanges)(nil), // 9: seaweedfs.block.control.WorkspaceLostRanges - (*WorkspaceMovePreview)(nil), // 10: seaweedfs.block.control.WorkspaceMovePreview - (*WorkspaceStatus)(nil), // 11: seaweedfs.block.control.WorkspaceStatus - (*WorkspaceBinding)(nil), // 12: seaweedfs.block.control.WorkspaceBinding - (*WorkspacePlacement)(nil), // 13: seaweedfs.block.control.WorkspacePlacement + (WorkspaceLeaseRefusal_Kind)(0), // 0: seaweedfs.block.control.WorkspaceLeaseRefusal.Kind + (*WorkspaceIdentity)(nil), // 1: seaweedfs.block.control.WorkspaceIdentity + (*WorkspaceVolume)(nil), // 2: seaweedfs.block.control.WorkspaceVolume + (*WorkspaceEmpty)(nil), // 3: seaweedfs.block.control.WorkspaceEmpty + (*WorkspaceLeaseFact)(nil), // 4: seaweedfs.block.control.WorkspaceLeaseFact + (*WorkspaceLeaseRefusal)(nil), // 5: seaweedfs.block.control.WorkspaceLeaseRefusal + (*WorkspaceRevocationAck)(nil), // 6: seaweedfs.block.control.WorkspaceRevocationAck + (*WorkspaceMove)(nil), // 7: seaweedfs.block.control.WorkspaceMove + (*WorkspaceGrant)(nil), // 8: seaweedfs.block.control.WorkspaceGrant + (*WorkspaceLostRange)(nil), // 9: seaweedfs.block.control.WorkspaceLostRange + (*WorkspaceLostRangeQuery)(nil), // 10: seaweedfs.block.control.WorkspaceLostRangeQuery + (*WorkspaceLostRanges)(nil), // 11: seaweedfs.block.control.WorkspaceLostRanges + (*WorkspaceMovePreview)(nil), // 12: seaweedfs.block.control.WorkspaceMovePreview + (*WorkspaceStatus)(nil), // 13: seaweedfs.block.control.WorkspaceStatus + (*WorkspaceBinding)(nil), // 14: seaweedfs.block.control.WorkspaceBinding + (*WorkspacePlacement)(nil), // 15: seaweedfs.block.control.WorkspacePlacement } var file_workspace_proto_depIdxs = []int32{ - 0, // 0: seaweedfs.block.control.WorkspaceRevocationAck.identity:type_name -> seaweedfs.block.control.WorkspaceIdentity - 7, // 1: seaweedfs.block.control.WorkspaceGrant.lost_range:type_name -> seaweedfs.block.control.WorkspaceLostRange - 7, // 2: seaweedfs.block.control.WorkspaceLostRanges.ranges:type_name -> seaweedfs.block.control.WorkspaceLostRange - 3, // 3: seaweedfs.block.control.WorkspaceStatus.lease:type_name -> seaweedfs.block.control.WorkspaceLeaseFact - 4, // 4: seaweedfs.block.control.WorkspaceStatus.revocation_ack:type_name -> seaweedfs.block.control.WorkspaceRevocationAck - 6, // 5: seaweedfs.block.control.WorkspaceStatus.moves:type_name -> seaweedfs.block.control.WorkspaceGrant - 12, // 6: seaweedfs.block.control.WorkspaceStatus.bindings:type_name -> seaweedfs.block.control.WorkspaceBinding - 12, // 7: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:input_type -> seaweedfs.block.control.WorkspaceBinding - 13, // 8: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:input_type -> seaweedfs.block.control.WorkspacePlacement - 0, // 9: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:input_type -> seaweedfs.block.control.WorkspaceIdentity - 0, // 10: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:input_type -> seaweedfs.block.control.WorkspaceIdentity - 4, // 11: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:input_type -> seaweedfs.block.control.WorkspaceRevocationAck - 5, // 12: seaweedfs.block.control.WorkspaceService.MoveWorkspace:input_type -> seaweedfs.block.control.WorkspaceMove - 1, // 13: seaweedfs.block.control.WorkspaceService.QueryWorkspace:input_type -> seaweedfs.block.control.WorkspaceVolume - 8, // 14: seaweedfs.block.control.WorkspaceService.QueryWorkspaceLostRange:input_type -> seaweedfs.block.control.WorkspaceLostRangeQuery - 5, // 15: seaweedfs.block.control.WorkspaceService.PreviewWorkspaceMove:input_type -> seaweedfs.block.control.WorkspaceMove - 12, // 16: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:output_type -> seaweedfs.block.control.WorkspaceBinding - 2, // 17: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:output_type -> seaweedfs.block.control.WorkspaceEmpty - 3, // 18: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:output_type -> seaweedfs.block.control.WorkspaceLeaseFact - 3, // 19: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:output_type -> seaweedfs.block.control.WorkspaceLeaseFact - 2, // 20: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:output_type -> seaweedfs.block.control.WorkspaceEmpty - 6, // 21: seaweedfs.block.control.WorkspaceService.MoveWorkspace:output_type -> seaweedfs.block.control.WorkspaceGrant - 11, // 22: seaweedfs.block.control.WorkspaceService.QueryWorkspace:output_type -> seaweedfs.block.control.WorkspaceStatus - 9, // 23: seaweedfs.block.control.WorkspaceService.QueryWorkspaceLostRange:output_type -> seaweedfs.block.control.WorkspaceLostRanges - 10, // 24: seaweedfs.block.control.WorkspaceService.PreviewWorkspaceMove:output_type -> seaweedfs.block.control.WorkspaceMovePreview - 16, // [16:25] is the sub-list for method output_type - 7, // [7:16] is the sub-list for method input_type - 7, // [7:7] is the sub-list for extension type_name - 7, // [7:7] is the sub-list for extension extendee - 0, // [0:7] is the sub-list for field type_name + 0, // 0: seaweedfs.block.control.WorkspaceLeaseRefusal.kind:type_name -> seaweedfs.block.control.WorkspaceLeaseRefusal.Kind + 1, // 1: seaweedfs.block.control.WorkspaceRevocationAck.identity:type_name -> seaweedfs.block.control.WorkspaceIdentity + 9, // 2: seaweedfs.block.control.WorkspaceGrant.lost_range:type_name -> seaweedfs.block.control.WorkspaceLostRange + 9, // 3: seaweedfs.block.control.WorkspaceLostRanges.ranges:type_name -> seaweedfs.block.control.WorkspaceLostRange + 4, // 4: seaweedfs.block.control.WorkspaceStatus.lease:type_name -> seaweedfs.block.control.WorkspaceLeaseFact + 6, // 5: seaweedfs.block.control.WorkspaceStatus.revocation_ack:type_name -> seaweedfs.block.control.WorkspaceRevocationAck + 8, // 6: seaweedfs.block.control.WorkspaceStatus.moves:type_name -> seaweedfs.block.control.WorkspaceGrant + 14, // 7: seaweedfs.block.control.WorkspaceStatus.bindings:type_name -> seaweedfs.block.control.WorkspaceBinding + 14, // 8: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:input_type -> seaweedfs.block.control.WorkspaceBinding + 15, // 9: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:input_type -> seaweedfs.block.control.WorkspacePlacement + 1, // 10: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:input_type -> seaweedfs.block.control.WorkspaceIdentity + 1, // 11: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:input_type -> seaweedfs.block.control.WorkspaceIdentity + 6, // 12: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:input_type -> seaweedfs.block.control.WorkspaceRevocationAck + 7, // 13: seaweedfs.block.control.WorkspaceService.MoveWorkspace:input_type -> seaweedfs.block.control.WorkspaceMove + 2, // 14: seaweedfs.block.control.WorkspaceService.QueryWorkspace:input_type -> seaweedfs.block.control.WorkspaceVolume + 10, // 15: seaweedfs.block.control.WorkspaceService.QueryWorkspaceLostRange:input_type -> seaweedfs.block.control.WorkspaceLostRangeQuery + 7, // 16: seaweedfs.block.control.WorkspaceService.PreviewWorkspaceMove:input_type -> seaweedfs.block.control.WorkspaceMove + 14, // 17: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:output_type -> seaweedfs.block.control.WorkspaceBinding + 3, // 18: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:output_type -> seaweedfs.block.control.WorkspaceEmpty + 4, // 19: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:output_type -> seaweedfs.block.control.WorkspaceLeaseFact + 4, // 20: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:output_type -> seaweedfs.block.control.WorkspaceLeaseFact + 3, // 21: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:output_type -> seaweedfs.block.control.WorkspaceEmpty + 8, // 22: seaweedfs.block.control.WorkspaceService.MoveWorkspace:output_type -> seaweedfs.block.control.WorkspaceGrant + 13, // 23: seaweedfs.block.control.WorkspaceService.QueryWorkspace:output_type -> seaweedfs.block.control.WorkspaceStatus + 11, // 24: seaweedfs.block.control.WorkspaceService.QueryWorkspaceLostRange:output_type -> seaweedfs.block.control.WorkspaceLostRanges + 12, // 25: seaweedfs.block.control.WorkspaceService.PreviewWorkspaceMove:output_type -> seaweedfs.block.control.WorkspaceMovePreview + 17, // [17:26] is the sub-list for method output_type + 8, // [8:17] is the sub-list for method input_type + 8, // [8:8] is the sub-list for extension type_name + 8, // [8:8] is the sub-list for extension extendee + 0, // [0:8] is the sub-list for field type_name } func init() { file_workspace_proto_init() } @@ -1321,13 +1441,14 @@ func file_workspace_proto_init() { File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_workspace_proto_rawDesc), len(file_workspace_proto_rawDesc)), - NumEnums: 0, - NumMessages: 14, + NumEnums: 1, + NumMessages: 15, NumExtensions: 0, NumServices: 1, }, GoTypes: file_workspace_proto_goTypes, DependencyIndexes: file_workspace_proto_depIdxs, + EnumInfos: file_workspace_proto_enumTypes, MessageInfos: file_workspace_proto_msgTypes, }.Build() File_workspace_proto = out.File diff --git a/seaweed-block/core/rpc/proto/workspace.proto b/seaweed-block/core/rpc/proto/workspace.proto index eadcdb5b66..74f0ca9ce7 100644 --- a/seaweed-block/core/rpc/proto/workspace.proto +++ b/seaweed-block/core/rpc/proto/workspace.proto @@ -28,6 +28,15 @@ message WorkspaceLeaseFact { string volume_id = 1; string replica_id = 2; uint64 epoch = 3; int64 expires_at_ns = 4; int64 valid_for_ns = 5; bool revoking = 6; } +// The typed reason of a RenewWorkspaceLease refusal, carried as a gRPC status +// detail (code and text unchanged). A refusal without it is OTHER. MOVED and +// DELETED are set only on a permanent, known fact; every doubtful case is +// OTHER. retry_after_ns (BARRIER only) is relative to the request's start. +message WorkspaceLeaseRefusal { + enum Kind { OTHER = 0; BARRIER = 1; MOVED = 2; DELETED = 3; } + Kind kind = 1; + int64 retry_after_ns = 2; +} message WorkspaceRevocationAck { WorkspaceIdentity identity = 1; uint64 head_gen = 2; } message WorkspaceMove { string request_id = 1; string volume_id = 2; From c8e9f4dde21eddc532bd0b26e0f22246915f0e9c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 21:04:43 -0800 Subject: [PATCH 04/34] test: MOVED as a newer epoch on another host Co-Authored-By: Claude Opus 5.5 --- .../workspace_lease_refusal_kind_test.go | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go b/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go index d3b71ead19..b3e10e63a9 100644 --- a/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go +++ b/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go @@ -63,10 +63,11 @@ func TestLeaseRefusalKinds(t *testing.T) { t.Fatal(err) } line := waitAuthorityLine(t, h.Publisher(), "v") - id := func(replica string, epoch uint64) *control.WorkspaceIdentity { - return &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: replica, Epoch: epoch, ServerId: "node-a"} + nodeB := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-b", DataAddr: "127.0.0.1:20000", CtrlAddr: "127.0.0.1:20001"} + id := func(server string, epoch uint64) *control.WorkspaceIdentity { + return &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: epoch, ServerId: server} } - e1 := id("r1", line.Epoch) + e1 := id("node-a", line.Epoch) if _, err := ws.RenewWorkspaceLease(ctx, e1); err != nil { t.Fatal("first grant:", err) } @@ -89,9 +90,9 @@ func TestLeaseRefusalKinds(t *testing.T) { t.Fatal("re-grant after the barrier:", err) } - // cleanMove revokes and ACKs the current holder, then moves the line on - // the same host to replica. - cleanMove := func(req string, from *control.WorkspaceIdentity, replica string) uint64 { + // cleanMove revokes and ACKs the current holder, then moves the line to + // the binding's host. + cleanMove := func(req string, from *control.WorkspaceIdentity, to *control.WorkspaceBinding) uint64 { t.Helper() if _, err := ws.RevokeWorkspace(ctx, from); err != nil { t.Fatal(err) @@ -101,11 +102,11 @@ func TestLeaseRefusalKinds(t *testing.T) { if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: from, HeadGen: uint64(headGen.Load())}); err != nil { t.Fatal(err) } - if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + if _, err := ws.RegisterWorkspaceBinding(ctx, to); err != nil { t.Fatal(err) } - g, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: req, VolumeId: "v", ExpectedReplicaId: from.GetReplicaId(), ExpectedEpoch: from.GetEpoch(), - TargetReplicaId: replica, TargetServerId: "node-a", TargetDataAddr: b.DataAddr, TargetCtrlAddr: b.CtrlAddr, Kind: "clean"}) + g, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: req, VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: from.GetEpoch(), + TargetReplicaId: "r1", TargetServerId: to.GetServerId(), TargetDataAddr: to.GetDataAddr(), TargetCtrlAddr: to.GetCtrlAddr(), Kind: "clean"}) if err != nil { t.Fatal(err) } @@ -113,7 +114,7 @@ func TestLeaseRefusalKinds(t *testing.T) { } // OTHER: the same owner at a newer epoch (a clean move back to this host). - e2 := id("r1", cleanMove("same-replica", e1, "r1")) + e2 := id("node-a", cleanMove("same-host", e1, b)) text, r = refusalOf(t, "same owner, newer epoch", func() error { _, err := ws.RenewWorkspaceLease(ctx, e1); return err }()) if r != nil || text != "workspace lease: server identity does not match the current holder" { t.Fatalf("same owner at a newer epoch: %q detail %v; want the unchanged text, no detail", text, r) @@ -122,11 +123,12 @@ func TestLeaseRefusalKinds(t *testing.T) { t.Fatal("grant at the newer epoch:", err) } - // MOVED: the line names another replica. - e3 := id("r2", cleanMove("other-replica", e2, "r2")) - text, r = refusalOf(t, "line names another replica", func() error { _, err := ws.RenewWorkspaceLease(ctx, e2); return err }()) + // MOVED: a newer epoch owned by another known server. (A line naming + // another replica is MOVED too; a v1 move keeps the replica id.) + e3 := id("node-b", cleanMove("other-host", e2, nodeB)) + text, r = refusalOf(t, "moved to another host", func() error { _, err := ws.RenewWorkspaceLease(ctx, e2); return err }()) if r == nil || r.GetKind() != control.WorkspaceLeaseRefusal_MOVED || text != "workspace lease: server identity does not match the current holder" { - t.Fatalf("line names another replica: %q detail %v; want MOVED with the unchanged text", text, r) + t.Fatalf("moved to another host: %q detail %v; want MOVED with the unchanged text", text, r) } // An admitted deletion is OTHER; a committed one is DELETED. From 15f980f63862419163a1d8827b91a515742e6b49 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 21:22:43 -0800 Subject: [PATCH 05/34] feat: a workspace primary waits for an unreachable master The startup authority wait no longer runs out while blockmaster gives no reply or refuses the node's credentials. Its 30 s bound counts from the first answered contact, or from the master's barrier time when later; a typed MOVED or DELETED renewal refusal ends it at once with exit 78. Before its first grant the lease guard sleeps until the barrier time instead of polling every second. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/main.go | 9 + seaweed-block/cmd/blockvolume/process_exit.go | 7 + .../core/frontend/durable/provider.go | 7 + .../core/frontend/durable/provider_chunk.go | 32 ++- seaweed-block/core/host/volume/host.go | 11 + seaweed-block/core/host/volume/master_wait.go | 218 ++++++++++++++++++ .../core/host/volume/workspace_lease.go | 25 +- .../core/host/volume/workspace_runtime.go | 1 + 8 files changed, 304 insertions(+), 6 deletions(-) create mode 100644 seaweed-block/core/host/volume/master_wait.go diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 939191bdcc..6ae1f22433 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -695,6 +695,15 @@ func runVolume(f flags, exits *processExit) int { cfg.ChunkMaintenanceInterval = f.chunk.maintenanceInterval cfg.ChunkMaintenanceTimeout = defaultChunkMaintenanceTimeout cfg.ChunkMaintenance = chunk.maintenance + if f.workspaceLease { + // The startup wait does not run out while the master gives no + // reply; it ends 30 s after answered contact (or the master's + // barrier), or at once on a moved/deleted refusal. + cfg.ChunkMasterWait = func() (time.Time, bool) { + deadline, final := h.MasterWaitState() + return deadline, final != "" + } + } if chunk.catalog != nil && f.chunk.snapshotSchedule.period > 0 { cfg.ChunkSnapshotPeriod = f.chunk.snapshotSchedule.period cfg.ChunkScheduledSnapshot = volume.ScheduledSnapshot(chunk.catalog, f.chunk.snapshotSchedule.keep) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 9fdcb53767..3e81e14fe5 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -249,6 +249,13 @@ func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStar // INV-WS-STARTUP-RETRY-001: one exit decision consumes both proof // sources; the provider rechecks the claim generation below. out := workspaceRetryOutcome("assignment_timeout", h, p.ChunkStartupSuperseded(f.volumeID, gen)) + if out.code == exitWorkspaceRetry && h != nil { + // A typed MOVED or DELETED renewal refusal is permanent: 78 at once, + // never a restart loop to the unit's start limit. + if _, final := h.MasterWaitState(); final != "" { + out = workspaceExit{code: exitWorkspaceSuperseded, reason: final} + } + } if c, ok := p.(interface{ ChunkStartupCure(string, uint64) string }); ok { out.detail = c.ChunkStartupCure(f.volumeID, gen) } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index a6af566c84..715e0d292d 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -116,6 +116,13 @@ type ProviderConfig struct { // the host can apply its assignment. Zero defaults to 30s. ChunkAssignmentTimeout time.Duration + // ChunkMasterWait, when set, replaces ChunkAssignmentTimeout's fixed + // deadline (a workspace primary): it returns the wait's bound (zero: no + // bound, the master gives no reply) and whether a permanent refusal + // (moved or deleted) ends the wait now. It is read on the wait's poll + // and must not block. + ChunkMasterWait func() (deadline time.Time, final bool) + // WALRetentionLSNs is the operator-tunable retention window past // the substrate's checkpoint LSN (G6 §1.A α). Zero = pre-G6 // strict checkpoint-driven recycle. Non-zero relaxes the recycle diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index f4a2680e6f..072a097a08 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -159,17 +159,35 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen limit = 30 * time.Second } start := time.Now() - log.Printf("durable: chunk layer for volume=%s waits for master authority (up to %s): projection lacks %s", - volumeID, limit, chunkAuthorityGap(p.view.Projection(), volumeID)) + bound := fmt.Sprintf("up to %s", limit) + if p.cfg.ChunkMasterWait != nil { + bound = fmt.Sprintf("%s of answered contact with the master", limit) + } + log.Printf("durable: chunk layer for volume=%s waits for master authority (%s): projection lacks %s", + volumeID, bound, chunkAuthorityGap(p.view.Projection(), volumeID)) ended := "superseded by a later recovery" defer func() { log.Printf("durable: chunk authority wait for volume=%s ended after %s: %s", volumeID, time.Since(start), ended) }() retained := false // this generation already chose sealed replay or diagnostics - waitCtx, endWait := context.WithTimeout(p.closeCtx, limit) + // expired: the wait gave up (deadline, or a permanent refusal). Without + // ChunkMasterWait the deadline is the fixed limit from now; with it the + // host's bound, which does not run while the master gives no reply. + expired := false + waitCtx, endWait := context.WithCancel(p.closeCtx) + if p.cfg.ChunkMasterWait == nil { + waitCtx, endWait = context.WithTimeout(p.closeCtx, limit) + } defer endWait() + gaveUp := func() bool { + if p.cfg.ChunkMasterWait == nil { + return false + } + deadline, final := p.cfg.ChunkMasterWait() + return final || (!deadline.IsZero() && !time.Now().Before(deadline)) + } defer func() { - if retained || !errors.Is(waitCtx.Err(), context.DeadlineExceeded) { + if retained || !(expired || errors.Is(waitCtx.Err(), context.DeadlineExceeded)) { return } // The old wait must not overwrite a newer recovery's readiness. @@ -177,7 +195,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen defer h.attachMu.Unlock() if p.current(h, gen) && h.chunk == nil { ended = fmt.Sprintf("assignment unavailable, not serving (projection lacks %s)", chunkAuthorityGap(p.view.Projection(), volumeID)) - h.backend.SetOperational(false, "chunk assignment unavailable: "+waitCtx.Err().Error()) + h.backend.SetOperational(false, "chunk assignment unavailable: master wait ended") p.endChunkStartup(h, gen, nil) } }() @@ -204,6 +222,10 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen if !p.current(h, gen) { return // a later recovery (successful or failed) owns the volume } + if gaveUp() { + expired, ended = true, "master wait ended (bound reached or permanent refusal)" + return + } proj := p.view.Projection() if !chunkAuthority(proj, volumeID) { continue diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 0e1797403b..eb8cdc3361 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -113,6 +113,7 @@ type replicaSetUpdater interface { type Host struct { // incarnation is new on every process start and reported in every // heartbeat, so the master can tell a restart from a long silence. + mw *masterWait // observed blockmaster call results (workspace startup wait) incarnation string // wd is the recovery watchdog (#128 rule 6). wd *recoveryWatchdog @@ -301,6 +302,7 @@ func New(cfg Config) (*Host, error) { asnCli: control.NewAssignmentServiceClient(conn), } h.incarnation = newIncarnation() + h.mw = newMasterWait(nil, lg.Printf) h.wd = newRecoveryWatchdog(cfg.RecoverTimeout) h.log.Printf("blockvolume: volume %s recovery watchdog: a primary assignment must become promotion-ready within %s", cfg.VolumeID, h.wd.timeout) if cfg.ReplicationVolume != nil { @@ -622,6 +624,9 @@ func (h *Host) runHeartbeat(ctx context.Context) { rpcCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, err := h.obsCli.ReportHeartbeat(rpcCtx, h.buildReport()) + if ctx.Err() == nil { + h.mw.call(err) + } if err != nil { h.log.Printf("blockvolume: heartbeat: %v", err) } @@ -765,10 +770,16 @@ func (h *Host) streamOnce(ctx context.Context) error { ServerId: h.cfg.ServerID, // INV-AUTH-HOLDER-IDENTITY-001: the master checks it against the stream's host }) if err != nil { + if ctx.Err() == nil { + h.mw.call(err) + } return err } for { fact, err := stream.Recv() + if ctx.Err() == nil && err != io.EOF { + h.mw.call(err) // a delivered fact or a handler's status is contact + } if err == io.EOF { return nil } diff --git a/seaweed-block/core/host/volume/master_wait.go b/seaweed-block/core/host/volume/master_wait.go new file mode 100644 index 0000000000..61f6fc9999 --- /dev/null +++ b/seaweed-block/core/host/volume/master_wait.go @@ -0,0 +1,218 @@ +package volume + +import ( + "context" + "errors" + "log" + "sync" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// MasterWaitLimit is how long a workspace chunk primary waits for its grant +// while the master answers: counted from the start of the current contact +// streak, or from the master's barrier time when that is later. +const MasterWaitLimit = 30 * time.Second + +// masterWaitLogEvery repeats the wait's log line while it lasts. +const masterWaitLogEvery = 10 * time.Minute + +// MasterWait is why a workspace primary is not yet granted, for /status. +// Reason is unreachable (no reply), credentials (the master refused the +// node's credentials), barrier (Until is the master's barrier time), +// no_assignment, refused, moved or deleted. Until is zero while the wait +// has no bound. +type MasterWait struct { + Reason string + Since time.Time + Until time.Time +} + +// masterWait observes the results of the process's calls to blockmaster +// (heartbeat, assignment stream, lease renewal). It holds observations +// only: no decision branches on it except the startup wait's end. +type masterWait struct { + mu sync.Mutex + now func() time.Time + contact time.Time // start of the current contact streak; zero while none + down time.Time // first failure without a reply since the last contact + creds time.Time // first credentials refusal since the last accepted call + barrier time.Time // T: request start + retry_after of the latest BARRIER refusal + final string // "moved" or "deleted": a permanent refusal + logged string // the reason last logged + loggedAt time.Time + logf func(string, ...any) +} + +func newMasterWait(now func() time.Time, logf func(string, ...any)) *masterWait { + if now == nil { + now = time.Now + } + if logf == nil { + logf = log.Printf + } + return &masterWait{now: now, logf: logf} +} + +// masterCallClass sorts a call result: a reply produced by blockmaster's +// handler (any status but the transport codes) is contact; Unavailable, +// DeadlineExceeded and Canceled are no reply; Unauthenticated and +// PermissionDenied are a credentials refusal. +func masterCallClass(err error) (contact, credentials bool) { + if err == nil { + return true, false + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return false, false + } + switch status.Code(err) { + case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled: + return false, false + case codes.Unauthenticated, codes.PermissionDenied: + return false, true + } + return true, false +} + +// call records one call's result. +func (w *masterWait) call(err error) { + contact, credentials := masterCallClass(err) + w.mu.Lock() + now := w.now() + switch { + case contact: + if w.contact.IsZero() { + w.contact = now + } + w.down, w.creds = time.Time{}, time.Time{} + case credentials: + w.contact, w.down = time.Time{}, time.Time{} + if w.creds.IsZero() { + w.creds = now + } + default: + w.contact, w.creds = time.Time{}, time.Time{} + if w.down.IsZero() { + w.down = now + } + } + w.mu.Unlock() +} + +// renewal records a lease renewal started at start: the call itself, and +// the typed kind of a refusal (status detail only, never its text). +func (w *masterWait) renewal(start time.Time, err error) { + w.call(err) + r := leaseRefusalDetail(err) + if r == nil { + return + } + w.mu.Lock() + defer w.mu.Unlock() + switch r.GetKind() { + case control.WorkspaceLeaseRefusal_BARRIER: + if t := start.Add(time.Duration(r.GetRetryAfterNs())); t.After(w.barrier) { + w.barrier = t + } + case control.WorkspaceLeaseRefusal_MOVED: + w.final = "moved" + case control.WorkspaceLeaseRefusal_DELETED: + w.final = "deleted" + } +} + +// leaseRefusalDetail returns the typed refusal of a renewal error, or nil +// (OTHER) when it carries none. +func leaseRefusalDetail(err error) *control.WorkspaceLeaseRefusal { + st, ok := status.FromError(err) + if err == nil || !ok { + return nil + } + for _, d := range st.Details() { + if r, ok := d.(*control.WorkspaceLeaseRefusal); ok { + return r + } + } + return nil +} + +// deadlineLocked is max(contact streak start, barrier T) + MasterWaitLimit, +// or zero while there is no contact (no bound). Caller holds mu. +func (w *masterWait) deadlineLocked() time.Time { + if w.contact.IsZero() { + return time.Time{} + } + from := w.contact + if w.barrier.After(from) { + from = w.barrier + } + return from.Add(MasterWaitLimit) +} + +// state returns the startup wait's bound (zero: none) and a permanent +// refusal ("" when none). +func (w *masterWait) state() (time.Time, string) { + w.mu.Lock() + defer w.mu.Unlock() + return w.deadlineLocked(), w.final +} + +// snapshot names the reason for a process that holds no grant, and logs it +// on a change and every masterWaitLogEvery while it lasts. +func (w *masterWait) snapshot(assigned bool) MasterWait { + w.mu.Lock() + now := w.now() + var out MasterWait + switch { + case w.final != "": + out = MasterWait{Reason: w.final, Since: now} + case !w.creds.IsZero(): + out = MasterWait{Reason: "credentials", Since: w.creds} + case w.contact.IsZero(): + out = MasterWait{Reason: "unreachable", Since: w.down} + if w.down.IsZero() { + out.Since = now + } + case w.barrier.After(now): + out = MasterWait{Reason: "barrier", Since: w.contact, Until: w.barrier} + case !assigned: + out = MasterWait{Reason: "no_assignment", Since: w.contact, Until: w.deadlineLocked()} + default: + out = MasterWait{Reason: "refused", Since: w.contact, Until: w.deadlineLocked()} + } + logIt := out.Reason != w.logged || now.Sub(w.loggedAt) >= masterWaitLogEvery + if logIt { + w.logged, w.loggedAt = out.Reason, now + } + logf := w.logf + w.mu.Unlock() + if logIt { + if out.Until.IsZero() { + logf("blockvolume: waiting for the master: %s since %s (no bound)", out.Reason, out.Since.UTC().Format(time.RFC3339)) + } else { + logf("blockvolume: waiting for the master: %s since %s until %s", out.Reason, out.Since.UTC().Format(time.RFC3339), out.Until.UTC().Format(time.RFC3339)) + } + } + return out +} + +// MasterWaitState is the workspace startup wait's bound (zero while the +// master gives no reply or refuses the node's credentials: no bound) and a +// permanent refusal of the lease ("moved" or "deleted"; "" when none). +func (h *Host) MasterWaitState() (time.Time, string) { return h.mw.state() } + +// MasterWaitStatus is why a workspace primary is not serving under a +// grant, or nil when it holds one (or is not a workspace primary). +func (h *Host) MasterWaitStatus() *MasterWait { + if !h.cfg.WorkspaceLease { + return nil + } + if g := h.view.workspaceGuard.Load(); g != nil && g.Held() { + return nil + } + w := h.mw.snapshot(h.realAdpt.Projection().Epoch > 0) + return &w +} diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index f3ae20dbbc..d751b6ff94 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -52,6 +52,13 @@ type WorkspaceLeaseGuard struct { // after schedules Run's sleep between renewals (time.After; tests // replace it before Run starts to observe the delays chosen). after func(time.Duration) <-chan time.Time + // barrier is the master's barrier time T from the latest BARRIER refusal + // (request start + retry_after, under mu): before the first grant Run + // sleeps until T instead of polling every second. + barrier time.Time + // observe, when set, receives every renewal's start and result (the + // host's master wait). Set before Run; never called with mu held. + observe func(time.Time, error) } // stopPendingPoll caps Run's sleep after a completed renewal while a stop is @@ -96,12 +103,20 @@ func (g *WorkspaceLeaseGuard) ClearStopPending() { // while a stop is pending. func (g *WorkspaceLeaseGuard) renewDelay() time.Duration { g.mu.Lock() - delay := g.until.Sub(g.now()) / 3 + now := g.now() + delay := g.until.Sub(now) / 3 if g.until.IsZero() { delay = time.Second } + barrier := g.until.IsZero() && g.barrier.After(now) + if barrier { + delay = g.barrier.Sub(now) // the master refuses every call before T + } pending := g.stopPending g.mu.Unlock() + if barrier && !pending { + return delay + } if delay < 50*time.Millisecond { delay = 50 * time.Millisecond } @@ -208,6 +223,14 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { } defer cancel() reply, err := g.client.RenewWorkspaceLease(rpcCtx, &g.id) + if g.observe != nil && ctx.Err() == nil { + g.observe(start, err) + } + if r := leaseRefusalDetail(err); r != nil && r.GetKind() == control.WorkspaceLeaseRefusal_BARRIER { + g.mu.Lock() + g.barrier = start.Add(time.Duration(r.GetRetryAfterNs())) + g.mu.Unlock() + } if err != nil { end := g.now() elapsed := end.Sub(start).Round(time.Millisecond) diff --git a/seaweed-block/core/host/volume/workspace_runtime.go b/seaweed-block/core/host/volume/workspace_runtime.go index f0a06bd88a..9a27b9aac2 100644 --- a/seaweed-block/core/host/volume/workspace_runtime.go +++ b/seaweed-block/core/host/volume/workspace_runtime.go @@ -37,6 +37,7 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context, if err != nil { return err } + guard.observe = h.mw.renewal if beforeInstall != nil { beforeInstall() } From 03b165f0586679ba14b39da74de41773f744b96a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 21:49:04 -0800 Subject: [PATCH 06/34] fix: keep the fixed-timeout evidence text; no leaked wait context Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/frontend/durable/provider_chunk.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 072a097a08..86c79621e1 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -174,9 +174,12 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen // ChunkMasterWait the deadline is the fixed limit from now; with it the // host's bound, which does not run while the master gives no reply. expired := false - waitCtx, endWait := context.WithCancel(p.closeCtx) + var waitCtx context.Context + var endWait context.CancelFunc if p.cfg.ChunkMasterWait == nil { waitCtx, endWait = context.WithTimeout(p.closeCtx, limit) + } else { + waitCtx, endWait = context.WithCancel(p.closeCtx) } defer endWait() gaveUp := func() bool { @@ -195,7 +198,11 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen defer h.attachMu.Unlock() if p.current(h, gen) && h.chunk == nil { ended = fmt.Sprintf("assignment unavailable, not serving (projection lacks %s)", chunkAuthorityGap(p.view.Projection(), volumeID)) - h.backend.SetOperational(false, "chunk assignment unavailable: master wait ended") + why := "master wait ended" + if !expired { + why = waitCtx.Err().Error() // the fixed limit: context deadline exceeded + } + h.backend.SetOperational(false, "chunk assignment unavailable: "+why) p.endChunkStartup(h, gen, nil) } }() From d16a30eca49d79f1d03b37bdd7ec3be186f3ee5f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 21:50:17 -0800 Subject: [PATCH 07/34] test: startup wait follows the master contact, the barrier and final refusals Co-Authored-By: Claude Opus 5.5 --- .../durable/provider_master_wait_test.go | 69 ++++++++ .../core/host/volume/master_wait_test.go | 163 ++++++++++++++++++ 2 files changed, 232 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/provider_master_wait_test.go create mode 100644 seaweed-block/core/host/volume/master_wait_test.go diff --git a/seaweed-block/core/frontend/durable/provider_master_wait_test.go b/seaweed-block/core/frontend/durable/provider_master_wait_test.go new file mode 100644 index 0000000000..0b09d040a1 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_master_wait_test.go @@ -0,0 +1,69 @@ +package durable_test + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// With ChunkMasterWait set (a workspace primary), the startup authority wait +// does not run out on the fixed timeout while the host reports no bound (the +// master gives no reply); it ends once the host's bound passes, or at once +// on a permanent refusal, with the same latched outcome as a timeout. +func TestChunkAuthorityWaitFollowsTheMasterWait(t *testing.T) { + for _, tc := range []struct { + name string + final bool + }{{"bound", false}, {"final", true}} { + t.Run(tc.name, func(t *testing.T) { + logs := &lockedLog{} + captureWriteLogs(t, logs) + var bound atomic.Int64 // unix ns; 0 = no bound + var final atomic.Bool + v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, + BlockSize: 4096, ChunkBlocks: 4, ChunkAssignmentTimeout: time.Millisecond, + ChunkMasterWait: func() (time.Time, bool) { + if b := bound.Load(); b != 0 { + return time.Unix(0, b), final.Load() + } + return time.Time{}, final.Load() + }, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { + t.Error("remote reached without authority") + return storage.NewMemChunkRemote(), nil + }, + }, v) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + v.active.Store(true) + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + outcomes := any(p).(interface{ ChunkStartupOutcome(string) (uint64, bool) }) + time.Sleep(500 * time.Millisecond) // 500x the fixed timeout + if _, failed := outcomes.ChunkStartupOutcome("v1"); failed { + t.Fatal("the wait ran out on the fixed timeout while the master gave no reply") + } + if tc.final { + final.Store(true) + } else { + bound.Store(time.Now().Add(200 * time.Millisecond).UnixNano()) + } + waitLog(t, logs, "assignment unavailable, not serving") + if gen, failed := outcomes.ChunkStartupOutcome("v1"); !failed || gen != 1 { + t.Fatalf("outcome generation %d failed %v; want the current recovery's", gen, failed) + } + }) + } +} diff --git a/seaweed-block/core/host/volume/master_wait_test.go b/seaweed-block/core/host/volume/master_wait_test.go new file mode 100644 index 0000000000..bb33d18d77 --- /dev/null +++ b/seaweed-block/core/host/volume/master_wait_test.go @@ -0,0 +1,163 @@ +package volume + +import ( + "context" + "errors" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func refusalWith(t *testing.T, text string, kind control.WorkspaceLeaseRefusal_Kind, retry time.Duration) error { + t.Helper() + st, err := status.New(codes.FailedPrecondition, text).WithDetails(&control.WorkspaceLeaseRefusal{Kind: kind, RetryAfterNs: int64(retry)}) + if err != nil { + t.Fatal(err) + } + return st.Err() +} + +// The startup wait's bound starts at the first answered contact, never +// while the master gives no reply; a BARRIER moves it to T + 30 s; a +// transport failure ends the streak (the next contact restarts it); +// credentials refusals have no bound; MOVED and DELETED are final; a +// refusal with the old text and no detail is plain contact, as today. +func TestChunkAuthorityWaitStartsAtFirstContact(t *testing.T) { + now := time.Unix(1_800_000_000, 0) + w := newMasterWait(func() time.Time { return now }, func(string, ...any) {}) + unreachable := status.Error(codes.Unavailable, "connection refused") + + w.call(unreachable) + now = now.Add(5 * time.Minute) + w.call(unreachable) + if d, final := w.state(); !d.IsZero() || final != "" { + t.Fatalf("5 min without a reply: bound %v final %q; want none", d, final) + } + if s := w.snapshot(false); s.Reason != "unreachable" || !s.Until.IsZero() || now.Sub(s.Since) != 5*time.Minute { + t.Fatalf("unreachable status %+v", s) + } + + contact := now + w.call(nil) // a heartbeat answered + now = now.Add(10 * time.Second) + w.call(nil) + if d, _ := w.state(); !d.Equal(contact.Add(MasterWaitLimit)) { + t.Fatalf("bound %v; want first contact + 30 s (%v)", d, contact.Add(MasterWaitLimit)) + } + if s := w.snapshot(false); s.Reason != "no_assignment" || !s.Until.Equal(contact.Add(MasterWaitLimit)) { + t.Fatalf("no-assignment status %+v", s) + } + + // Old text, no detail: contact, as today (no early exit, no barrier). + w.renewal(now, status.Error(codes.FailedPrecondition, "workspace forced move lease expiry plus clock-skew margin has not elapsed")) + if d, final := w.state(); !d.Equal(contact.Add(MasterWaitLimit)) || final != "" { + t.Fatalf("detail-less refusal changed the wait: bound %v final %q", d, final) + } + + // BARRIER: T = request start + retry_after; bound T + 30 s. + start := now + w.renewal(start, refusalWith(t, "barrier", control.WorkspaceLeaseRefusal_BARRIER, 45*time.Second)) + if d, _ := w.state(); !d.Equal(start.Add(45*time.Second + MasterWaitLimit)) { + t.Fatalf("bound %v after BARRIER; want T + 30 s", d) + } + if s := w.snapshot(true); s.Reason != "barrier" || !s.Until.Equal(start.Add(45*time.Second)) { + t.Fatalf("barrier status %+v; want until T", s) + } + + // A transport failure ends the streak; the next contact restarts it. + now = now.Add(time.Minute) + w.call(status.Error(codes.DeadlineExceeded, "slow")) + if d, _ := w.state(); !d.IsZero() { + t.Fatalf("bound %v while unreachable again; want none", d) + } + now = now.Add(2 * time.Minute) + again := now + w.call(nil) + if d, _ := w.state(); !d.Equal(again.Add(MasterWaitLimit)) { + t.Fatalf("bound %v; want the new streak + 30 s", d) + } + + // Credentials refused: no bound, visible. + w.call(status.Error(codes.PermissionDenied, "node revoked")) + now = now.Add(10 * time.Minute) + if d, _ := w.state(); !d.IsZero() { + t.Fatalf("bound %v under refused credentials; want none", d) + } + if s := w.snapshot(true); s.Reason != "credentials" { + t.Fatalf("credentials status %+v", s) + } + + // A plain local error is contact (it is not a transport code). + w.call(errors.New("local")) + for _, k := range []struct { + kind control.WorkspaceLeaseRefusal_Kind + want string + }{{control.WorkspaceLeaseRefusal_MOVED, "moved"}, {control.WorkspaceLeaseRefusal_DELETED, "deleted"}} { + m := newMasterWait(func() time.Time { return now }, func(string, ...any) {}) + m.renewal(now, refusalWith(t, "x", k.kind, 0)) + if _, final := m.state(); final != k.want { + t.Fatalf("%v refusal: final %q; want %q", k.kind, final, k.want) + } + } +} + +// Before its first grant the guard sleeps until the master's barrier time T +// (condition: not a fixed 1 s poll), a detail-less refusal keeps the 1 s +// poll, and a cancel during the long sleep ends Run promptly. +func TestLeaseGuardSleepsUntilTheBarrier(t *testing.T) { + now := time.Unix(1_800_000_000, 0) + var reply error + client := funcLeaseClient(func(context.Context, *control.WorkspaceIdentity, ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + return nil, reply + }) + 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) + } + var observed int + g.observe = func(time.Time, error) { observed++ } + + reply = status.Error(codes.FailedPrecondition, "workspace forced move lease expiry plus clock-skew margin has not elapsed") + _ = g.Refresh(context.Background()) + if d := g.renewDelay(); d != time.Second { + t.Fatalf("delay after a detail-less refusal %v; want the 1 s poll, as today", d) + } + reply = refusalWith(t, "barrier", control.WorkspaceLeaseRefusal_BARRIER, 40*time.Second) + _ = g.Refresh(context.Background()) + if d := g.renewDelay(); d != 40*time.Second { + t.Fatalf("delay after BARRIER %v; want until T (40 s)", d) + } + now = now.Add(39 * time.Second) + if d := g.renewDelay(); d != time.Second { + t.Fatalf("delay 1 s before T: %v", d) + } + now = now.Add(2 * time.Second) + if d := g.renewDelay(); d != time.Second { + t.Fatalf("delay past T %v; want the 1 s poll", d) + } + if observed != 2 { + t.Fatalf("renewals observed %d; want 2", observed) + } + + // Cancel during the long barrier sleep: Run returns at once. + now = time.Unix(1_800_000_000, 0) + g2, _ := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return now }) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- g2.Run(ctx) }() + time.Sleep(100 * time.Millisecond) + stopped := time.Now() + cancel() + select { + case <-done: + if d := time.Since(stopped); d > 2*time.Second { + t.Fatalf("Run took %v to stop during the barrier sleep", d) + } + case <-time.After(10 * time.Second): + t.Fatal("Run did not stop during the barrier sleep") + } +} From 232a74e73e446b5e9030fd3303fb32abaacd7b86 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 21:51:12 -0800 Subject: [PATCH 08/34] feat: /status MasterWait for a workspace primary without a grant Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/main.go | 1 + .../core/host/volume/master_wait_test.go | 23 ++++++++++++++ .../core/host/volume/status_server.go | 30 +++++++++++++++++++ 3 files changed, 54 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 6ae1f22433..b5f037a042 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -630,6 +630,7 @@ func runVolume(f flags, exits *processExit) int { var status *volume.StatusServer if f.statusAddr != "" { status = volume.NewStatusServer(h.ProjectionView()) + status.SetMasterWait(h.MasterWaitStatus) if f.nvmeListen != "" { status.SetNVMeListenerReady(false) } diff --git a/seaweed-block/core/host/volume/master_wait_test.go b/seaweed-block/core/host/volume/master_wait_test.go index bb33d18d77..ced1c0af6a 100644 --- a/seaweed-block/core/host/volume/master_wait_test.go +++ b/seaweed-block/core/host/volume/master_wait_test.go @@ -6,6 +6,8 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/engine" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "google.golang.org/grpc" "google.golang.org/grpc/codes" @@ -161,3 +163,24 @@ func TestLeaseGuardSleepsUntilTheBarrier(t *testing.T) { t.Fatal("Run did not stop during the barrier sleep") } } + +// /status shows MasterWait (reason, since, until) only while a workspace +// primary holds no granted lease. +func TestStatusShowsTheMasterWait(t *testing.T) { + p := stubProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 1, EndpointVersion: 1}} + view := NewAdapterProjectionView(p, "v1", "r1", nil) + view.workspaceRequired = true + s := NewStatusServer(view) + s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}}) + since, until := time.Unix(1000, 0), time.Unix(1045, 0) + s.SetMasterWait(func() *MasterWait { return &MasterWait{Reason: "barrier", Since: since, Until: until} }) + got := s.statusProjection() + if got.NotReadyReason != NotReadyLeaseNotHeld || got.MasterWait == nil || + *got.MasterWait != (MasterWaitStatus{Reason: "barrier", SinceMs: since.UnixMilli(), UntilMs: until.UnixMilli()}) { + t.Fatalf("status %q MasterWait %+v; want barrier since/until", got.NotReadyReason, got.MasterWait) + } + view.workspaceRequired = false + if got := s.statusProjection(); got.MasterWait != nil { + t.Fatalf("MasterWait %+v shown without a lease wait", got.MasterWait) + } +} diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index 456b46f1e3..0202686b8e 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -64,6 +64,7 @@ type StatusServer struct { allowExternal bool peerSource peerStatusSource durableSource durableStatusSource + masterWait func() *MasterWait // why a workspace primary holds no grant; nil: not wired nvmeSource nvmeStatusSource ublkSource ublkStatusSource runtimeSource runtimeRecoverySource @@ -218,6 +219,26 @@ type StatusProjection struct { // wal_hole_suspected, issue #51). Visible, not an alert: they do not // change Healthy or the frontend's readiness. Warnings []string `json:",omitempty"` + // MasterWait is why a workspace primary holds no granted lease, present + // only while NotReadyReason is lease_not_held: Reason (unreachable, + // credentials, barrier, no_assignment, refused, moved, deleted), since + // when, and the wait's bound or the master's barrier time (UntilMs, + // absent while there is no bound). + MasterWait *MasterWaitStatus `json:",omitempty"` +} + +// MasterWaitStatus is MasterWait on /status (unix milliseconds). +type MasterWaitStatus struct { + Reason string + SinceMs int64 + UntilMs int64 `json:",omitempty"` +} + +// SetMasterWait wires the host's master-wait reason into /status. +func (s *StatusServer) SetMasterWait(f func() *MasterWait) { + s.mu.Lock() + s.masterWait = f + s.mu.Unlock() } // CatchUpStatus is a supporting replica's catch-up state. @@ -506,6 +527,7 @@ func (s *StatusServer) statusProjection() StatusProjection { p.Healthy = p.Healthy && !nvmePending p.FrontendPrimaryReady = p.FrontendPrimaryReady && !nvmePending src := s.durableSource + masterWait := s.masterWait s.mu.Unlock() // INV-FE-PRIMARY-READY-OPERATIONAL-001: not FrontendPrimaryReady while the // local backend admits no I/O (before the storage claim of a chunk volume, @@ -534,6 +556,14 @@ func (s *StatusServer) statusProjection() StatusProjection { switch { case leaseNotHeld: p.NotReadyReason = NotReadyLeaseNotHeld + if masterWait != nil { + if w := masterWait(); w != nil { + p.MasterWait = &MasterWaitStatus{Reason: w.Reason, SinceMs: w.Since.UnixMilli()} + if !w.Until.IsZero() { + p.MasterWait.UntilMs = w.Until.UnixMilli() + } + } + } case backendReason != "": p.NotReadyReason = backendReason case nvmePending: From a2cf0f8983a4abc47fadcbe2943bc531acade6a3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 21:53:26 -0800 Subject: [PATCH 09/34] test: waiting through a master outage, barrier, stop, moved, obsolete unit Co-Authored-By: Claude Opus 5.5 --- .../master_wait_integration_test.go | 186 ++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/master_wait_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/master_wait_integration_test.go b/seaweed-block/cmd/blockvolume/master_wait_integration_test.go new file mode 100644 index 0000000000..e2c9f7b738 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/master_wait_integration_test.go @@ -0,0 +1,186 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "encoding/json" + "io" + "net/http" + "syscall" + "testing" + "time" +) + +type masterWaitView struct { + Reason string + Since time.Time + Until time.Time +} + +// masterWaitOf reads /status MasterWait for v1 (ok false when absent). +func masterWaitOf(statusAddr string) (masterWaitView, bool) { + c := &http.Client{Timeout: 2 * time.Second} + resp, err := c.Get("http://" + statusAddr + "/status?volume=v1") + if err != nil { + return masterWaitView{}, false + } + defer resp.Body.Close() + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + var st struct { + MasterWait *struct { + Reason string + SinceMs, UntilMs int64 + } + } + if json.Unmarshal(raw, &st) != nil || st.MasterWait == nil { + return masterWaitView{}, false + } + v := masterWaitView{Reason: st.MasterWait.Reason, Since: time.UnixMilli(st.MasterWait.SinceMs)} + if st.MasterWait.UntilMs != 0 { + v.Until = time.UnixMilli(st.MasterWait.UntilMs) + } + return v, true +} + +func stillRunning(t *testing.T, d *daemon, what string) { + t.Helper() + select { + case <-d.done: + t.Fatalf("%s: %s exited (%v); it must wait", what, d.name, d.err) + default: + } +} + +// waitForBarrier starts a waiting process with the master down, restarts the +// master and returns the process and the barrier time /status shows. +func waitForBarrier(t *testing.T, env *handoffEnv, name string) (*daemon, time.Time) { + t.Helper() + b := env.hosts["s1"] + first := env.start(t, name+"-holder", "s1") + env.adopt(t, first, "s1") + env.masterProcess.kill(t) + if code := exitCode(first.wait(90 * time.Second)); code != 75 { + t.Fatalf("the holder exited %v with the master down; want one fence exit 75", first.err) + } + waiting := env.start(t, name, "s1") + time.Sleep(45 * time.Second) // past the old fixed 30 s wait + stillRunning(t, waiting, "45 s with the master unreachable") + mw, ok := masterWaitOf(b.status) + if !ok || mw.Reason != "unreachable" || !mw.Until.IsZero() || time.Since(mw.Since) < 40*time.Second { + t.Fatalf("/status MasterWait %+v (present %v); want unreachable for 40 s or more, no bound", mw, ok) + } + env.masterProcess = env.h.start(t, name+"-master-back", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + var until time.Time + poll(t, 30*time.Second, "/status never showed the master's barrier", func() bool { + mw, ok := masterWaitOf(b.status) + if ok && mw.Reason == "barrier" && !mw.Until.IsZero() { + until = mw.Until + return true + } + return false + }) + waiting.waitLog(t, 10*time.Second, "re-grant refused until") + return waiting, until +} + +// A start that finds blockmaster unreachable waits inside the process with +// no bound (no exit 75 every ~38 s), shows why on /status, and when the +// master returns shows the master's barrier time and serves within 2 s of +// it, without a restart. +func TestMasterRestartShowsBarrierUntil(t *testing.T) { + env := startHandoffEnv(t, 1) + b := env.hosts["s1"] + waiting, until := waitForBarrier(t, env, "bv-wait") + t.Logf("barrier until %s (%v from now)", until.UTC().Format(time.RFC3339Nano), time.Until(until).Round(time.Millisecond)) + deadline := until.Add(2 * time.Second) + for !volumeFrontendReady(b.status, "v1") { + if time.Now().After(deadline.Add(30 * time.Second)) { + t.Fatal("the waiting process never served after the barrier") + } + stillRunning(t, waiting, "after the barrier") + time.Sleep(100 * time.Millisecond) + } + late := time.Since(until) + t.Logf("served %v after the barrier time", late.Round(time.Millisecond)) + if late > 2*time.Second { + t.Fatalf("served %v after the master's barrier time; want <= 2 s", late.Round(time.Millisecond)) + } + if _, ok := masterWaitOf(b.status); ok { + t.Fatal("/status still shows MasterWait while serving") + } +} + +// SIGTERM (systemctl stop) during either wait ends the process with status 0 +// within 10 s: while the master is unreachable, and at the barrier. +func TestStopDuringMasterWaitReturnsPromptly(t *testing.T) { + env := startHandoffEnv(t, 1) + stopIn := func(d *daemon, what string) { + t.Helper() + at := time.Now() + d.term(t, 10*time.Second) + if d.err != nil { + t.Fatalf("%s: exit %v after SIGTERM; want status 0", what, d.err) + } + t.Logf("%s: stopped in %v", what, time.Since(at).Round(time.Millisecond)) + } + waiting, _ := waitForBarrier(t, env, "bv-stop") + stopIn(waiting, "at the barrier") + + env.masterProcess.kill(t) + unreachable := env.start(t, "bv-stop-unreachable", "s1") + poll(t, 30*time.Second, "/status never showed unreachable", func() bool { + mw, ok := masterWaitOf(env.hosts["s1"].status) + return ok && mw.Reason == "unreachable" + }) + stopIn(unreachable, "unreachable") +} + +// A process waiting at the barrier with its cached assignment at e, frozen +// while a forced move gives the line to s2 at e+1, then resumed: the +// master's typed MOVED refusal ends it with exit 78 moved at once. It never +// served. +func TestWaitingVolumeMovedDuringOutageExits78(t *testing.T) { + env := startHandoffEnv(t, 2) + b := env.hosts["s1"] + holder := env.start(t, "bv-moved-holder", "s1") + e := env.adopt(t, holder, "s1") + holder.kill(t) + time.Sleep(35 * time.Second) // the lease has lapsed; the barrier has not + waiting := env.start(t, "bv-moved-waiting", "s1") + poll(t, 30*time.Second, "/status never showed the barrier", func() bool { + mw, ok := masterWaitOf(b.status) + return ok && mw.Reason == "barrier" + }) + if err := waiting.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatal(err) + } + env.forceMove(t, e, "s2", "force-moved-during-wait") + if err := waiting.proc.Signal(syscall.SIGCONT); err != nil { + t.Fatal(err) + } + err := waiting.wait(60 * time.Second) + if code := exitCode(err); code != 78 || !waiting.has("blockvolume: exiting status=78 reason=moved") { + t.Fatalf("the waiting process exit %v; want 78 reason=moved", err) + } + if waiting.has("adopted as PRIMARY") && volumeFrontendReady(b.status, "v1") { + t.Fatal("the moved process served") + } +} + +// A unit for a volume the master does not assign to this host stops: with +// the master answering, the wait is bounded (30 s from contact) and exits +// 75 assignment_timeout, so the unit still reaches its start limit. +func TestObsoleteUnitStopsWithReachableMaster(t *testing.T) { + env := startHandoffEnv(t, 1) + b := env.hosts["s1"] + b.volume, b.root = "v-unknown", t.TempDir() + at := time.Now() + d := env.h.start(t, "bv-obsolete", env.h.volume, env.volArgsFor(b)...) + err := d.wait(2 * time.Minute) + took := time.Since(at) + t.Logf("obsolete unit exited %v after %v", err, took.Round(time.Millisecond)) + if exitCode(err) != 75 || !d.has("reason=assignment_timeout") || took < 25*time.Second { + t.Fatalf("obsolete unit exit %v after %v; want 75 assignment_timeout after the 30 s bound", err, took) + } +} From b232d8a34223d1143338c7e6dd79828167a2d4a4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 21:53:56 -0800 Subject: [PATCH 10/34] test: the shipped unit survives a 10-minute master outage Replaces the measurement of today's give-up (start limit after ~6 min) with the requirement: one fence restart, never failed, MasterWait unreachable on /status, serving within 2 s of the master's barrier. Co-Authored-By: Claude Opus 5.5 --- ..._systemd_master_outage_integration_test.go | 81 ++++++++++--------- 1 file changed, 43 insertions(+), 38 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_master_outage_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_master_outage_integration_test.go index 084c77787d..de71812de2 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_master_outage_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_master_outage_integration_test.go @@ -15,17 +15,16 @@ import ( "time" ) -// A long blockmaster outage under real systemd (root), with the shipped -// unit's restart policy AND its shipped start limit: a serving volume's -// blockvolume fences, exits 75 and is restarted by the unit; each start -// waits for a grant and exits 75 again. The test keeps the master down until -// systemd stops retrying (the start limit) or 12 minutes pass, records when -// and after how many restarts, then brings the master back and records -// whether the volume serves by itself, and, if the unit failed, how long -// `systemctl reset-failed` + `systemctl start` take to serve it. +// A 10-minute blockmaster outage under real systemd (root), with the shipped +// unit's restart policy and start limit: the serving process fences once and +// exits 75; the unit starts it again and that process waits inside itself +// (no restart loop): the unit never reaches its start limit (NRestarts 1, 2 +// starts), /status shows MasterWait unreachable with its age, and when the +// master returns the volume serves by itself within 2 s of the master's +// barrier time. // // A runtime unit file (/run/systemd/system) stands for the installed unit. -func TestSystemdMasterOutagePastTheStartLimit(t *testing.T) { +func TestUnitSurvivesTenMinuteMasterOutage(t *testing.T) { if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" { t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof") } @@ -55,43 +54,49 @@ func TestSystemdMasterOutagePastTheStartLimit(t *testing.T) { killAt := time.Now() env.masterProcess.kill(t) var state map[string]string - gaveUp := false - for deadline := killAt.Add(12 * time.Minute); time.Now().Before(deadline); time.Sleep(2 * time.Second) { + for deadline := killAt.Add(10 * time.Minute); time.Now().Before(deadline); time.Sleep(2 * time.Second) { s, err := gap1ReadUnit(unit) - if err == nil { - state = s - if s["ActiveState"] == "failed" { - gaveUp = true - break - } + if err != nil { + continue + } + state = s + if s["ActiveState"] == "failed" { + t.Fatalf("the unit gave up %v into the outage (NRestarts %s, Result %s)", time.Since(killAt).Round(time.Second), s["NRestarts"], s["Result"]) } } - downFor := time.Since(killAt) - journal := unitJournal(unit) - t.Logf("PHASE0-SYSTEMD master down %v: unit gave up (start limit %s in %s) %v; NRestarts %s; ActiveState %s; Result %s; 'Start request repeated too quickly' %v", - downFor.Round(time.Second), burst, interval, gaveUp, state["NRestarts"], state["ActiveState"], state["Result"], strings.Contains(journal, "Start request repeated too quickly")) + mw, ok := masterWaitOf(b.status) + t.Logf("PHASE0-SYSTEMD master down %v: ActiveState %s NRestarts %s; MasterWait %+v", + time.Since(killAt).Round(time.Second), state["ActiveState"], state["NRestarts"], mw) + if state["ActiveState"] != "active" || state["NRestarts"] != "1" { + t.Fatalf("after 10 min: ActiveState %s NRestarts %s; want active after exactly one restart (the fence)", state["ActiveState"], state["NRestarts"]) + } + if !ok || mw.Reason != "unreachable" || time.Since(mw.Since) < 9*time.Minute { + t.Fatalf("/status MasterWait %+v (present %v); want unreachable for most of the outage", mw, ok) + } env.masterProcess = env.h.start(t, "blockmaster-back", env.h.master, env.masterArgs...) env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") - backAt := time.Now() - served := false - for deadline := backAt.Add(90 * time.Second); time.Now().Before(deadline) && !served; time.Sleep(time.Second) { - served = volumeFrontendReady(b.status, "v1") + var until time.Time + poll(t, 30*time.Second, "/status never showed the master's barrier", func() bool { + mw, ok := masterWaitOf(b.status) + if ok && mw.Reason == "barrier" && !mw.Until.IsZero() { + until = mw.Until + return true + } + return false + }) + for !volumeFrontendReady(b.status, "v1") { + if time.Now().After(until.Add(60 * time.Second)) { + t.Fatal("v1 never served by itself after the master returned") + } + time.Sleep(100 * time.Millisecond) } - if served { - t.Logf("PHASE0-SYSTEMD with the master back, v1 served by itself after %v", time.Since(backAt).Round(time.Millisecond)) - return + late := time.Since(until) + s, _ := gap1ReadUnit(unit) + t.Logf("PHASE0-SYSTEMD master back: served %v after the barrier time; NRestarts %s", late.Round(time.Millisecond), s["NRestarts"]) + if late > 2*time.Second || s["NRestarts"] != "1" { + t.Fatalf("served %v after the barrier (want <= 2 s), NRestarts %s (want 1)", late.Round(time.Millisecond), s["NRestarts"]) } - t.Logf("PHASE0-SYSTEMD with the master back, v1 did not serve by itself within 90 s (unit %s)", state["ActiveState"]) - if out, err := runSystemctl("reset-failed", unit); err != nil { - t.Fatalf("systemctl reset-failed %s: %v %s", unit, err, out) - } - resetAt := time.Now() - if out, err := runSystemctl("start", unit); err != nil { - t.Fatalf("systemctl start %s: %v %s", unit, err, out) - } - poll(t, 3*time.Minute, "v1 never served after reset-failed and start", func() bool { return volumeFrontendReady(b.status, "v1") }) - t.Logf("PHASE0-SYSTEMD after reset-failed + start, v1 served after %v", time.Since(resetAt).Round(time.Millisecond)) } // shippedStartLimit reads StartLimitIntervalSec and StartLimitBurst from the From 887564ee845a1b41d3ed3dab4d48d688281d11da Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 21:55:22 -0800 Subject: [PATCH 11/34] docs: ledger rows for the master wait INV-WS-MASTER-WAIT-001 (new, ACTIVE), its C.W wait site, and the startup-wait wording of the M2 exit transition, INV-WS-SERVE-LEASE-HELD-001, TERM-SERVING-001, TERM-STOP-EXIT-001 and the supervisor retry row. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e6252c26ab..9e21840ce7 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -169,7 +169,7 @@ a pre-issued publication. | Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node (the source itself only for a clean, non-force move), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-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 | Granted | Same current primary server/replica/epoch, validated by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) with missing server refused, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-AUTH-HOLDER-IDENTITY-001` | -| Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait or lease fence exits 75 after bounded cleanup; a foreign master fact newer than nonzero observed-own lineage or exact foreign HEAD at or above the assigned epoch permits 78. Planned drain retires startup monitoring before cleanup; ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` | +| Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait (`INV-WS-MASTER-WAIT-001`: 30 s of answered contact past the master's barrier time; no bound while the master gives no reply) or lease fence exits 75 after bounded cleanup; a typed MOVED or DELETED lease refusal exits 78 at once; a foreign master fact newer than nonzero observed-own lineage or exact foreign HEAD at or above the assigned epoch permits 78. Planned drain retires startup monitoring before cleanup; ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` | | Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | | Moved | epoch issued | the moved owner is captured with the assignment under pub.mu and persisted with the issuing move journal before publication; the stream uses that captured owner, empty when unknown, with placement fallback only for a move-less epoch; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/workspace_binding.go` `workspaceLineOwner`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` | @@ -497,7 +497,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -320 rows: 249 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 303 new. +321 rows: 250 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 304 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -513,7 +513,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-FE-NVME-READY-ANA-001` | An I/O that ends during the attachment-readiness wait because the backend closed or its lineage went stale keeps its ANA error, and a physical I/O fault keeps Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | | `INV-FE-PRIMARY-READY-OPERATIONAL-001` | FrontendPrimaryReady is reported only while the local durable backend admits I/O, and the frontend target listens only after it first does; attach-pending, fenced or no durable status reports not ready with the reason. | M1 Opened / Recovering → Serving; M2 process exit | `core/host/volume/status_server.go` `statusProjection`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (the iSCSI, NVMe and ublk targets in `cmd/blockvolume/main.go` `runVolume` start after it); `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` | `TestStatusServer_ReadyOnlyWhileBackendOperational`, `TestStatusServer_NotReadyAlwaysHasAReason` (`core/host/volume/status_server_test.go`); `TestFrontendGateWaitsForTheStorageClaim`, `TestFrontendGateStopsWithoutStartingTheFrontends` (`cmd/blockvolume/frontend_gate_test.go`); `TestDurableProvider_NonChunkVolumeServesRightAfterOpen` (`core/frontend/durable/first_serving_test.go`) | — | ACTIVE | | `INV-FE-FENCE-EXIT-001` | A workspace chunk primary whose backend fences after its target listens ends the process within detection plus the 5 s cleanup bound: a lease expiry at the guard's own deadline, a HEAD fence within 50 ms. | M1 Serving → Closed; M2 process exit | `core/frontend/durable/provider_startup.go` `watchChunkFence` (HEAD fence: not operational with the evidence within 50 ms; I/O refused from the fence); `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (78 `head_fenced`) and `waitWorkspaceStop` (lease fence: 75 `lease_expired`); `superviseProcess` (the 5 s cleanup bound from the decision) | `TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational` (`core/frontend/durable/runtime_fence_test.go`); `TestRuntimeHeadFenceChoosesHeadFencedExit` (`cmd/blockvolume/runtime_fence_exit_test.go`); real-binary case C (lease expiry after listening: exit 75) | — | ACTIVE | -| `INV-WS-SERVE-LEASE-HELD-001` | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now; without a granted lease it holds at the gate and exits 75 after the start-time wait. | M1 Recovering → Serving; M2 process exit | `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.Held` / `permits` (the one deciding function: the guarded projection gates the chunk claim, the per-I/O admit and `FrontendPrimaryReady`); `core/frontend/durable/storage_adapter.go` `AdmitsIO` (the one "may serve" function, the I/O gate: backend admits AND guarded projection names this lineage; V1-SPEC r2.39); `core/host/volume/status_server.go` `statusProjection` (`FrontendPrimaryReady` from `AdmitsIO`; `NotReadyReason=lease_not_held` first); `cmd/blockvolume/frontend_gate.go` `frontendStartSignal` / `awaitFrontendStart` (a workspace primary's frontends start once `AdmitsIO` passes; non-chunk and supporting replicas start after open as before); `cmd/blockvolume/process_exit.go` (exit 75 `assignment_timeout`) | `TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease`, `TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals`, `TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant` (`core/host/volume/workspace_lease_held_test.go`); `TestStorageBackend_AdmitsIOIsTheIOGate` (`core/frontend/durable/admits_io_test.go`); `TestFrontendStartSignal_WorkspacePrimaryWaitsForAdmitsIO`, `TestFrontendStartSignal_OtherVolumesStartAfterOpenAsBefore`, `TestFirstAdmittedStopEndsTheWorker` (`cmd/blockvolume/frontend_start_signal_test.go`); real-binary cases B-late (restart before the forced-move barrier, re-granted inside the wait: no claim, listen or ready before the re-grant), B75 (no grant inside the wait: no claim, listen or ready, exit 75; a restart after the barrier serves) and B0 (restart inside the lease serves at once) | — | ACTIVE | +| `INV-WS-SERVE-LEASE-HELD-001` | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now; without a granted lease it holds at the gate and exits 75 when the startup wait runs out (`INV-WS-MASTER-WAIT-001`). | M1 Recovering → Serving; M2 process exit | `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.Held` / `permits` (the one deciding function: the guarded projection gates the chunk claim, the per-I/O admit and `FrontendPrimaryReady`); `core/frontend/durable/storage_adapter.go` `AdmitsIO` (the one "may serve" function, the I/O gate: backend admits AND guarded projection names this lineage; V1-SPEC r2.39); `core/host/volume/status_server.go` `statusProjection` (`FrontendPrimaryReady` from `AdmitsIO`; `NotReadyReason=lease_not_held` first); `cmd/blockvolume/frontend_gate.go` `frontendStartSignal` / `awaitFrontendStart` (a workspace primary's frontends start once `AdmitsIO` passes; non-chunk and supporting replicas start after open as before); `cmd/blockvolume/process_exit.go` (exit 75 `assignment_timeout`) | `TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease`, `TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals`, `TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant` (`core/host/volume/workspace_lease_held_test.go`); `TestStorageBackend_AdmitsIOIsTheIOGate` (`core/frontend/durable/admits_io_test.go`); `TestFrontendStartSignal_WorkspacePrimaryWaitsForAdmitsIO`, `TestFrontendStartSignal_OtherVolumesStartAfterOpenAsBefore`, `TestFirstAdmittedStopEndsTheWorker` (`cmd/blockvolume/frontend_start_signal_test.go`); real-binary cases B-late (restart before the forced-move barrier, re-granted inside the wait: no claim, listen or ready before the re-grant), B75 (no grant inside the wait: no claim, listen or ready, exit 75; a restart after the barrier serves) and B0 (restart inside the lease serves at once) | — | ACTIVE | | `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`); `TestNativeReplacementCheckpointSIGKILL` (`core/storage/legacy_checkpoint_replacement_v3_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | @@ -774,6 +774,7 @@ Notes: | `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | | `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE | +| `INV-WS-MASTER-WAIT-001` | A workspace primary's startup wait has no bound while blockmaster gives no reply or refuses its credentials; once it answers, the wait ends 30 s after max(contact streak start, the master's barrier time), and a typed MOVED or DELETED lease refusal ends it at once with 78. | M2 Awaiting assignment → Process exited | `core/host/volume/master_wait.go` `masterWait` (contact from heartbeat, stream and renewal results; the refusal kind from the status detail only); `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` (`ChunkMasterWait`); `cmd/blockvolume/process_exit.go` `chooseChunkStartupExit`; `core/host/master/workspace_service.go` `leaseRefusal`, `renewalMoved`; `core/authority/workspace_lease_view.go` `LeaseBarrierError`; `core/host/volume/workspace_lease.go` `renewDelay` (sleeps until the barrier time); `core/rpc/link/link.go` `MasterReconnect` | `TestChunkAuthorityWaitStartsAtFirstContact`, `TestLeaseGuardSleepsUntilTheBarrier`, `TestStatusShowsTheMasterWait` (`core/host/volume/master_wait_test.go`); `TestMasterLinkReconnectsWithinTwoSeconds` (`core/host/volume/master_reconnect_test.go`); `TestChunkAuthorityWaitFollowsTheMasterWait` (`core/frontend/durable/provider_master_wait_test.go`); `TestLeaseRefusalKinds` (`core/host/master/workspace_lease_refusal_kind_test.go`) | — | ACTIVE | - `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process. - Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages`, `TestWorkspaceExitLineageIncludesBlockedOwnAssignment`, and `TestWorkspaceObservedLineageNeverTrailsAdoption` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal. @@ -1047,6 +1048,7 @@ One row per wait in the data and control paths. Guest-visible rows on one path m | `cmd/blockvolume/main.go` `runVolume`, the receive of `stopWait` after the frontends started (when `awaitFrontendStart` released on first serving) | the one result of the `waitWorkspaceStop` goroutine (its only producer, a channel of capacity one it sends to exactly once) | the process lifetime, as `waitWorkspaceStop` | the process exit owner (`superviseProcess`) | shutdown with the handed-back lease drain request | none | no (the targets serve until the stop) | | `core/frontend/durable/provider_startup.go` `watchChunkFence` (one goroutine per attached chunk layer, started when the layer attaches) | the 50 ms ticker (then reads the layer's latched fence flag) or provider close (`closeCtx`) | the attached layer's lifetime: it returns at provider close, when the layer is no longer the volume's, or after publishing a fence; Close joins it (`p.inflight`) | `DurableProvider.Close` (cancels `closeCtx`, then waits `p.inflight`) | none: the ticker is its poll, not a deadline; a HEAD fence is published at most 50 ms after the layer latches it (I/O is refused from the latch) | none while waiting (`p.mu` only briefly to check the handle and publish) | no | | `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (one goroutine from `runVolume`, workspace chunk primaries) | the provider's runtime-fence wakeup (capacity one, `ChunkRuntimeFenceUpdates`), the process outcome (`e.done`) or the watch context | the process lifetime: it returns after choosing 78 `head_fenced`, when another outcome is chosen, or when `runVolume` cancels its watch context | the process exit owner (`superviseProcess`) | none | none | no | +| `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` (one goroutine per recovery of a workspace chunk primary awaiting authority) | a healthy projection (own assignment and a lease grant), then the HEAD claim | none while blockmaster gives no reply or refuses the node's credentials (it serves nothing and holds no lease); once it answers, max(contact streak start, the master's barrier time) + 30 s; each attach attempt 30 s | the host's contact observations (`core/host/volume/master_wait.go`), provider Close, a later recovery | exit 75 `assignment_timeout`; 78 `moved` or `deleted` at once on a typed refusal | none: the bound is read on the 20 ms poll without `p.mu` or `h.attachMu` | no (no target listens) | Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The W/BASE/fence owner (`WALStore.recoverV3`) must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. @@ -1068,7 +1070,7 @@ Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed sc |---|---|---|---|---| | Workspace revocation ACK closeout | M2 Revoking → Revoked; `INV-WS-STARTUP-RETRY-001` | Existing `workspaceLeaseCloseoutTimeout` (3 s), after the resource owner replies to the guard | `finishWorkspaceLease` owns the wait. ACK success selects normal exit; error/expiry selects 75 with `revoke_ack_unconfirmed`. The 5 s supervisor cleanup clock starts only after a nonzero outcome is selected. | No provider/storage lock held. | | Workspace primary retry cleanup | M2 restart; `INV-WS-STARTUP-RETRY-001` | Existing `WorkspaceDrainTimeout` (5 s) after retry/no-retry outcome selection | Process supervisor owns the deadline and returns 75 or 78 even if resource-owner cleanup blocks; first outcome stays latched. Signal and ACKed revocation retain normal exit. | Provider latches by recovery generation under p.mu; wake is nonblocking; the supervisor holds no provider/storage lock. | -| Workspace primary supervisor retries | M2 restart; `INV-WS-STARTUP-RETRY-001` | Shipped systemd units: `StartLimitIntervalSec=600`, `StartLimitBurst=10`, `RestartSec=5s`. Each cycle is the assignment wait (default 30 s) + 5 s, reaching the limit in about 6 minutes. If the assignment wait exceeds about 55 s, raise the interval too or the window never fills | systemd owns the restart window: after 10 starts in 600 s, another start within the window is refused and the unit fails; operator reset/start follows remediation. Exit 78 and ACKed exit 0 do not restart. | No application lock; `TestBlockvolumeUnitsBoundStartupRetries` (`internal/testops/blockvolume_systemd_test.go`) checks both shipped units. | +| Workspace primary supervisor retries | M2 restart; `INV-WS-STARTUP-RETRY-001` | Shipped systemd units: `StartLimitIntervalSec=600`, `StartLimitBurst=10`, `RestartSec=5s`. While the master answers, each cycle is the assignment wait (30 s from contact) + 5 s, reaching the limit in about 6 minutes; while it gives no reply the process waits without exiting, so an outage costs one start (the fence), not the limit. If the assignment wait exceeds about 55 s, raise the interval too or the window never fills | systemd owns the restart window: after 10 starts in 600 s, another start within the window is refused and the unit fails; operator reset/start follows remediation. Exit 78 and ACKed exit 0 do not restart. | No application lock; `TestBlockvolumeUnitsBoundStartupRetries` (`internal/testops/blockvolume_systemd_test.go`) checks both shipped units. | | Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; positive HTTP timeoutMs. Completed uploads resume only within one blockvolume process and matching owner/HEAD/chunk versions; after restart the seal must fit seal_timeout_ms. | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. | | Plain seal remote proof | M5 RemoteProof; `INV-WS-SEAL-REPLAY-001` | Earlier caller context or existing 2 s HEAD-operation bound for the filer read; attachment serialization retains its owner's cooperative caller bound | Provider registers with Close; closeBoundRemote cancels the read, and Close joins it. Failure keeps frontend admission closed. | Attachment mutex serializes against recover/detach; no backend/store/map lock spans the filer read. | | Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` (not reachable in this release) | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. | @@ -1102,13 +1104,13 @@ A row that names a function existing only on an open pull request says so ("on # |---|---|---|---|---|---| | `TERM-HOLDER-001` Holder identity (the primary of a single-copy workspace volume only; supporting replicas are not holders) | The process that may act as primary of a single-copy workspace volume at an epoch is the pair (server id, replica id) at that epoch. A matching replica id or endpoint alone never names it, and a missing server id is refused. No local-root nonce joins it (V1-SPEC r2.45); one live process per volume on a host is the host lock (`TERM-ONE-PROCESS-001`). | `AssignmentFact` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/control.proto`; `server_id` on [#411](https://github.com/seaweedfs/seaweed-block/pull/411)); `WorkspaceIdentity` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/workspace.proto`; `server_id` on #411); the published line's `PublishedLine.IssuedHost` (`core/authority/workspace_lease_view.go`) and the move journal's `WorkspaceMoveRecord.NewHost` (`core/authority/workspace.go`); the volume's `Config.ServerID`, `Config.ReplicaID` (`core/host/volume/host.go`, from `--server-id`, `--replica-id`); the HEAD `Holder`, written as `/` (`cmd/blockvolume/chunk_remote.go` `chunkHolder`) | Master: `core/host/master/workspace_service.go` `services.holderMatches(volume, replica, server, epoch)`, on #411; it gates `RenewWorkspaceLease` and `AckWorkspaceRevoked`, after the host check of #416, and takes the line's owner server from `core/host/master/workspace_binding.go` `Host.workspaceLineOwner`, on #423, the one owner decision for current and historical lines (through `PublishedLine.Owner`, which the snapshot builder's `expectOwnerForLine` also calls). The line's owner server is carried in the published line; a move's line names the move's new host; placement names the owner only for the initial line; an unknown owner is sent empty and never adopted. A volume that has seen an epoch owned by one server never adopts that epoch for another (this covers replays). The safety rule is the refusal to adopt a line naming another server; fencing on a foreign line is defence in depth, and only a process that has adopted a lineage fences, on a strictly newer foreign line. Volume: `core/host/volume/assignment_holder.go` `Host.assignmentNamesSelf`, on #411; called by `applyFact` and `IsSuperseded`. | `Host.applyFact` adopts a fact on the replica id alone. `Host.IsSuperseded` ignores a same-replica line from another server. `Host.recordOtherLine` lets an older line overwrite a newer one. Lease renewals and revocation ACKs carry no server id. All four are removed by #411. The master's status frontends and CSI publish target take the freshest same-replica heartbeat from any server (`ObservationStore.SlotFact` via `statusFrontendsForAssignedVolume`), and the operator's primary node is the placement slot (`serverForReplica`). Both are removed by [#416](https://github.com/seaweedfs/seaweed-block/pull/416), stacked on #411. The master computed the line's owner server twice; #423 makes it one function. | authority (master side); volume host (volume side) | | `TERM-LEASE-NOW-001` Lease valid now | The holder may act on its workspace lease at this instant only while the guard has not fenced and host monotonic time is before the start of its last successful renewal plus the granted validity. The granted validity is the master expiry less half the clock-skew bound, capped by the configured TTL. The takeover margin (half the skew bound) exceeds the configured fence-exit budget (watch cadence 50 ms + drain timeout 5 s), assuming normal scheduling; blockmaster refuses a smaller or equal margin at startup, deriving the budget from `durable.ChunkFenceWatchInterval` and `volume.WorkspaceDrainTimeout`. Safety premise for v1.0, alongside one live process per holder (`TERM-ONE-PROCESS-001`): blockmaster's host slews its wall clock, not steps it, while volumes are served; a step larger than the configured skew bound while a lease is live is unsupported (see `docs/operator-guide.md`, Clock safety requirement). This closes coverage gap 8 by a documented premise, not a wall-step test. | `WorkspaceLease` `ExpiresAtNS`, `MaxClockSkewNS`, and the lease view's durable horizon and granted deadline (`core/authority/workspace_lease_view.go`); `WorkspaceLeaseFact` `valid_for_ns`, `expires_at_ns`, `revoking` (`core/rpc/proto/workspace.proto`); `WorkspaceLeaseGuard` `until`, `fenced` (`core/host/volume/workspace_lease.go`) | Holder: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.permits`. Master: `core/authority/workspace_lease_view.go` `Publisher.WorkspaceLeaseValidity` / `workspaceLeaseValidityAt` is shared by renewal admission, `leaseFact` and `AckWorkspaceRevocation`. `WorkspaceLeaseValidity` reads the publisher clock; its leaf calculation uses the larger configured/persisted skew and configured TTL. `Publisher.RenewWorkspaceLease`. `firstWorkspaceGrant` and `regrantWorkspaceLease` are reached only from it, and only it starts the extender `extendWorkspaceLease`. | `WorkspaceLeaseGuard.drain` checks `now < until` again inline before the ACK, and `WorkspaceLeaseGuard.Refresh` repeats the expiry check of `permits`: open (both should call one predicate). The host reply sanity bound in `Refresh` still repeats the publisher's default 30 s TTL: open. Not a duplicate: `Publisher.forcedMoveBarrierLocked` decides the opposite term, "the lease is over for the master" (the horizon and the deadline each plus the full skew bound), which a forced move and a re-grant need. Follow-up for 1.0.1: split `workspaceNow` into wall and monotonic sources so the barrier for in-memory lines uses monotonic time, and add a real independent wall-step test. No new clock seam is added in v1.0. | authority (grant); volume host (guard) | -| `TERM-SERVING-001` Serving / ready | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now and its durable backend is operational. Without a granted lease it holds at the gate and exits 75 after the start-time wait. | `frontend.Projection.Healthy`; the `StorageBackend` operational flag and its evidence, reported as `VolumeStatus.Operational` (`core/frontend/durable`); `StatusProjection.FrontendPrimaryReady` (and `NotReadyReason`, on [#410](https://github.com/seaweedfs/seaweed-block/pull/410)); the ALUA and ANA state; `HeartbeatSlot.frontends` | Authority side: `core/host/volume/projection_bridge.go` `AdapterProjectionView.projectionWithSupersede`, which ANDs in `WorkspaceLeaseGuard.permits` for workspace volumes. Storage side: the `StorageBackend` operational flag (`core/frontend/durable/storage_adapter.go`), written only by `SetOperational` and read by `readyCheck`. The one decision of both sides together is `StorageBackend.AdmitsIO` (the guarded AND), read by the status, the frontend start gate and every I/O: on #410 (today `StorageBackend.gate` on `main`). | `StatusServer.authorityProjection` derives `FrontendPrimaryReady` from the authority view alone, and it repeats the supersede and supporting tests that `Healthy` already contains. #410 adds the backend half in `statusProjection`; the repeated tests remain open. The frontends listen whether or not the backend admits I/O: #410 holds them in `awaitBackendAdmitsIO` until it does. #410 replaces its earlier `backendAdmitsIO` (which read only `VolumeStatus.Operational`) with `StorageBackend.AdmitsIO`. A later lease fence ends the process on [#409](https://github.com/seaweedfs/seaweed-block/pull/409). `projectionALUAProvider.ALUAState` and `projectionANAProvider.ANAState` (`cmd/blockvolume`) follow the projection only: open. The start-time wait (`chunkAuthorityWait`; `ProviderConfig.ChunkAssignmentTimeout`, 30 s by default) ends once, and the process then stays up without serving: #409 makes it exit 75. iSCSI reports a not-ready or busy backend as a medium error, while NVMe retries the same error: [#415](https://github.com/seaweedfs/seaweed-block/pull/415) (`frontend.ClassifyBackendError`). The heartbeat `Frontends` are set when the listeners start and cleared only at shutdown: open. | volume host | +| `TERM-SERVING-001` Serving / ready | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now and its durable backend is operational. Without a granted lease it holds at the gate and exits 75 when the startup wait runs out (`INV-WS-MASTER-WAIT-001`). | `frontend.Projection.Healthy`; the `StorageBackend` operational flag and its evidence, reported as `VolumeStatus.Operational` (`core/frontend/durable`); `StatusProjection.FrontendPrimaryReady` (and `NotReadyReason`, on [#410](https://github.com/seaweedfs/seaweed-block/pull/410)); the ALUA and ANA state; `HeartbeatSlot.frontends` | Authority side: `core/host/volume/projection_bridge.go` `AdapterProjectionView.projectionWithSupersede`, which ANDs in `WorkspaceLeaseGuard.permits` for workspace volumes. Storage side: the `StorageBackend` operational flag (`core/frontend/durable/storage_adapter.go`), written only by `SetOperational` and read by `readyCheck`. The one decision of both sides together is `StorageBackend.AdmitsIO` (the guarded AND), read by the status, the frontend start gate and every I/O: on #410 (today `StorageBackend.gate` on `main`). | `StatusServer.authorityProjection` derives `FrontendPrimaryReady` from the authority view alone, and it repeats the supersede and supporting tests that `Healthy` already contains. #410 adds the backend half in `statusProjection`; the repeated tests remain open. The frontends listen whether or not the backend admits I/O: #410 holds them in `awaitBackendAdmitsIO` until it does. #410 replaces its earlier `backendAdmitsIO` (which read only `VolumeStatus.Operational`) with `StorageBackend.AdmitsIO`. A later lease fence ends the process on [#409](https://github.com/seaweedfs/seaweed-block/pull/409). `projectionALUAProvider.ALUAState` and `projectionANAProvider.ANAState` (`cmd/blockvolume`) follow the projection only: open. The start-time wait (`chunkAuthorityWait`; `ProviderConfig.ChunkAssignmentTimeout`, 30 s by default) ends once, and the process then stays up without serving: #409 makes it exit 75. iSCSI reports a not-ready or busy backend as a medium error, while NVMe retries the same error: [#415](https://github.com/seaweedfs/seaweed-block/pull/415) (`frontend.ClassifyBackendError`). The heartbeat `Frontends` are set when the listeners start and cleared only at shutdown: open. | volume host | | `TERM-STOP-SUPERSEDED-001` Superseded | A newer published line for this volume names another holder (another replica, or the same replica on another server) at or above this process's epoch and endpoint version. From then on the process is not healthy. | `Host.lastOther` (an `AssignmentFact`); the process's own epoch and endpoint version | Volume: `core/host/volume/host.go` `Host.IsSuperseded`. Its same-replica branch, and the ordered `recordOtherLine` it reads, are on #411. | The status repeat listed under `TERM-SERVING-001`. `Host.IsCurrentReplicaSuperseded` (on #409) and `Host.promotionReady` call `IsSuperseded` with other lineages. They are wrappers, not second derivations. | volume host | | `TERM-STOP-LEASE-FENCED-001` Lease fenced / revoked | The lease guard has latched: its deadline passed, a reply was invalid or late, the lease is revoking, or the process is stopping. A fenced guard never reopens. The host drains, and only when the lease was revoked does it acknowledge with the HEAD generation. | `WorkspaceLeaseGuard` `fenced`, `cause`, `revoked` (`core/host/volume/workspace_lease.go`) | Volume: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.fenceLocked`, the one writer of `fenced`; it is read through `permits`. | `Host.FenceWorkspaceLease` and `runWorkspaceLease` (`core/host/volume/workspace_runtime.go`) set `fenced` directly, with no cause, and keep a second latch, `Host.workspaceLeaseFenced`: open. On `main` a guard fence ends the process with status 0: #409 makes it exit 75. | volume host | | `TERM-STOP-HEAD-FENCED-001` HEAD fenced | HEAD shows a higher epoch, or another holder at this epoch. The chunk layer latches fenced and publishes nothing more, and the backend refuses I/O as stale. | HEAD `Epoch`, `Holder`, `Gen`; `chunkLayerImpl` `fenced` (`core/storage`) | Volume: `core/storage/chunk_layer.go` `chunkLayerImpl.supersededBy`. | `ClaimChunkHead` (`core/storage/chunk_restore.go`) repeats the comparison inline: open. Four cut and detach paths in `chunk_layer.go` set `fenced` directly, next to the setter `fencePublication`: open (one setter). A HEAD fence after startup ends the process with 78 (`head_fenced`): on #410. A refused startup claim exits with 78: on #409. | chunk layer | | `TERM-STOP-STALE-ROOT-001` Stale local root | An existing local root whose HEAD another holder has published, or whose local durable LSN is below HEAD's `remote_lsn`, is refused before the claim and never served. A rolled-back copy exits 78; a foreign holder below the assignment's epoch stays up without serving. | HEAD `Holder`, `RemoteLSN`; `ProviderConfig.ChunkHolder`; the store's durable LSN (`WALStore.Boundaries`) | Volume: the `PrepareRestore` check inside `DurableProvider.newChunkLayer` (`core/frontend/durable/provider_chunk.go`). It is not a named function: open. | A copy of the root taken after its last cut has HEAD's LSN and passes: no local check sees it (never restore a root from a copy). | volume host | | `TERM-STOP-SEALED-001` Sealed | HEAD is detached by this holder at this epoch with a matching `DetachedBy` proof (generation, epoch, holder). The sealing process never reopens it, and only that proof licenses a clean move. | HEAD `State`, `DetachedBy` `Gen`, `Epoch`, `Holder` | Volume: `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`. Master: `core/host/master/workspace_head.go` `NewWorkspaceHEADReader`, whose reader checks the proof before `workspaceHeadAdmits` sees the HEAD. | Revocation ACK also delegates to `ReadDetachedChunkHead` through `workspaceDetachedGeneration` (`cmd/blockvolume/workspace_lease.go`); `TestWorkspaceRevocationUsesExactStoredSeal` (`cmd/blockvolume/workspace_proof_test.go`) checks assigned epoch/holder, fresh proof and read errors without a write. The sealed-reopen test in `ClaimChunkHead` checks state, epoch and holder without the proof: open. | chunk layer (volume side); authority (master side) | -| `TERM-STOP-EXIT-001` Exit class of a stopped workspace primary | A workspace primary that stops ends its process with one latched class. 75 means retry (start-time wait exhausted, lease fence, unconfirmed ACK). 78 means superseded (the line names another holder). 0 is used only after an ACKed revocation or a signal. | `workspaceExit` `code`, `reason`; the `processExit` decision (`cmd/blockvolume/process_exit.go`, on #409) | Volume: `cmd/blockvolume/process_exit.go` `workspaceRetryOutcome`, on #409. `processExit.choose` latches the first outcome. | `chooseChunkStartupExit` (on #409) turns 75 into 78 on a refused HEAD claim (`DurableProvider.ChunkStartupSuperseded`), outside `workspaceRetryOutcome`: open. On #409 alone, "superseded" means another replica; the same replica on another server counts only with #411's `IsSuperseded`: open until both merge. | volume host | +| `TERM-STOP-EXIT-001` Exit class of a stopped workspace primary | A workspace primary that stops ends its process with one latched class. 75 means retry (start-time wait exhausted, lease fence, unconfirmed ACK). 78 means superseded (the line names another holder, or the master refused the lease as moved or deleted). 0 is used only after an ACKed revocation or a signal. | `workspaceExit` `code`, `reason`; the `processExit` decision (`cmd/blockvolume/process_exit.go`, on #409) | Volume: `cmd/blockvolume/process_exit.go` `workspaceRetryOutcome`, on #409. `processExit.choose` latches the first outcome. | `chooseChunkStartupExit` (on #409) turns 75 into 78 on a refused HEAD claim (`DurableProvider.ChunkStartupSuperseded`), outside `workspaceRetryOutcome`: open. On #409 alone, "superseded" means another replica; the same replica on another server counts only with #411's `IsSuperseded`: open until both merge. | volume host | | `TERM-ONE-PROCESS-001` One live process per volume per host | At most one blockvolume process serves a volume on one host: each holds `/run/sw-block/locks/.lock` from before its store opens, whatever its `--durable-root`. Across hosts the assignment and the workspace lease keep holders apart. | The host lock file (`durable.HostVolumeLockDir`, `deploy/systemd/sw-block.tmpfiles.conf`); the store file `<--durable-root>/.bin` (`cmd/blockvolume/main.go` `durableCreateGeometry`); their exclusive OS file locks; the HEAD `Holder` | Volume: `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` (on #439; `ProviderConfig.HostVolumeLock`, set by blockvolume; a missing directory refuses the provider), taken in `ensureHandle` before the store opens and released after it closes. `core/storage/volume_lock.go` `LockWALStoreFile`: an exclusive, non-blocking `flock` in `volume_lock_unix.go` and an exclusive, fail-immediately `LockFileEx` in `volume_lock_windows.go`. It is taken by v3 create and open and by the read-only open. | Not a second derivation but the locks' limit: they cover one host. A second process is not refused when it runs on another host with the same server id, in a container without the host's `/run/sw-block/locks` (the Kubernetes renderer does not mount it: open), or on a copied root on another host. Two such processes with one holder string both pass `ClaimChunkHead` and both renew. A failed CAS against the other process's same-epoch, same-holder HEAD is treated as a conflict, not a fence (`publicationOwnerChanged`): open. #416 refuses a server id that heartbeats from another host's address (`refuseServerIDFromOtherHost`), which covers part of this. The master's grants carry no per-process identity: open. | storage engine | Notes: From be75beed90b2dafc9e6b5f987e88dea1bf510ef7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 22:27:32 -0800 Subject: [PATCH 12/34] fix: a typed moved/deleted refusal names the exit; status schema doc Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/process_exit.go | 6 ++++-- seaweed-block/docs/status-schema.md | 4 ++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 3e81e14fe5..d3e98449f8 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -249,9 +249,11 @@ func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStar // INV-WS-STARTUP-RETRY-001: one exit decision consumes both proof // sources; the provider rechecks the claim generation below. out := workspaceRetryOutcome("assignment_timeout", h, p.ChunkStartupSuperseded(f.volumeID, gen)) - if out.code == exitWorkspaceRetry && h != nil { + if h != nil { // A typed MOVED or DELETED renewal refusal is permanent: 78 at once, - // never a restart loop to the unit's start limit. + // never a restart loop to the unit's start limit. It is the reason + // that ended the wait, so it names the exit even when a newer + // foreign line was also observed (superseded). if _, final := h.MasterWaitState(); final != "" { out = workspaceExit{code: exitWorkspaceSuperseded, reason: final} } diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 8e38ecfade..52aaa7e569 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -37,6 +37,10 @@ The volume's authority and health projection. Go type `volume.StatusProjection`. | `CatchUp.ElapsedMs` | int64 | ElapsedMs is the time since this replica was admitted as a supporting replica at its current epoch. | | `CatchUp.LagLSN` | uint64 | LagLSN is the engine's H-R (primary head minus this replica's durable frontier) as last observed; 0 when unknown or caught up. | | `Warnings[]` | string | Warnings include routing disagreements and typed recovery warnings (e.g. wal_hole_suspected, issue #51). Visible, not an alert: they do not change Healthy or the frontend's readiness. (omitted when empty) | +| `MasterWait` | object | MasterWait is why a workspace primary holds no granted lease, present only while NotReadyReason is lease_not_held: Reason (unreachable, credentials, barrier, no_assignment, refused, moved, deleted), since when, and the wait's bound or the master's barrier time (UntilMs, absent while there is no bound). (omitted when empty) | +| `MasterWait.Reason` | string | — | +| `MasterWait.SinceMs` | int64 | — | +| `MasterWait.UntilMs` | int64 | — (omitted when empty) | ### `GET /status/peers` From a614031c5c6bd07134c73c6f1f6b1f642ad16390 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 22:41:56 -0800 Subject: [PATCH 13/34] fix: MOVED needs a line at a newer epoch than the caller's A line naming another replica at the caller's epoch or below is OTHER, not MOVED: a false MOVED is exit 78, which the unit does not restart. Tests: the decision table, and a move away and back on the real master. Co-Authored-By: Claude Opus 5.5 --- .../workspace_lease_refusal_kind_test.go | 52 ++++++++++++++++--- .../core/host/master/workspace_service.go | 30 +++++++---- 2 files changed, 65 insertions(+), 17 deletions(-) diff --git a/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go b/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go index b3e10e63a9..3c9f7519dc 100644 --- a/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go +++ b/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go @@ -131,31 +131,69 @@ func TestLeaseRefusalKinds(t *testing.T) { t.Fatalf("moved to another host: %q detail %v; want MOVED with the unchanged text", text, r) } - // An admitted deletion is OTHER; a committed one is DELETED. + // Move back to node-a: the stale node-a process at e2 is the same owner at + // a newer epoch, so OTHER (no detail), never a false MOVED. if _, err := ws.RenewWorkspaceLease(ctx, e3); err != nil { - t.Fatal("grant to the moved replica:", err) + t.Fatal("grant to the moved host:", err) } - if _, err := ws.RevokeWorkspace(ctx, e3); err != nil { + e4 := id("node-a", cleanMove("move-back", e3, b)) + text, r = refusalOf(t, "moved and moved back", func() error { _, err := ws.RenewWorkspaceLease(ctx, e2); return err }()) + if r != nil || text != "workspace lease: server identity does not match the current holder" { + t.Fatalf("moved and moved back: %q detail %v; want the unchanged text, no detail", text, r) + } + + // An admitted deletion is OTHER; a committed one is DELETED. + if _, err := ws.RenewWorkspaceLease(ctx, e4); err != nil { + t.Fatal("grant after the move back:", err) + } + if _, err := ws.RevokeWorkspace(ctx, e4); err != nil { t.Fatal(err) } - headEpoch.Store(int64(e3.GetEpoch())) + headEpoch.Store(int64(e4.GetEpoch())) headGen.Add(1) - if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: e3, HeadGen: uint64(headGen.Load())}); err != nil { + if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: e4, HeadGen: uint64(headGen.Load())}); err != nil { t.Fatal(err) } res, err := control.NewLifecycleServiceClient(conn).MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-1"}) if err != nil || res.GetState() != lifecycle.ReservationAdmitted { t.Fatalf("admit the delete: %+v %v", res, err) } - text, r = refusalOf(t, "admitted deletion", func() error { _, err := ws.RenewWorkspaceLease(ctx, e3); return err }()) + text, r = refusalOf(t, "admitted deletion", func() error { _, err := ws.RenewWorkspaceLease(ctx, e4); return err }()) if r != nil || text != "workspace: volume is being deleted" { t.Fatalf("admitted deletion: %q detail %v; want the unchanged text, no detail", text, r) } if _, err := h.lifecycle.Deletions.Commit("v", "del-1"); err != nil { t.Fatal(err) } - text, r = refusalOf(t, "committed deletion", func() error { _, err := ws.RenewWorkspaceLease(ctx, e3); return err }()) + text, r = refusalOf(t, "committed deletion", func() error { _, err := ws.RenewWorkspaceLease(ctx, e4); return err }()) if r == nil || r.GetKind() != control.WorkspaceLeaseRefusal_DELETED || text != "workspace: volume is being deleted" { t.Fatalf("committed deletion: %q detail %v; want DELETED with the unchanged text", text, r) } } + +// MOVED needs a line at a newer epoch than the caller's: another replica or +// another known owner. A line at or below the caller's epoch, the same owner, +// an unknown owner or a caller without a server id is OTHER (F6). +func TestRenewalReplicaMismatchAtOlderLineEpochIsOther(t *testing.T) { + owner := func(s string) func() string { return func() string { return s } } + for _, c := range []struct { + name string + lineEpoch uint64 + lineReplica, lineHost string + server string + epoch uint64 + want bool + }{ + {"another replica at an older line epoch", 2, "r2", "node-b", "node-a", 3, false}, + {"another replica at the same epoch", 3, "r2", "node-b", "node-a", 3, false}, + {"another replica at a newer epoch", 4, "r2", "node-b", "node-a", 3, true}, + {"another known owner at a newer epoch", 4, "r1", "node-b", "node-a", 3, true}, + {"the same owner at a newer epoch (move and move back)", 4, "r1", "node-a", "node-a", 3, false}, + {"an unknown owner at a newer epoch", 4, "r1", "", "node-a", 3, false}, + {"no server id on the call", 4, "r1", "node-b", "", 3, false}, + } { + if got := lineMovedFrom(c.lineEpoch, c.lineReplica, owner(c.lineHost), "r1", c.server, c.epoch); got != c.want { + t.Errorf("%s: MOVED=%v; want %v", c.name, got, c.want) + } + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 5022645205..c33d83019a 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -69,22 +69,32 @@ func leaseRefusal(text string, kind control.WorkspaceLeaseRefusal_Kind, retryAft } // renewalMoved reports whether a holder mismatch is a permanent, known move: -// the published line names another replica, or a newer epoch of this replica -// owned by another known server. An unknown owner, the same owner at a newer -// epoch, or no line is not (OTHER: a bounded wait, then exit 75). +// the published line is at a newer epoch than the caller's and names another +// replica, or is owned by another known server. An unknown owner, the same +// owner at a newer epoch, a line at or below the caller's epoch, or no line is +// not (OTHER: a bounded wait, then exit 75): a false MOVED is exit 78, which +// the shipped unit does not restart. func (s *services) renewalMoved(volume, replica, server string, epoch uint64) bool { line, ok := s.host.Publisher().PublishedAuthorityLine(volume) - if !ok || server == "" { + if !ok { return false } - if line.ReplicaID != replica { + return lineMovedFrom(line.Epoch, line.ReplicaID, func() string { + return s.host.workspaceLineOwner(line, volume, line.ReplicaID, line.Epoch) + }, replica, server, epoch) +} + +// lineMovedFrom is renewalMoved's decision on the published line (epoch, +// replica, owner) against the caller (replica, server, epoch). +func lineMovedFrom(lineEpoch uint64, lineReplica string, owner func() string, replica, server string, epoch uint64) bool { + if server == "" || lineEpoch <= epoch { + return false + } + if lineReplica != replica { return true } - if line.Epoch <= epoch { - return false - } - owner := s.host.workspaceLineOwner(line, volume, line.ReplicaID, line.Epoch) - return owner != "" && owner != server + o := owner() + return o != "" && o != server } // isWorkspaceVolume reports whether volume is a workspace volume (workspace RPC on, an existing RF1 volume), from the From 9a303f6ec99abdd319d584bfa6645c7291be7f01 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 22:41:57 -0800 Subject: [PATCH 14/34] fix: one barrier time, woken past it with jitter; retry from admission's clocks The guard reads the host's barrier time (one copy) and wakes 100 ms past it plus up to 500 ms of jitter, capped at 2 min; its 1 s pre-grant poll is jittered by 20 %. The master's retry_after uses the same two predicates as admission: lease expiry plus skew (wall) and the grant deadline plus skew (its monotonic clock), each measured from now. Co-Authored-By: Claude Opus 5.5 --- .../core/authority/workspace_lease_view.go | 11 +++- seaweed-block/core/host/volume/master_wait.go | 8 +++ .../core/host/volume/master_wait_test.go | 28 +++++---- .../core/host/volume/workspace_lease.go | 59 +++++++++++++------ .../core/host/volume/workspace_runtime.go | 2 +- 5 files changed, 75 insertions(+), 33 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index 617b93e927..92577cc553 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -374,10 +374,15 @@ func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder st if p.store == nil || p.workspaceUncertain[volume] { return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain") } - lostUntil, now, err := p.forcedMoveBarrierLocked(volume, s.Lease) + _, now, err := p.forcedMoveBarrierLocked(volume, s.Lease) if err != nil { - until := time.Unix(0, lostUntil) - return WorkspaceLease{}, &LeaseBarrierError{Until: until, RetryAfter: max(until.Sub(now), 0), err: err} + // The same two predicates as admission: lease expiry plus skew (wall + // time, persisted) and the grant deadline plus skew (this process's + // monotonic clock), each measured from now. A client adds the result + // to its own request start; it never compares clocks. + skew := p.workspaceSkew(s.Lease) + retry := max(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew).Sub(now), p.leaseDeadlineLocked(volume).Add(skew).Sub(now), 0) + return WorkspaceLease{}, &LeaseBarrierError{Until: now.Add(retry), RetryAfter: retry, err: err} } lease, grant := p.newWorkspaceLease(holder, epoch, now) lease.ExpiresAtNS = max(lease.ExpiresAtNS, s.Lease.ExpiresAtNS) diff --git a/seaweed-block/core/host/volume/master_wait.go b/seaweed-block/core/host/volume/master_wait.go index 61f6fc9999..681649bba0 100644 --- a/seaweed-block/core/host/volume/master_wait.go +++ b/seaweed-block/core/host/volume/master_wait.go @@ -216,3 +216,11 @@ func (h *Host) MasterWaitStatus() *MasterWait { w := h.mw.snapshot(h.realAdpt.Projection().Epoch > 0) return &w } + +// barrierTime is the master's barrier time T from the latest BARRIER refusal +// (zero when none): the lease guard sleeps until just past it. +func (w *masterWait) barrierTime() time.Time { + w.mu.Lock() + defer w.mu.Unlock() + return w.barrier +} diff --git a/seaweed-block/core/host/volume/master_wait_test.go b/seaweed-block/core/host/volume/master_wait_test.go index ced1c0af6a..f18d3c3394 100644 --- a/seaweed-block/core/host/volume/master_wait_test.go +++ b/seaweed-block/core/host/volume/master_wait_test.go @@ -120,27 +120,33 @@ func TestLeaseGuardSleepsUntilTheBarrier(t *testing.T) { if err != nil { t.Fatal(err) } + w := newMasterWait(func() time.Time { return now }, func(string, ...any) {}) var observed int - g.observe = func(time.Time, error) { observed++ } + g.observe = func(start time.Time, err error) { observed++; w.renewal(start, err) } + g.barrierAt = w.barrierTime + in := func(what string, d, lo, hi time.Duration) { + t.Helper() + if d < lo || d > hi { + t.Fatalf("%s: delay %v; want within [%v, %v]", what, d, lo, hi) + } + } reply = status.Error(codes.FailedPrecondition, "workspace forced move lease expiry plus clock-skew margin has not elapsed") _ = g.Refresh(context.Background()) - if d := g.renewDelay(); d != time.Second { - t.Fatalf("delay after a detail-less refusal %v; want the 1 s poll, as today", d) + for i := 0; i < 20; i++ { + in("detail-less refusal: the 1 s poll, jittered", g.renewDelay(), 800*time.Millisecond, 1200*time.Millisecond) } reply = refusalWith(t, "barrier", control.WorkspaceLeaseRefusal_BARRIER, 40*time.Second) _ = g.Refresh(context.Background()) - if d := g.renewDelay(); d != 40*time.Second { - t.Fatalf("delay after BARRIER %v; want until T (40 s)", d) + for i := 0; i < 20; i++ { + in("after BARRIER: until just past T", g.renewDelay(), 40*time.Second+100*time.Millisecond, 40*time.Second+600*time.Millisecond) } now = now.Add(39 * time.Second) - if d := g.renewDelay(); d != time.Second { - t.Fatalf("delay 1 s before T: %v", d) - } + in("1 s before T", g.renewDelay(), 1100*time.Millisecond, 1600*time.Millisecond) now = now.Add(2 * time.Second) - if d := g.renewDelay(); d != time.Second { - t.Fatalf("delay past T %v; want the 1 s poll", d) - } + in("past T: the 1 s poll", g.renewDelay(), 800*time.Millisecond, 1200*time.Millisecond) + w.renewal(now, refusalWith(t, "barrier", control.WorkspaceLeaseRefusal_BARRIER, time.Hour)) + in("a far barrier: capped", g.renewDelay(), 2*time.Minute, 2*time.Minute) if observed != 2 { t.Fatalf("renewals observed %d; want 2", observed) } diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index d751b6ff94..a26359a146 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "log" + "math/rand/v2" "sync" "time" @@ -52,10 +53,10 @@ type WorkspaceLeaseGuard struct { // after schedules Run's sleep between renewals (time.After; tests // replace it before Run starts to observe the delays chosen). after func(time.Duration) <-chan time.Time - // barrier is the master's barrier time T from the latest BARRIER refusal - // (request start + retry_after, under mu): before the first grant Run - // sleeps until T instead of polling every second. - barrier time.Time + // barrierAt, when set, returns the master's barrier time T (the host's + // master wait keeps the one copy): before the first grant Run sleeps until + // just past T instead of polling every second. Set before Run. + barrierAt func() time.Time // observe, when set, receives every renewal's start and result (the // host's master wait). Set before Run; never called with mu held. observe func(time.Time, error) @@ -105,17 +106,23 @@ func (g *WorkspaceLeaseGuard) renewDelay() time.Duration { g.mu.Lock() now := g.now() delay := g.until.Sub(now) / 3 - if g.until.IsZero() { - delay = time.Second - } - barrier := g.until.IsZero() && g.barrier.After(now) - if barrier { - delay = g.barrier.Sub(now) // the master refuses every call before T - } + pregrant := g.until.IsZero() pending := g.stopPending g.mu.Unlock() - if barrier && !pending { - return delay + if pregrant { + // Before the first grant: poll about once a second, jittered so the + // volumes of one host do not stay in step; while the master has said + // it refuses until T, sleep until just past T (it refuses every call + // before; the request's own latency would otherwise land it early). + delay = jittered(time.Second, time.Second/5) + if g.barrierAt != nil { + if t := g.barrierAt(); t.After(now) { + delay = min(t.Sub(now)+barrierWakeMargin+jittered(0, barrierWakeJitter), barrierSleepCap) + } + } + if !pending { + return delay + } } if delay < 50*time.Millisecond { delay = 50 * time.Millisecond @@ -226,11 +233,6 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { if g.observe != nil && ctx.Err() == nil { g.observe(start, err) } - if r := leaseRefusalDetail(err); r != nil && r.GetKind() == control.WorkspaceLeaseRefusal_BARRIER { - g.mu.Lock() - g.barrier = start.Add(time.Duration(r.GetRetryAfterNs())) - g.mu.Unlock() - } if err != nil { end := g.now() elapsed := end.Sub(start).Round(time.Millisecond) @@ -307,6 +309,27 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { return nil } +// Before the first grant: after the master's barrier time the guard wakes +// barrierWakeMargin plus up to barrierWakeJitter later (every volume a master +// restart lapsed gets the same T); one sleep is at most barrierSleepCap. +const ( + barrierWakeMargin = 100 * time.Millisecond + barrierWakeJitter = 500 * time.Millisecond + barrierSleepCap = 2 * time.Minute +) + +// jittered returns base plus a uniform offset in [-spread, +spread) (only +// [0, spread) when base is zero). +func jittered(base, spread time.Duration) time.Duration { + if spread <= 0 { + return base + } + if base == 0 { + return rand.N(spread) + } + return base - spread + rand.N(2*spread) +} + // renewalRPCTimeout bounds one renewal call; the lease deadline may bound it // sooner (Refresh). const renewalRPCTimeout = 2 * time.Second diff --git a/seaweed-block/core/host/volume/workspace_runtime.go b/seaweed-block/core/host/volume/workspace_runtime.go index 9a27b9aac2..b5eda6f0c5 100644 --- a/seaweed-block/core/host/volume/workspace_runtime.go +++ b/seaweed-block/core/host/volume/workspace_runtime.go @@ -37,7 +37,7 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context, if err != nil { return err } - guard.observe = h.mw.renewal + guard.observe, guard.barrierAt = h.mw.renewal, h.mw.barrierTime if beforeInstall != nil { beforeInstall() } From e56fe3b9b89d254f0a73d11ed150b994df11461e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 22:42:58 -0800 Subject: [PATCH 15/34] fix: log the master wait's reason from the heartbeat loop; flapping note The reason line and its 10-minute repeat no longer depend on someone reading /status. A flapping master postpones the bound and never ends the wait early: tested and noted under INV-WS-MASTER-WAIT-001. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/volume/host.go | 3 + .../core/host/volume/master_wait_test.go | 82 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 1 + 3 files changed, 86 insertions(+) diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index eb8cdc3361..9b976d4e49 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -626,6 +626,9 @@ func (h *Host) runHeartbeat(ctx context.Context) { _, err := h.obsCli.ReportHeartbeat(rpcCtx, h.buildReport()) if ctx.Err() == nil { h.mw.call(err) + // The wait's reason reaches the journal on a change and every + // 10 min from here, whether or not anyone reads /status. + _ = h.MasterWaitStatus() } if err != nil { h.log.Printf("blockvolume: heartbeat: %v", err) diff --git a/seaweed-block/core/host/volume/master_wait_test.go b/seaweed-block/core/host/volume/master_wait_test.go index f18d3c3394..20d27cb460 100644 --- a/seaweed-block/core/host/volume/master_wait_test.go +++ b/seaweed-block/core/host/volume/master_wait_test.go @@ -3,6 +3,10 @@ package volume import ( "context" "errors" + "fmt" + "log" + "strings" + "sync" "testing" "time" @@ -190,3 +194,81 @@ func TestStatusShowsTheMasterWait(t *testing.T) { t.Fatalf("MasterWait %+v shown without a lease wait", got.MasterWait) } } + +// Refused credentials for an hour: no bound, reason credentials, and the log +// line at the start and every 10 min, driven by the heartbeat cadence alone +// (no /status read) (F1). +func TestCredentialsRefusedForAnHourWaitsAndLogs(t *testing.T) { + now := time.Unix(1_800_000_000, 0) + var lines []string + w := newMasterWait(func() time.Time { return now }, func(f string, a ...any) { lines = append(lines, fmt.Sprintf(f, a...)) }) + denied := status.Error(codes.PermissionDenied, "node certificate revoked") + for i := 0; i < 1800; i++ { // one heartbeat every 2 s for 60 min + w.call(denied) + _ = w.snapshot(true) + now = now.Add(2 * time.Second) + } + if d, final := w.state(); !d.IsZero() || final != "" { + t.Fatalf("after an hour of refused credentials: bound %v final %q; want none", d, final) + } + if len(lines) != 6 { + t.Fatalf("%d log lines in 60 min; want 6 (at 0 and every 10 min): %q", len(lines), lines) + } + for _, l := range lines { + if !strings.Contains(l, "waiting for the master: credentials since") || !strings.Contains(l, "(no bound)") { + t.Fatalf("log line %q; want the credentials reason without a bound", l) + } + } +} + +// The heartbeat loop itself logs the wait's reason: a workspace host whose +// master is unreachable states it with no /status read (F1 wiring). +func TestHeartbeatLogsTheMasterWait(t *testing.T) { + var buf safeBuffer + h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "s1", VolumeID: "v1", ReplicaID: "r1", + DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304", WorkspaceLease: true, + HeartbeatInterval: 20 * time.Millisecond, Logger: log.New(&buf, "", 0)}) + if err != nil { + t.Fatal(err) + } + h.Start() + t.Cleanup(func() { _ = h.Close() }) + deadline := time.Now().Add(10 * time.Second) + for !strings.Contains(buf.String(), "waiting for the master: unreachable since") { + if time.Now().After(deadline) { + t.Fatalf("no wait reason logged from the heartbeat loop; log:\n%s", buf.String()) + } + time.Sleep(20 * time.Millisecond) + } +} + +type safeBuffer struct { + mu sync.Mutex + b strings.Builder +} + +func (s *safeBuffer) Write(p []byte) (int, error) { s.mu.Lock(); defer s.mu.Unlock(); return s.b.Write(p) } +func (s *safeBuffer) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() } + +// A flapping master (an answer, then no reply, every 10 s for 10 min) never +// ends the wait early: each answer starts a new streak, so the bound is never +// before the latest contact + 30 s. It postpones the bound for as long as the +// flapping lasts, also for an obsolete unit (documented: F7). +func TestFlappingMasterNeverExpiresEarly(t *testing.T) { + now := time.Unix(1_800_000_000, 0) + w := newMasterWait(func() time.Time { return now }, func(string, ...any) {}) + var lastContact time.Time + for i := 0; i < 60; i++ { + if i%2 == 0 { + w.call(nil) + lastContact = now + } else { + w.call(status.Error(codes.Unavailable, "flap")) + } + d, _ := w.state() + if !d.IsZero() && (d.Before(lastContact.Add(MasterWaitLimit)) || !now.Before(d)) { + t.Fatalf("step %d: bound %v ends the wait early (latest contact %v, now %v)", i, d, lastContact, now) + } + now = now.Add(10 * time.Second) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9e21840ce7..0c734aa40e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -777,6 +777,7 @@ Notes: | `INV-WS-MASTER-WAIT-001` | A workspace primary's startup wait has no bound while blockmaster gives no reply or refuses its credentials; once it answers, the wait ends 30 s after max(contact streak start, the master's barrier time), and a typed MOVED or DELETED lease refusal ends it at once with 78. | M2 Awaiting assignment → Process exited | `core/host/volume/master_wait.go` `masterWait` (contact from heartbeat, stream and renewal results; the refusal kind from the status detail only); `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` (`ChunkMasterWait`); `cmd/blockvolume/process_exit.go` `chooseChunkStartupExit`; `core/host/master/workspace_service.go` `leaseRefusal`, `renewalMoved`; `core/authority/workspace_lease_view.go` `LeaseBarrierError`; `core/host/volume/workspace_lease.go` `renewDelay` (sleeps until the barrier time); `core/rpc/link/link.go` `MasterReconnect` | `TestChunkAuthorityWaitStartsAtFirstContact`, `TestLeaseGuardSleepsUntilTheBarrier`, `TestStatusShowsTheMasterWait` (`core/host/volume/master_wait_test.go`); `TestMasterLinkReconnectsWithinTwoSeconds` (`core/host/volume/master_reconnect_test.go`); `TestChunkAuthorityWaitFollowsTheMasterWait` (`core/frontend/durable/provider_master_wait_test.go`); `TestLeaseRefusalKinds` (`core/host/master/workspace_lease_refusal_kind_test.go`) | — | ACTIVE | - `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process. +- `INV-WS-MASTER-WAIT-001`: every reply produced by blockmaster's handler starts or continues a contact streak; a transport failure (`Unavailable`, `DeadlineExceeded`, `Canceled`) ends it. So a master that answers and drops in turn postpones the 30 s bound for as long as it flaps, also for an obsolete unit; it never ends the wait early (`TestFlappingMasterNeverExpiresEarly`). The barrier time travels as a duration the master computes from the same two predicates as admission, added by the volume to its own monotonic request start; the master re-checks the barrier on every re-grant, so a wrong duration only moves the 75 exit. The status codes alone still mean retry 75 (`INV-WS-STARTUP-RETRY-001`); only the typed `WorkspaceLeaseRefusal` detail (MOVED, DELETED) permits the early 78. - Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages`, `TestWorkspaceExitLineageIncludesBlockedOwnAssignment`, and `TestWorkspaceObservedLineageNeverTrailsAdoption` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal. - Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with a foreign master line newer than nonzero observed-own; absent proof means retry 75. - Part T fence ownership: `Host.FenceWorkspaceLease` uses `WorkspaceLeaseGuard.fenceLocked`, including before runtime publication; the zero-validity terminal guard preserves the first cause through installation and can grant no I/O. No second host fence latch exists. `TestWorkspaceHostFencePublishesOneTerminalCause`, `TestWorkspaceInstalledHostFenceRecordsCause`, `TestWorkspaceFenceBeforeHeldInstallIsTerminal` (`core/host/volume/workspace_terminal_test.go`). From f77a75c58efe1fdb5eec717be4e86d2bc519144e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 22:43:55 -0800 Subject: [PATCH 16/34] test: a typed moved/deleted refusal gives 78 with its reason; none stays 75 Co-Authored-By: Claude Opus 5.5 --- .../process_exit_authority_test.go | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index 44cbe8bece..7c9f841c27 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -10,6 +10,8 @@ import ( control "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/storage" "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "net" "sync/atomic" "testing" @@ -21,12 +23,16 @@ type exitAssignmentStream struct { control.UnimplementedObservationServiceServer control.UnimplementedWorkspaceServiceServer revoke bool + refuse error // when set, every renewal is refused with it ackError error acks atomic.Int32 facts chan *control.AssignmentFact } func (s *exitAssignmentStream) RenewWorkspaceLease(_ context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) { + if s.refuse != nil { + return nil, s.refuse + } return &control.WorkspaceLeaseFact{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch, ValidForNs: int64(30 * time.Second), Revoking: s.revoke}, nil } func (s *exitAssignmentStream) AckWorkspaceRevoked(_ context.Context, a *control.WorkspaceRevocationAck) (*control.WorkspaceEmpty, error) { @@ -490,3 +496,64 @@ func TestWorkspaceDisplacedClaimUsesAssignedEpoch(t *testing.T) { }) } } + +// A typed MOVED or DELETED renewal refusal, seen by the real host's guard, +// turns the startup outcome into 78 with that reason; a refusal without the +// detail stays 75 assignment_timeout. +func TestChunkStartupExitFinalGives78(t *testing.T) { + refusal := func(kind control.WorkspaceLeaseRefusal_Kind) error { + st, err := status.New(codes.FailedPrecondition, "workspace lease: server identity does not match the current holder"). + WithDetails(&control.WorkspaceLeaseRefusal{Kind: kind}) + if err != nil { + t.Fatal(err) + } + return st.Err() + } + for _, tc := range []struct { + name string + refuse error + code int + reason string + }{ + {"moved", refusal(control.WorkspaceLeaseRefusal_MOVED), exitWorkspaceSuperseded, "moved"}, + {"deleted", refusal(control.WorkspaceLeaseRefusal_DELETED), exitWorkspaceSuperseded, "deleted"}, + {"no detail", status.Error(codes.FailedPrecondition, "workspace lease: server identity does not match the current holder"), exitWorkspaceRetry, "assignment_timeout"}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + h, assign := exitAuthorityHost(t, func(s *exitAssignmentStream) { s.refuse = tc.refuse }) + assign("r", 1) + leaseCtx, stopLease := context.WithCancel(ctx) + done := make(chan error, 1) + go func() { + done <- h.RunWorkspaceLease(leaseCtx, func(context.Context, *control.WorkspaceIdentity) (uint64, error) { return 1, nil }) + }() + t.Cleanup(func() { stopLease(); <-done }) + if tc.reason == "assignment_timeout" { + time.Sleep(2 * time.Second) // a renewal or two, refused without a detail + if _, final := h.MasterWaitState(); final != "" { + t.Fatalf("a refusal without a detail was taken as final %q", final) + } + } + for tc.reason != "assignment_timeout" { + if _, final := h.MasterWaitState(); final != "" { + break + } + select { + case <-ctx.Done(): + t.Fatal("the guard's refusal never reached the host") + case <-time.After(20 * time.Millisecond): + } + } + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, &exitStartupOutcome{expired: true}) { + t.Fatal("the startup outcome selected no exit") + } + out := <-e.decision + if out.code != tc.code || out.reason != tc.reason { + t.Fatalf("exit %+v; want %d %s", out, tc.code, tc.reason) + } + }) + } +} From c49134bc00a434f9a76b348adc72d1ebeefc5bcb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 22:44:59 -0800 Subject: [PATCH 17/34] test: a committed delete during the wait exits 78 deleted; admitted stays 75 Co-Authored-By: Claude Opus 5.5 --- .../master_wait_integration_test.go | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/master_wait_integration_test.go b/seaweed-block/cmd/blockvolume/master_wait_integration_test.go index e2c9f7b738..2c996f0d01 100644 --- a/seaweed-block/cmd/blockvolume/master_wait_integration_test.go +++ b/seaweed-block/cmd/blockvolume/master_wait_integration_test.go @@ -3,12 +3,18 @@ package main_test import ( + "context" "encoding/json" + "fmt" "io" "net/http" "syscall" "testing" "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" ) type masterWaitView struct { @@ -184,3 +190,73 @@ func TestObsoleteUnitStopsWithReachableMaster(t *testing.T) { t.Fatalf("obsolete unit exit %v after %v; want 75 assignment_timeout after the 30 s bound", err, took) } } + +// revokeAndExit seals v1 on s1, revokes it at e and waits for the holder's +// clean exit and recorded ACK: the volume is then admissible for delete. +func revokeAndExit(t *testing.T, env *handoffEnv, holder *daemon, e uint64) { + t.Helper() + b := env.hosts["s1"] + out, _ := env.h.command(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", b.status, "--timeout", "120s") + var a struct { + HeadGen uint64 `json:"headGen"` + } + if err := json.Unmarshal([]byte(out), &a); err != nil || a.HeadGen == 0 { + t.Fatalf("plain detach: %v %q", err, out) + } + env.h.command(t, "ops", "workspace", "revoke", "--master", env.h.masterAddr, "--volume", "v1", "--replica", "r1", + "--epoch", fmt.Sprint(e), "--sealed-gen", fmt.Sprint(a.HeadGen)) + if err := holder.wait(30 * time.Second); err != nil { + t.Fatalf("holder after the revocation: %v; want a clean exit", err) + } + poll(t, 30*time.Second, "the ACK was never recorded", func() bool { + out, _ := env.h.command(t, "ops", "workspace", "show", "--master", env.h.masterAddr, "--volume", "v1") + return showsAck(out, e, a.HeadGen) + }) +} + +// A process waiting on its cached assignment while the volume's delete is +// committed exits 78 deleted at once (the master's typed DELETED refusal); +// while the delete is only admitted (abortable) it keeps the bounded wait and +// exits 75 assignment_timeout, never 78. +func TestWaitingVolumeDeletedDuringOutageExits78(t *testing.T) { + t.Run("committed", func(t *testing.T) { + env := startHandoffEnv(t, 1) + holder := env.start(t, "bv-del-holder", "s1") + e := env.adopt(t, holder, "s1") + revokeAndExit(t, env, holder, e) + waiting := env.start(t, "bv-del-waiting", "s1") + waiting.waitLog(t, 30*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@") + out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, + "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-while-waiting") + var del struct{ Completed bool } + if code != 0 || json.Unmarshal([]byte(out), &del) != nil || !del.Completed { + t.Fatalf("volume-delete while a process waits: exit %d %s %s; want completed", code, out, errOut) + } + err := waiting.wait(30 * time.Second) + if exitCode(err) != 78 || !waiting.has("blockvolume: exiting status=78 reason=deleted") { + t.Fatalf("waiting process after the committed delete: %v; want 78 reason=deleted", err) + } + }) + t.Run("admitted", func(t *testing.T) { + env := startHandoffEnv(t, 1) + holder := env.start(t, "bv-adm-holder", "s1") + e := env.adopt(t, holder, "s1") + revokeAndExit(t, env, holder, e) + conn, err := grpc.NewClient(env.h.masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := control.NewLifecycleServiceClient(conn).MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v1", Token: "admit-only"}); err != nil { + t.Fatal("admit the delete:", err) + } + at := time.Now() + waiting := env.start(t, "bv-adm-waiting", "s1") + err = waiting.wait(2 * time.Minute) + if exitCode(err) != 75 || !waiting.has("reason=assignment_timeout") || time.Since(at) < 25*time.Second { + t.Fatalf("waiting process under an admitted delete: %v after %v; want the bounded 75 assignment_timeout", err, time.Since(at)) + } + }) +} From 1be0e6419c202eccf5964ba266cec67acd44ca4e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 22:46:14 -0800 Subject: [PATCH 18/34] test: 20 volumes serve within 2 s of their barrier after a master restart Gated by SWB_MANY_VOLUMES=1 (twenty volume processes). Co-Authored-By: Claude Opus 5.5 --- .../master_wait_integration_test.go | 89 ++++++++++++++++++- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/master_wait_integration_test.go b/seaweed-block/cmd/blockvolume/master_wait_integration_test.go index 2c996f0d01..b787a26131 100644 --- a/seaweed-block/cmd/blockvolume/master_wait_integration_test.go +++ b/seaweed-block/cmd/blockvolume/master_wait_integration_test.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "net/http" + "os" "syscall" "testing" "time" @@ -24,9 +25,12 @@ type masterWaitView struct { } // masterWaitOf reads /status MasterWait for v1 (ok false when absent). -func masterWaitOf(statusAddr string) (masterWaitView, bool) { +func masterWaitOf(statusAddr string) (masterWaitView, bool) { return masterWaitOfVolume(statusAddr, "v1") } + +// masterWaitOfVolume reads /status MasterWait for vol. +func masterWaitOfVolume(statusAddr, vol string) (masterWaitView, bool) { c := &http.Client{Timeout: 2 * time.Second} - resp, err := c.Get("http://" + statusAddr + "/status?volume=v1") + resp, err := c.Get("http://" + statusAddr + "/status?volume=" + vol) if err != nil { return masterWaitView{}, false } @@ -260,3 +264,84 @@ func TestWaitingVolumeDeletedDuringOutageExits78(t *testing.T) { } }) } + +// After a master restart every lapsed volume gets the same barrier time; with +// 20 volume processes (one per volume) waiting, each must serve within 2 s of +// its barrier: the guards' jittered wake and the publisher's busy refusals +// must not keep them in step. Twenty processes: run only when +// SWB_MANY_VOLUMES=1 (not in every CI pass). +func TestManyVolumesServeTogetherAfterMasterRestart(t *testing.T) { + if os.Getenv("SWB_MANY_VOLUMES") != "1" { + t.Skip("20 volume processes: set SWB_MANY_VOLUMES=1") + } + const n = 20 + var targets []string + for i := 2; i <= n; i++ { + targets = append(targets, fmt.Sprintf("v%d", i)) + } + env := startHandoffEnvWith(t, 1, targets) + hosts := []bvHost{env.hosts["s1"]} + hosts[0].volume = "v1" + for _, v := range targets { + hosts = append(hosts, env.hosts["n-"+v]) + } + start := func(round string) []*daemon { + ds := make([]*daemon, len(hosts)) + for i, b := range hosts { + ds[i] = env.h.start(t, fmt.Sprintf("bv-%s-%s", round, b.volume), env.h.volume, env.volArgsFor(b)...) + } + return ds + } + first := start("first") + for _, b := range hosts { + poll(t, 3*time.Minute, b.volume+" never served", func() bool { return volumeFrontendReady(b.status, b.volume) }) + } + env.masterProcess.kill(t) + for i, d := range first { + if code := exitCode(d.wait(90 * time.Second)); code != 75 { + t.Fatalf("%s holder exited %v with the master down; want 75", hosts[i].volume, d.err) + } + } + waiting := start("waiting") + time.Sleep(10 * time.Second) + env.masterProcess = env.h.start(t, "blockmaster-back", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + + until := make([]time.Time, len(hosts)) + served := make([]time.Time, len(hosts)) + deadline := time.Now().Add(3 * time.Minute) + for left := len(hosts); left > 0; time.Sleep(100 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatalf("%d of %d volumes never served after the master returned", left, len(hosts)) + } + for i, b := range hosts { + if !served[i].IsZero() { + continue + } + if until[i].IsZero() { + if mw, ok := masterWaitOfVolume(b.status, b.volume); ok && mw.Reason == "barrier" { + until[i] = mw.Until + } + } + if volumeFrontendReady(b.status, b.volume) { + served[i] = time.Now() + left-- + } + } + } + var worst time.Duration + for i, b := range hosts { + stillRunning(t, waiting[i], b.volume) + if until[i].IsZero() { + t.Errorf("%s served without /status ever showing the barrier", b.volume) + continue + } + late := served[i].Sub(until[i]) + t.Logf("%s served %v after its barrier", b.volume, late.Round(time.Millisecond)) + worst = max(worst, late) + } + t.Logf("%d volumes: worst %v after the barrier", len(hosts), worst.Round(time.Millisecond)) + if worst > 2*time.Second { + t.Fatalf("a volume served %v after its barrier; want every one within 2 s", worst.Round(time.Millisecond)) + } +} From c9d4cb02078f62c748c79cbb8c29aa5ef8d269ff Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 23:18:01 -0800 Subject: [PATCH 19/34] fix: poll fast just past the barrier; tests: per-volume watchers, delete via a cut proxy For 5 s after the master's barrier time the pre-grant poll is 200 ms (jittered): every lapsed volume re-grants at once, and the ones that find the publisher busy retry soon instead of a second later (20 volumes: worst 2.2 s after the barrier with the 1 s poll). Co-Authored-By: Claude Opus 5.5 --- .../master_wait_integration_test.go | 149 +++++++++++++++--- .../core/host/volume/master_wait_test.go | 4 +- .../core/host/volume/workspace_lease.go | 8 + 3 files changed, 137 insertions(+), 24 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/master_wait_integration_test.go b/seaweed-block/cmd/blockvolume/master_wait_integration_test.go index b787a26131..fda2ab5f3a 100644 --- a/seaweed-block/cmd/blockvolume/master_wait_integration_test.go +++ b/seaweed-block/cmd/blockvolume/master_wait_integration_test.go @@ -7,8 +7,10 @@ import ( "encoding/json" "fmt" "io" + "net" "net/http" "os" + "sync" "syscall" "testing" "time" @@ -197,9 +199,9 @@ func TestObsoleteUnitStopsWithReachableMaster(t *testing.T) { // revokeAndExit seals v1 on s1, revokes it at e and waits for the holder's // clean exit and recorded ACK: the volume is then admissible for delete. -func revokeAndExit(t *testing.T, env *handoffEnv, holder *daemon, e uint64) { +func revokeAndExit(t *testing.T, env *handoffEnv, hostID string, holder *daemon, e uint64) { t.Helper() - b := env.hosts["s1"] + b := env.hosts[hostID] out, _ := env.h.command(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", b.status, "--timeout", "120s") var a struct { HeadGen uint64 `json:"headGen"` @@ -224,19 +226,42 @@ func revokeAndExit(t *testing.T, env *handoffEnv, holder *daemon, e uint64) { // exits 75 assignment_timeout, never 78. func TestWaitingVolumeDeletedDuringOutageExits78(t *testing.T) { t.Run("committed", func(t *testing.T) { - env := startHandoffEnv(t, 1) + // The waiting s1 process reaches the master through a proxy the test + // cuts: while it cannot reach the master (no bound), the line moves to + // s2, s2 is revoked with an ACK and the delete commits. When the + // proxy returns, the renewal at its cached epoch meets the committed + // deletion. + env := startHandoffEnv(t, 2) holder := env.start(t, "bv-del-holder", "s1") e := env.adopt(t, holder, "s1") - revokeAndExit(t, env, holder, e) - waiting := env.start(t, "bv-del-waiting", "s1") - waiting.waitLog(t, 30*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@") + holder.kill(t) + px := startMasterProxy(t, env.h.masterAddr) + args := env.volArgs("s1") + for i := range args { + if args[i] == "--master" { + args[i+1] = px.addr + } + } + time.Sleep(35 * time.Second) // the lease lapsed; the barrier has not passed + waiting := env.h.start(t, "bv-del-waiting", env.h.volume, args...) + poll(t, 30*time.Second, "/status never showed the barrier", func() bool { + mw, ok := masterWaitOf(env.hosts["s1"].status) + return ok && mw.Reason == "barrier" + }) + px.cut() + env.forceMove(t, e, "s2", "force-before-delete") + s2 := env.start(t, "bv-del-s2", "s2") + e2 := env.adopt(t, s2, "s2") + revokeAndExit(t, env, "s2", s2, e2) out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-while-waiting") var del struct{ Completed bool } if code != 0 || json.Unmarshal([]byte(out), &del) != nil || !del.Completed { t.Fatalf("volume-delete while a process waits: exit %d %s %s; want completed", code, out, errOut) } - err := waiting.wait(30 * time.Second) + stillRunning(t, waiting, "while the master was unreachable") + px.restore() + err := waiting.wait(60 * time.Second) if exitCode(err) != 78 || !waiting.has("blockvolume: exiting status=78 reason=deleted") { t.Fatalf("waiting process after the committed delete: %v; want 78 reason=deleted", err) } @@ -245,7 +270,7 @@ func TestWaitingVolumeDeletedDuringOutageExits78(t *testing.T) { env := startHandoffEnv(t, 1) holder := env.start(t, "bv-adm-holder", "s1") e := env.adopt(t, holder, "s1") - revokeAndExit(t, env, holder, e) + revokeAndExit(t, env, "s1", holder, e) conn, err := grpc.NewClient(env.h.masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { t.Fatal(err) @@ -307,26 +332,34 @@ func TestManyVolumesServeTogetherAfterMasterRestart(t *testing.T) { env.masterProcess = env.h.start(t, "blockmaster-back", env.h.master, env.masterArgs...) env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + // One watcher per volume, every 50 ms: its barrier time from /status, + // then the moment it serves. until := make([]time.Time, len(hosts)) served := make([]time.Time, len(hosts)) + var wg sync.WaitGroup deadline := time.Now().Add(3 * time.Minute) - for left := len(hosts); left > 0; time.Sleep(100 * time.Millisecond) { - if time.Now().After(deadline) { - t.Fatalf("%d of %d volumes never served after the master returned", left, len(hosts)) - } - for i, b := range hosts { - if !served[i].IsZero() { - continue - } - if until[i].IsZero() { - if mw, ok := masterWaitOfVolume(b.status, b.volume); ok && mw.Reason == "barrier" { - until[i] = mw.Until + for i, b := range hosts { + wg.Add(1) + go func() { + defer wg.Done() + for time.Now().Before(deadline) { + if until[i].IsZero() { + if mw, ok := masterWaitOfVolume(b.status, b.volume); ok && mw.Reason == "barrier" { + until[i] = mw.Until + } } + if volumeFrontendReady(b.status, b.volume) { + served[i] = time.Now() + return + } + time.Sleep(50 * time.Millisecond) } - if volumeFrontendReady(b.status, b.volume) { - served[i] = time.Now() - left-- - } + }() + } + wg.Wait() + for i, b := range hosts { + if served[i].IsZero() { + t.Fatalf("%s never served after the master returned", b.volume) } } var worst time.Duration @@ -345,3 +378,73 @@ func TestManyVolumesServeTogetherAfterMasterRestart(t *testing.T) { t.Fatalf("a volume served %v after its barrier; want every one within 2 s", worst.Round(time.Millisecond)) } } + +// masterProxy forwards TCP connections to the master; cut closes its +// listener and every open connection (the master is unreachable through it), +// restore listens again on the same address. +type masterProxy struct { + t *testing.T + addr string + target string + mu sync.Mutex + ln net.Listener + conns []net.Conn +} + +func startMasterProxy(t *testing.T, target string) *masterProxy { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + p := &masterProxy{t: t, addr: ln.Addr().String(), target: target} + p.serve(ln) + t.Cleanup(p.cut) + return p +} + +func (p *masterProxy) serve(ln net.Listener) { + p.mu.Lock() + p.ln = ln + p.mu.Unlock() + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + up, err := net.Dial("tcp", p.target) + if err != nil { + _ = c.Close() + continue + } + p.mu.Lock() + p.conns = append(p.conns, c, up) + p.mu.Unlock() + go func() { _, _ = io.Copy(up, c); _ = up.Close() }() + go func() { _, _ = io.Copy(c, up); _ = c.Close() }() + } + }() +} + +func (p *masterProxy) cut() { + p.mu.Lock() + defer p.mu.Unlock() + if p.ln != nil { + _ = p.ln.Close() + p.ln = nil + } + for _, c := range p.conns { + _ = c.Close() + } + p.conns = nil +} + +func (p *masterProxy) restore() { + p.t.Helper() + ln, err := net.Listen("tcp", p.addr) + if err != nil { + p.t.Fatalf("proxy relisten %s: %v", p.addr, err) + } + p.serve(ln) +} diff --git a/seaweed-block/core/host/volume/master_wait_test.go b/seaweed-block/core/host/volume/master_wait_test.go index 20d27cb460..da5e1c8914 100644 --- a/seaweed-block/core/host/volume/master_wait_test.go +++ b/seaweed-block/core/host/volume/master_wait_test.go @@ -148,7 +148,9 @@ func TestLeaseGuardSleepsUntilTheBarrier(t *testing.T) { now = now.Add(39 * time.Second) in("1 s before T", g.renewDelay(), 1100*time.Millisecond, 1600*time.Millisecond) now = now.Add(2 * time.Second) - in("past T: the 1 s poll", g.renewDelay(), 800*time.Millisecond, 1200*time.Millisecond) + in("just past T: the fast poll", g.renewDelay(), 150*time.Millisecond, 250*time.Millisecond) + now = now.Add(5 * time.Second) + in("5 s past T: the 1 s poll", g.renewDelay(), 800*time.Millisecond, 1200*time.Millisecond) w.renewal(now, refusalWith(t, "barrier", control.WorkspaceLeaseRefusal_BARRIER, time.Hour)) in("a far barrier: capped", g.renewDelay(), 2*time.Minute, 2*time.Minute) if observed != 2 { diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index a26359a146..70dd913e00 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -118,6 +118,11 @@ func (g *WorkspaceLeaseGuard) renewDelay() time.Duration { if g.barrierAt != nil { if t := g.barrierAt(); t.After(now) { delay = min(t.Sub(now)+barrierWakeMargin+jittered(0, barrierWakeJitter), barrierSleepCap) + } else if !t.IsZero() && now.Sub(t) < barrierFastPollFor { + // Just past T every lapsed volume re-grants at once and the + // master refuses the ones that find its writer busy: retry + // those soon, not a second later. + delay = jittered(barrierFastPoll, barrierFastPoll/4) } } if !pending { @@ -316,6 +321,9 @@ const ( barrierWakeMargin = 100 * time.Millisecond barrierWakeJitter = 500 * time.Millisecond barrierSleepCap = 2 * time.Minute + // For barrierFastPollFor after T the pre-grant poll is barrierFastPoll. + barrierFastPoll = 200 * time.Millisecond + barrierFastPollFor = 5 * time.Second ) // jittered returns base plus a uniform offset in [-spread, +spread) (only From ec8f1ee0f74a56b582cf28ec14e22216aacee35e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 23:25:16 -0800 Subject: [PATCH 20/34] test: the fake HEAD follows the holder across moves Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/workspace_lease_refusal_kind_test.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go b/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go index 3c9f7519dc..9e29ac319d 100644 --- a/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go +++ b/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go @@ -38,12 +38,14 @@ func refusalOf(t *testing.T, stage string, err error) (string, *control.Workspac // detail (OTHER): a bounded wait, never an early 78. func TestLeaseRefusalKinds(t *testing.T) { var nowNS, headEpoch, headGen atomic.Int64 + var headHolder atomic.Value + headHolder.Store("node-a/r1") nowNS.Store(time.Now().UnixNano()) headEpoch.Store(1) headGen.Store(9) const ttl = 30 * time.Second h, conn, _ := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) { - return authority.WorkspaceHead{Gen: uint64(headGen.Load()), Epoch: uint64(headEpoch.Load()), Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil + return authority.WorkspaceHead{Gen: uint64(headGen.Load()), Epoch: uint64(headEpoch.Load()), Holder: headHolder.Load().(string), RemoteLSN: 42, Detached: true}, nil }, func(h *Host) { authority.WithWorkspaceLeaseConfig(ttl, func() time.Time { return time.Unix(0, nowNS.Load()) })(h.Publisher()) }) @@ -98,6 +100,7 @@ func TestLeaseRefusalKinds(t *testing.T) { t.Fatal(err) } headEpoch.Store(int64(from.GetEpoch())) + headHolder.Store(from.GetServerId() + "/r1") headGen.Add(1) if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: from, HeadGen: uint64(headGen.Load())}); err != nil { t.Fatal(err) @@ -150,6 +153,7 @@ func TestLeaseRefusalKinds(t *testing.T) { t.Fatal(err) } headEpoch.Store(int64(e4.GetEpoch())) + headHolder.Store("node-a/r1") headGen.Add(1) if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: e4, HeadGen: uint64(headGen.Load())}); err != nil { t.Fatal(err) From fc990eef8a8d345fb73a3be5c360f7fb42723e4c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 23:46:16 -0800 Subject: [PATCH 21/34] test: the barrier wake is jittered; a final refusal names the exit over superseded; docs The lifecycle page says how the start waits (no bound while blockmaster gives no reply, 30 s from the first answer or the barrier), what the new log lines mean, and what to do on exit 78 reason=moved or reason=deleted. Co-Authored-By: Claude Opus 5.5 --- .../process_exit_authority_test.go | 22 +++++++---- .../core/host/volume/master_wait_test.go | 10 ++++- seaweed-block/docs/volume-lifecycle.md | 38 ++++++++++++------- 3 files changed, 48 insertions(+), 22 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index 7c9f841c27..e157ae311e 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -510,14 +510,16 @@ func TestChunkStartupExitFinalGives78(t *testing.T) { return st.Err() } for _, tc := range []struct { - name string - refuse error - code int - reason string + name string + refuse error + foreign bool // the stream also delivered a newer line naming another replica + code int + reason string }{ - {"moved", refusal(control.WorkspaceLeaseRefusal_MOVED), exitWorkspaceSuperseded, "moved"}, - {"deleted", refusal(control.WorkspaceLeaseRefusal_DELETED), exitWorkspaceSuperseded, "deleted"}, - {"no detail", status.Error(codes.FailedPrecondition, "workspace lease: server identity does not match the current holder"), exitWorkspaceRetry, "assignment_timeout"}, + {"moved", refusal(control.WorkspaceLeaseRefusal_MOVED), false, exitWorkspaceSuperseded, "moved"}, + {"moved, newer foreign line also seen", refusal(control.WorkspaceLeaseRefusal_MOVED), true, exitWorkspaceSuperseded, "moved"}, + {"deleted", refusal(control.WorkspaceLeaseRefusal_DELETED), false, exitWorkspaceSuperseded, "deleted"}, + {"no detail", status.Error(codes.FailedPrecondition, "workspace lease: server identity does not match the current holder"), false, exitWorkspaceRetry, "assignment_timeout"}, } { t.Run(tc.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) @@ -538,6 +540,12 @@ func TestChunkStartupExitFinalGives78(t *testing.T) { } for tc.reason != "assignment_timeout" { if _, final := h.MasterWaitState(); final != "" { + if tc.foreign { + assign("r2", 2) + if !h.IsCurrentReplicaSuperseded() { + t.Fatal("fixture: the newer foreign line does not supersede") + } + } break } select { diff --git a/seaweed-block/core/host/volume/master_wait_test.go b/seaweed-block/core/host/volume/master_wait_test.go index da5e1c8914..fb89ffd2d3 100644 --- a/seaweed-block/core/host/volume/master_wait_test.go +++ b/seaweed-block/core/host/volume/master_wait_test.go @@ -142,8 +142,14 @@ func TestLeaseGuardSleepsUntilTheBarrier(t *testing.T) { } reply = refusalWith(t, "barrier", control.WorkspaceLeaseRefusal_BARRIER, 40*time.Second) _ = g.Refresh(context.Background()) - for i := 0; i < 20; i++ { - in("after BARRIER: until just past T", g.renewDelay(), 40*time.Second+100*time.Millisecond, 40*time.Second+600*time.Millisecond) + wakes := map[time.Duration]bool{} + for i := 0; i < 50; i++ { + d := g.renewDelay() + in("after BARRIER: until just past T", d, 40*time.Second+100*time.Millisecond, 40*time.Second+600*time.Millisecond) + wakes[d] = true + } + if len(wakes) < 10 { + t.Fatalf("%d distinct wake delays in 50; the wake past T must be jittered", len(wakes)) } now = now.Add(39 * time.Second) in("1 s before T", g.renewDelay(), 1100*time.Millisecond, 1600*time.Millisecond) diff --git a/seaweed-block/docs/volume-lifecycle.md b/seaweed-block/docs/volume-lifecycle.md index 0f9ed3ba79..96e2eca624 100644 --- a/seaweed-block/docs/volume-lifecycle.md +++ b/seaweed-block/docs/volume-lifecycle.md @@ -314,19 +314,27 @@ blockmaster grants the lease again only after a barrier: the stored lease horizo (up to 45 s after the last renewal) and the last grant, each plus `--workspace-max-clock-skew` (default `20s`). With the defaults that is at most **65 seconds after the process stopped**; if blockmaster restarted meanwhile, also at -least 50 seconds (30 s plus the skew) after that restart, whichever is later. Until -then the process logs, every second, `workspace lease: renewal failed after ...: ... -workspace forced move lease expiry plus clock-skew margin has not elapsed`, and does -not serve. After the grant it reclaims HEAD and serves its local WAL: nothing -acknowledged is lost. +least 50 seconds (30 s plus the skew) after that restart, whichever is later. The +refusal says when: `workspace lease: renewal failed after ...: workspace forced move +lease expiry plus clock-skew margin has not elapsed (re-grant refused until