From e9aecf52dc0c08ae34eb85e9c2afc1116dc4e5ee Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 04:42:38 -0800 Subject: [PATCH 1/6] master: name the precondition that refused a workspace move MoveWorkspace refused four different conditions with one message and no log line: an unknown source, an unregistered target node, a target that is the source, and target endpoints that are not registered. Each now has its own FailedPrecondition message, logged with the volume and request. The endpoint refusal also says what is registered: the node's own pair for a volume without per-volume bindings, else its live bindings on that node (a slot-1 target on a node registered at slot 0 shows up here). Co-Authored-By: Claude Opus 5.5 --- .../master/workspace_move_refusal_test.go | 128 ++++++++++++++++++ .../core/host/master/workspace_service.go | 37 ++++- 2 files changed, 163 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/host/master/workspace_move_refusal_test.go diff --git a/seaweed-block/core/host/master/workspace_move_refusal_test.go b/seaweed-block/core/host/master/workspace_move_refusal_test.go new file mode 100644 index 0000000000..1fb70288de --- /dev/null +++ b/seaweed-block/core/host/master/workspace_move_refusal_test.go @@ -0,0 +1,128 @@ +package master + +import ( + "bytes" + "context" + "log" + "strings" + "sync" + "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" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +type syncBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuffer) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *syncBuffer) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + +// A refused move names the precondition that failed, in the gRPC status and +// in the master log: an unknown source, an unregistered target node, a +// target that is the source, or target endpoints that are not registered +// (with what is registered: the node's pair, or the volume's live bindings +// on that node). A slot-1 target on a node registered at slot 0 is the last +// kind. +func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { + logs := &syncBuffer{} + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + Logger: log.New(logs, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil + }}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + for _, n := range []lifecycle.NodeRegistration{ + {ServerID: "node-a", DataAddr: "127.0.0.1:19101", CtrlAddr: "127.0.0.1:19102"}, + {ServerID: "node-b", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"}, + } { + if _, err := m.Lifecycle().Nodes.RegisterNode(n); err != nil { + t.Fatal(err) + } + } + for _, v := range []string{"placed", "unplaced", "bound"} { + if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: v, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + } + if _, err := m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "placed", DesiredRF: 1, + Candidates: []lifecycle.PlacementCandidate{{VolumeID: "placed", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { + t.Fatal(err) + } + // "bound" has explicit per-volume bindings: its source on node-a and a + // prepared target on node-b at slot 2. + for _, b := range []*control.WorkspaceBinding{ + {VolumeId: "bound", ServerId: "node-a", DataAddr: "127.0.0.1:19121", CtrlAddr: "127.0.0.1:19122"}, + {VolumeId: "bound", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}, + } { + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "bound", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + + move := func(vol, server, data, ctrl string) *control.WorkspaceMove { + return &control.WorkspaceMove{RequestId: vol + "-" + server + "-" + data, VolumeId: vol, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", + TargetServerId: server, TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"} + } + for _, c := range []struct { + name string + q *control.WorkspaceMove + want string + }{ + {"unknown source", move("unplaced", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), `move source unknown: no issued move or placement names replica "r1" at epoch 1`}, + {"unknown target node", move("placed", "node-z", "127.0.0.1:19301", "127.0.0.1:19302"), `move target node "node-z" is not registered`}, + {"target is the source", move("placed", "node-a", "127.0.0.1:19101", "127.0.0.1:19102"), `move target "node-a" is the current source host`}, + {"slot-1 target, node registered at slot 0", move("placed", "node-b", "127.0.0.1:19311", "127.0.0.1:19312"), + `move target endpoints 127.0.0.1:19311/127.0.0.1:19312 on "node-b" are not registered (the node registers 127.0.0.1:19301/127.0.0.1:19302; no per-volume binding is prepared)`}, + {"explicit binding elsewhere", move("bound", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), + `move target endpoints 127.0.0.1:19301/127.0.0.1:19302 on "node-b" are not registered (live bindings on that node: 127.0.0.1:19321/127.0.0.1:19322)`}, + } { + t.Run(c.name, func(t *testing.T) { + _, err := ws.MoveWorkspace(ctx, c.q) + if status.Code(err) != codes.FailedPrecondition || status.Convert(err).Message() != c.want { + t.Fatalf("refusal %v; want FailedPrecondition %q", err, c.want) + } + if line := `MoveWorkspace refused volume="` + c.q.VolumeId + `" request="` + c.q.RequestId + `": ` + c.want; !strings.Contains(logs.String(), line) { + t.Fatalf("log lacks %q:\n%s", line, logs.String()) + } + }) + } + // The slot-0 target passes these preconditions (it fails later, at the + // clean-move ACK check, for a different reason). + _, err = ws.MoveWorkspace(ctx, move("placed", "node-b", "127.0.0.1:19301", "127.0.0.1:19302")) + if err == nil || strings.Contains(err.Error(), "move target") || strings.Contains(err.Error(), "move source") { + t.Fatalf("slot-0 target: %v; want past the endpoint preconditions", err) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index f8a068cff9..1fb9cd5af5 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -2,6 +2,8 @@ package master import ( "context" + "fmt" + "strings" "time" "github.com/seaweedfs/seaweed-block/core/authority" @@ -163,8 +165,20 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) matched = true } } - if oldHost == "" || !ok || target.ServerID == oldHost || !matched { - return nil, status.Error(codes.FailedPrecondition, "move needs known source slot and registered target endpoints") + var refusal string + switch { + case oldHost == "": + refusal = fmt.Sprintf("move source unknown: no issued move or placement names replica %q at epoch %d", q.GetExpectedReplicaId(), q.GetExpectedEpoch()) + case !ok: + refusal = fmt.Sprintf("move target node %q is not registered", q.GetTargetServerId()) + case target.ServerID == oldHost: + refusal = fmt.Sprintf("move target %q is the current source host", target.ServerID) + case !matched: + refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit)) + } + if refusal != "" { + s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal) + return nil, status.Error(codes.FailedPrecondition, refusal) } if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { return nil, workspaceError(err) @@ -180,6 +194,25 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) return grantFact(r), nil } +// registeredTargetEndpoints describes what a move to target may name: the +// node's own pair for a volume without explicit bindings, else its live +// bindings on that node. +func registeredTargetEndpoints(target lifecycle.NodeRegistration, bindings []lifecycle.WorkspaceBinding, explicit bool) string { + if !explicit { + return fmt.Sprintf("the node registers %s/%s; no per-volume binding is prepared", target.DataAddr, target.CtrlAddr) + } + var live []string + for _, b := range bindings { + if !b.Retired && b.ServerID == target.ServerID { + live = append(live, b.DataAddr+"/"+b.CtrlAddr) + } + } + if len(live) == 0 { + return "the volume has explicit bindings but none live on that node" + } + return "live bindings on that node: " + strings.Join(live, ", ") +} + func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolume) (*control.WorkspaceStatus, error) { s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() From d8c42d0928eacb3384fd207e6acb9dd5a4a095da Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 04:57:41 -0800 Subject: [PATCH 2/6] master: a move target may use any port on the target node's host A volume without per-volume bindings could move only to the target node's single registered address pair, which models one slot per node: a host serving several slots refused every move whose target landed on a slot other than the registered one (slot 1 while slot 0 is held). The target now needs both endpoints on the node's registered hosts (literal host part, any port, no name resolution), and the existing collision check still refuses endpoints another live assignment or binding owns. Volumes with per-volume bindings keep the exact binding match. Co-Authored-By: Claude Opus 5.5 --- .../master/workspace_move_refusal_test.go | 19 +-- .../host/master/workspace_move_slot_test.go | 114 ++++++++++++++++++ .../core/host/master/workspace_service.go | 20 ++- 3 files changed, 142 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/core/host/master/workspace_move_slot_test.go diff --git a/seaweed-block/core/host/master/workspace_move_refusal_test.go b/seaweed-block/core/host/master/workspace_move_refusal_test.go index 1fb70288de..61ec0f4c67 100644 --- a/seaweed-block/core/host/master/workspace_move_refusal_test.go +++ b/seaweed-block/core/host/master/workspace_move_refusal_test.go @@ -39,8 +39,7 @@ func (s *syncBuffer) String() string { // in the master log: an unknown source, an unregistered target node, a // target that is the source, or target endpoints that are not registered // (with what is registered: the node's pair, or the volume's live bindings -// on that node). A slot-1 target on a node registered at slot 0 is the last -// kind. +// on that node). func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { logs := &syncBuffer{} m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, @@ -104,8 +103,8 @@ func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { {"unknown source", move("unplaced", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), `move source unknown: no issued move or placement names replica "r1" at epoch 1`}, {"unknown target node", move("placed", "node-z", "127.0.0.1:19301", "127.0.0.1:19302"), `move target node "node-z" is not registered`}, {"target is the source", move("placed", "node-a", "127.0.0.1:19101", "127.0.0.1:19102"), `move target "node-a" is the current source host`}, - {"slot-1 target, node registered at slot 0", move("placed", "node-b", "127.0.0.1:19311", "127.0.0.1:19312"), - `move target endpoints 127.0.0.1:19311/127.0.0.1:19312 on "node-b" are not registered (the node registers 127.0.0.1:19301/127.0.0.1:19302; no per-volume binding is prepared)`}, + {"target on another host", move("placed", "node-b", "10.9.9.9:19311", "127.0.0.1:19312"), + `move target endpoints 10.9.9.9:19311/127.0.0.1:19312 on "node-b" are not registered (not on the node's hosts: it registers 127.0.0.1:19301/127.0.0.1:19302; no per-volume binding is prepared)`}, {"explicit binding elsewhere", move("bound", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), `move target endpoints 127.0.0.1:19301/127.0.0.1:19302 on "node-b" are not registered (live bindings on that node: 127.0.0.1:19321/127.0.0.1:19322)`}, } { @@ -119,10 +118,12 @@ func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { } }) } - // The slot-0 target passes these preconditions (it fails later, at the - // clean-move ACK check, for a different reason). - _, err = ws.MoveWorkspace(ctx, move("placed", "node-b", "127.0.0.1:19301", "127.0.0.1:19302")) - if err == nil || strings.Contains(err.Error(), "move target") || strings.Contains(err.Error(), "move source") { - t.Fatalf("slot-0 target: %v; want past the endpoint preconditions", err) + // Slot-0 and slot-1 targets on the node's host pass these preconditions + // (they fail later, at the clean-move ACK check, for a different reason). + for _, data := range []string{"127.0.0.1:19301", "127.0.0.1:19311"} { + _, err = ws.MoveWorkspace(ctx, move("placed", "node-b", data, "127.0.0.1:19312")) + if err == nil || strings.Contains(err.Error(), "move target") || strings.Contains(err.Error(), "move source") { + t.Fatalf("target %s on the node's host: %v; want past the endpoint preconditions", data, err) + } } } diff --git a/seaweed-block/core/host/master/workspace_move_slot_test.go b/seaweed-block/core/host/master/workspace_move_slot_test.go new file mode 100644 index 0000000000..70046c2073 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_move_slot_test.go @@ -0,0 +1,114 @@ +package master + +import ( + "context" + "strconv" + "strings" + "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" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// The T08 shape: two volumes without per-volume bindings, nodes registered +// at slot 0 of their host. "a1" holds slot 0 on node-a; "a2" lives on +// node-b and moves back to node-a. Its target lands on slot 1 (slot 0 is +// held) and is granted; a target on a1's live slot-0 endpoints is refused by +// the collision check, and one on another host's address by the ownership +// check. The grant routes a2 to the slot-1 endpoints it asked for. +func TestWorkspaceMoveToAnotherSlotOnTheTargetHost(t *testing.T) { + heads := map[string]authority.WorkspaceHead{"a2": {Gen: 9, Epoch: 1, Holder: "node-b/r1", RemoteLSN: 42, Detached: true}} + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + WorkspaceHeadReader: func(_ context.Context, v string) (authority.WorkspaceHead, error) { return heads[v], nil }}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + slot := func(base, n int) (string, string) { + return "127.0.0.1:" + strconv.Itoa(base+10*n+1), "127.0.0.1:" + strconv.Itoa(base+10*n+2) + } + for _, n := range []struct { + id string + base int + }{{"node-a", 19100}, {"node-b", 19300}} { + d, c := slot(n.base, 0) + if _, err := m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: n.id, DataAddr: d, CtrlAddr: c}); err != nil { + t.Fatal(err) + } + } + place := func(vol, server string, base int) authority.AuthorityBasis { + t.Helper() + if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: vol, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + if _, err := m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: vol, DesiredRF: 1, + Candidates: []lifecycle.PlacementCandidate{{VolumeID: vol, ServerID: server, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { + t.Fatal(err) + } + d, c := slot(base, 0) + if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: vol, ReplicaId: "r1", DataAddr: d, CtrlAddr: c}}}); err != nil { + t.Fatal(err) + } + if _, err := m.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + return waitAuthorityLine(t, m.Publisher(), vol) + } + a1 := place("a1", "node-a", 19100) // holds node-a slot 0 + a2 := place("a2", "node-b", 19300) + if a1.DataAddr != "127.0.0.1:19101" || a2.DataAddr != "127.0.0.1:19301" { + t.Fatalf("fixture lines a1=%+v a2=%+v", a1, a2) + } + // a2 stops cleanly on node-b: lease, revocation, ACK of its detached HEAD. + id := &control.WorkspaceIdentity{VolumeId: "a2", ReplicaId: "r1", Epoch: a2.Epoch} + if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil { + t.Fatal(err) + } + if _, err := ws.RevokeWorkspace(ctx, id); err != nil { + t.Fatal(err) + } + if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil { + t.Fatal(err) + } + move := func(req, data, ctrl string) *control.WorkspaceMove { + return &control.WorkspaceMove{RequestId: req, VolumeId: "a2", ExpectedReplicaId: "r1", ExpectedEpoch: a2.Epoch, TargetReplicaId: "r1", + TargetServerId: "node-a", TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"} + } + d0, c0 := slot(19100, 0) + if _, err := ws.MoveWorkspace(ctx, move("onto-a1", d0, c0)); err == nil || !strings.Contains(err.Error(), "endpoint belongs to live assignment") { + t.Fatalf("move onto a1's live slot-0 endpoints: %v; want the collision refusal", err) + } + if _, err := ws.MoveWorkspace(ctx, move("other-host", "10.9.9.9:19111", "10.9.9.9:19112")); err == nil || !strings.Contains(err.Error(), `endpoints 10.9.9.9:19111/10.9.9.9:19112 on "node-a" are not registered`) { + t.Fatalf("move to another host's address: %v; want the ownership refusal", err) + } + d1, c1 := slot(19100, 1) + if _, err := ws.MoveWorkspace(ctx, move("ctrl-other-host", d1, "10.9.9.9:19112")); err == nil || !strings.Contains(err.Error(), `on "node-a" are not registered`) { + t.Fatalf("move with its ctrl endpoint on another host: %v; want the ownership refusal", err) + } + g, err := ws.MoveWorkspace(ctx, move("slot-1", d1, c1)) + if err != nil { + t.Fatalf("move to node-a slot 1 while slot 0 is held: %v", err) + } + line, ok := m.Publisher().VolumeAuthorityLine("a2") + if !g.Issued || g.NewHost != "node-a" || g.OldHost != "node-b" || !ok || line.Epoch != g.NewEpoch || line.DataAddr != d1 || line.CtrlAddr != c1 { + t.Fatalf("grant %+v line %+v; want a2 issued on node-a at %s/%s", g, line, d1, c1) + } + if l1, _ := m.Publisher().VolumeAuthorityLine("a1"); l1.DataAddr != d0 || l1.Epoch != a1.Epoch { + t.Fatalf("a1 changed: %+v", l1) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 1fb9cd5af5..6df4603586 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -3,6 +3,7 @@ package master import ( "context" "fmt" + "net" "strings" "time" @@ -159,7 +160,11 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err != nil { return nil, workspaceError(err) } - matched := !explicit && target.DataAddr == q.GetTargetDataAddr() && target.CtrlAddr == q.GetTargetCtrlAddr() + // A volume without per-volume bindings may move to any port on the + // target node's registered hosts (a host runs several slots); the + // collision check below still refuses endpoints another assignment or + // binding owns. The host match is the proof the endpoints are that node's. + matched := !explicit && sameHost(q.GetTargetDataAddr(), target.DataAddr) && sameHost(q.GetTargetCtrlAddr(), target.CtrlAddr) for _, b := range bindings { if !b.Retired && b.ServerID == q.GetTargetServerId() && b.DataAddr == q.GetTargetDataAddr() && b.CtrlAddr == q.GetTargetCtrlAddr() { matched = true @@ -194,12 +199,23 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) return grantFact(r), nil } +// sameHost reports whether two host:port addresses name the same host: the +// literal host parts after SplitHostPort, no name resolution. +func sameHost(a, b string) bool { + ha, _, err := net.SplitHostPort(a) + if err != nil { + return false + } + hb, _, err := net.SplitHostPort(b) + return err == nil && ha != "" && ha == hb +} + // registeredTargetEndpoints describes what a move to target may name: the // node's own pair for a volume without explicit bindings, else its live // bindings on that node. func registeredTargetEndpoints(target lifecycle.NodeRegistration, bindings []lifecycle.WorkspaceBinding, explicit bool) string { if !explicit { - return fmt.Sprintf("the node registers %s/%s; no per-volume binding is prepared", target.DataAddr, target.CtrlAddr) + return fmt.Sprintf("not on the node's hosts: it registers %s/%s; no per-volume binding is prepared", target.DataAddr, target.CtrlAddr) } var live []string for _, b := range bindings { From ec40814443919f620fffb43dcb17cdb6231d4763 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 05:34:16 -0800 Subject: [PATCH 3/6] master: validate a move target's endpoints; log a refusal outside the lock Fold of the #260 review: - the target endpoints get the binding endpoint rules before admission (host:port, numeric port 1..65535, data and ctrl distinct), without registering anything: a host match alone admitted ':0', ':65536', a non-numeric or empty port, or identical data and ctrl, and the move would have issued and cleared the source lease; - host parts compare in canonical form (equivalent IP spellings); - the refusal log runs after workspaceMu is released; - the comment no longer calls the host match a proof; the invariants ledger gets the move-admission row. Co-Authored-By: Claude Opus 5.5 --- .../master/workspace_move_refusal_test.go | 73 +++++++++++++++++++ .../host/master/workspace_move_slot_test.go | 19 +++++ .../core/host/master/workspace_service.go | 33 +++++---- .../core/lifecycle/workspace_bindings.go | 19 +++++ seaweed-block/docs/design/invariants.md | 1 + 5 files changed, 131 insertions(+), 14 deletions(-) diff --git a/seaweed-block/core/host/master/workspace_move_refusal_test.go b/seaweed-block/core/host/master/workspace_move_refusal_test.go index 61ec0f4c67..9a7e113705 100644 --- a/seaweed-block/core/host/master/workspace_move_refusal_test.go +++ b/seaweed-block/core/host/master/workspace_move_refusal_test.go @@ -127,3 +127,76 @@ func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { } } } + +// blockingWriter blocks the first write that contains marker until +// released; other writes pass. +type blockingWriter struct { + marker string + entered, release chan struct{} + once sync.Once +} + +func (b *blockingWriter) Write(p []byte) (int, error) { + if !strings.Contains(string(p), b.marker) { + return len(p), nil + } + first := false + b.once.Do(func() { first = true }) + if first { + close(b.entered) + <-b.release + } + return len(p), nil +} + +// A refused move is logged after workspaceMu is released: while the log +// writer is blocked, another workspace RPC still gets the lock. +func TestWorkspaceMoveRefusalLogsOutsideTheWorkspaceLock(t *testing.T) { + w := &blockingWriter{marker: "MoveWorkspace refused", entered: make(chan struct{}), release: make(chan struct{})} + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, Logger: log.New(w, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(w.release) }) } + defer release() + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + ws := control.NewWorkspaceServiceClient(conn) + if _, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + _, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "r", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"}) + done <- err + }() + select { + case <-w.entered: + case <-time.After(10 * time.Second): + t.Fatal("the refusal was never logged") + } + qctx, qcancel := context.WithTimeout(ctx, 5*time.Second) + defer qcancel() + if _, err := ws.QueryWorkspace(qctx, &control.WorkspaceVolume{VolumeId: "v"}); err != nil { + t.Fatalf("workspace RPC while the refusal log is blocked: %v; want workspaceMu free", err) + } + release() + select { + case err := <-done: + if status.Code(err) != codes.FailedPrecondition { + t.Fatalf("move: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("the move did not return after the log was released") + } +} diff --git a/seaweed-block/core/host/master/workspace_move_slot_test.go b/seaweed-block/core/host/master/workspace_move_slot_test.go index 70046c2073..f6a31dbac6 100644 --- a/seaweed-block/core/host/master/workspace_move_slot_test.go +++ b/seaweed-block/core/host/master/workspace_move_slot_test.go @@ -100,6 +100,25 @@ func TestWorkspaceMoveToAnotherSlotOnTheTargetHost(t *testing.T) { if _, err := ws.MoveWorkspace(ctx, move("ctrl-other-host", d1, "10.9.9.9:19112")); err == nil || !strings.Contains(err.Error(), `on "node-a" are not registered`) { t.Fatalf("move with its ctrl endpoint on another host: %v; want the ownership refusal", err) } + // Invalid endpoints on the right host are refused before anything is + // written: the epoch, the journal, the lease and the ACK stay as they were. + before := m.Publisher().WorkspaceState("a2") + for _, bad := range []struct{ name, data, ctrl string }{ + {"non-numeric port", "127.0.0.1:bad", c1}, + {"port 0", "127.0.0.1:0", c1}, + {"port 65536", d1, "127.0.0.1:65536"}, + {"empty port", "127.0.0.1:", c1}, + {"data equals ctrl", d1, d1}, + } { + if _, err := ws.MoveWorkspace(ctx, move("bad-"+bad.name, bad.data, bad.ctrl)); err == nil || !strings.Contains(err.Error(), "move target endpoints invalid") { + t.Fatalf("%s: %v; want the invalid-endpoint refusal", bad.name, err) + } + after := m.Publisher().WorkspaceState("a2") + line, _ := m.Publisher().VolumeAuthorityLine("a2") + if line.Epoch != a2.Epoch || after == nil || len(after.Moves) != 0 || after.Ack == nil || before.Ack == nil || *after.Ack != *before.Ack || after.Lease == nil || !after.Lease.Revoking { + t.Fatalf("%s: state changed by a refused move: line %+v state %+v", bad.name, line, after) + } + } g, err := ws.MoveWorkspace(ctx, move("slot-1", d1, c1)) if err != nil { t.Fatalf("move to node-a slot 1 while slot 0 is held: %v", err) diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 6df4603586..fabe00514c 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -3,7 +3,6 @@ package master import ( "context" "fmt" - "net" "strings" "time" @@ -146,6 +145,14 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) } // Remote reads never hold the workspace mutation lock. Re-read every // local precondition below; Publisher checks the expected epoch atomically. + // A refusal is logged after the lock is released (deferred first, so it + // runs last): a slow log writer never holds workspaceMu. + var refusal string + defer func() { + if refusal != "" { + s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal) + } + }() s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() if err := ctx.Err(); err != nil { @@ -161,17 +168,20 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) return nil, workspaceError(err) } // A volume without per-volume bindings may move to any port on the - // target node's registered hosts (a host runs several slots); the - // collision check below still refuses endpoints another assignment or - // binding owns. The host match is the proof the endpoints are that node's. + // target node's registered hosts (a host runs several slots): the host + // match ties the endpoints to that node's registration (it trusts the + // registration; it is not an identity proof). The collision check below + // still refuses endpoints another assignment or binding owns. matched := !explicit && sameHost(q.GetTargetDataAddr(), target.DataAddr) && sameHost(q.GetTargetCtrlAddr(), target.CtrlAddr) + endpointErr := lifecycle.ValidateWorkspaceEndpoints(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: q.GetTargetServerId(), DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}) for _, b := range bindings { if !b.Retired && b.ServerID == q.GetTargetServerId() && b.DataAddr == q.GetTargetDataAddr() && b.CtrlAddr == q.GetTargetCtrlAddr() { matched = true } } - var refusal string switch { + case endpointErr != nil: + refusal = fmt.Sprintf("move target endpoints invalid: %v", endpointErr) case oldHost == "": refusal = fmt.Sprintf("move source unknown: no issued move or placement names replica %q at epoch %d", q.GetExpectedReplicaId(), q.GetExpectedEpoch()) case !ok: @@ -182,7 +192,6 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit)) } if refusal != "" { - s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal) return nil, status.Error(codes.FailedPrecondition, refusal) } if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { @@ -199,15 +208,11 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) return grantFact(r), nil } -// sameHost reports whether two host:port addresses name the same host: the -// literal host parts after SplitHostPort, no name resolution. +// sameHost reports whether two host:port addresses name the same host: +// canonical host parts (equivalent IP spellings equal), no name resolution. func sameHost(a, b string) bool { - ha, _, err := net.SplitHostPort(a) - if err != nil { - return false - } - hb, _, err := net.SplitHostPort(b) - return err == nil && ha != "" && ha == hb + ha := lifecycle.WorkspaceEndpointHost(a) + return ha != "" && ha == lifecycle.WorkspaceEndpointHost(b) } // registeredTargetEndpoints describes what a move to target may name: the diff --git a/seaweed-block/core/lifecycle/workspace_bindings.go b/seaweed-block/core/lifecycle/workspace_bindings.go index 5d51a472ba..d3fbefd8e9 100644 --- a/seaweed-block/core/lifecycle/workspace_bindings.go +++ b/seaweed-block/core/lifecycle/workspace_bindings.go @@ -119,6 +119,25 @@ func validateWorkspaceBinding(b WorkspaceBinding) error { return nil } +// ValidateWorkspaceEndpoints applies a binding's endpoint rules (host:port +// with a numeric port 1..65535, data and ctrl distinct) without registering +// anything. +func ValidateWorkspaceEndpoints(b WorkspaceBinding) error { return validateWorkspaceBinding(b) } + +// WorkspaceEndpointHost returns addr's host in canonical form (equivalent IP +// spellings compare equal; names lower-cased; no DNS), or "" if addr is not +// host:port. +func WorkspaceEndpointHost(addr string) string { + h, _, err := net.SplitHostPort(addr) + if err != nil || h == "" { + return "" + } + if ip := net.ParseIP(h); ip != nil { + return ip.String() + } + return strings.ToLower(h) +} + // Compare numeric ports and equivalent IP spellings without DNS/network I/O. func workspaceEndpointKey(addr string) string { h, p, err := net.SplitHostPort(addr) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6ee4916e12..671d0687e1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -93,6 +93,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | +| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | | Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | | Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | From 6a063f2ec87d786718602a8c546b7f1c960fa49e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 05:44:54 -0800 Subject: [PATCH 4/6] test: freeze the publisher clock while the extension write is held (#247 hang) TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose hung ~9m40s in a loaded qual run (goroutine dump: one extender held in the store hook, four queued on p.mu, renewers looping, the test in the progress loop). Cause: a test bug. The test's publisher clock was real time with a 2 s TTL; while the held extension write holds p.mu no horizon can move, so a late test goroutine let horizons expire, renewals were refused, and the progress condition (a grant under the hold for every eligible volume) could never hold. Not a product stall: renewals never waited for the store. The clock is now frozen while the extension write is held and resumes from the frozen instant at the release (no jump over a horizon), so extensions again run in real time alongside the writers and Close. A 3.5 s late test goroutine after the hold is now part of the test; without the freeze it fails ('revoke ACK: lease expired'). Co-Authored-By: Claude Opus 5.5 --- .../authority/workspace_lease_horizon_test.go | 34 +++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 128cfc0291..efb2111d50 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -617,7 +617,27 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { var extensions atomic.Int64 heldEntered, heldRelease := make(chan struct{}), make(chan struct{}) var holdOnce, releaseOnce sync.Once - releaseHold := func() { releaseOnce.Do(func() { close(heldRelease) }) } + // The publisher clock is frozen while the extension write is held (#247 + // hang): the held write holds p.mu, so every other volume's extender queues + // and no horizon can move. With a running clock a late test goroutine could + // let horizons expire before each volume got a grant under the hold (the + // progress condition never holds), or before the writers run after the + // release (a revoke ACK finds the lease expired). This test is about lock + // and store ordering, not about lease expiry. + var frozenNS atomic.Int64 // 0 = running + // At the release the clock resumes from the frozen instant (the offset takes + // back the time spent held), so it neither jumps over a horizon nor runs + // backwards; extensions then run in real time alongside writers and Close. + var offNS atomic.Int64 + releaseHold := func() { + releaseOnce.Do(func() { + if f := frozenNS.Load(); f != 0 { + offNS.Add(-int64(time.Since(time.Unix(0, f)))) + frozenNS.Store(0) + } + close(heldRelease) + }) + } var classifying atomic.Bool var holding atomic.Bool // set when the extension write is held, before it blocks hs.setBefore(func(r DurableRecord) error { @@ -638,6 +658,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { first := false holdOnce.Do(func() { first = true }) if first { + frozenNS.Store(time.Now().Add(time.Duration(offNS.Load())).UnixNano()) holding.Store(true) // before the hold: a renewal started after this saw it close(heldEntered) <-heldRelease @@ -648,9 +669,13 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // The publisher clock is real time plus an offset. The forced-move volume // is granted at offset -10 s, so by offset 0 its horizon + skew barrier has // passed; the clock only moves forward. - var offNS atomic.Int64 offNS.Store(int64(-10 * time.Second)) - p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, func() time.Time { return time.Now().Add(time.Duration(offNS.Load())) })) + p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, func() time.Time { + if f := frozenNS.Load(); f != 0 { + return time.Unix(0, f) + } + return time.Now().Add(time.Duration(offNS.Load())) + })) t.Cleanup(p.CloseWorkspaceExtenders) ctx := context.Background() bindAndGrant(t, p, vol(forcedVol), "r") // never renewed again @@ -736,6 +761,9 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // Handshake 1: the first extension write is held inside the store. <-heldEntered // progress, no timer (#227): renewers keep triggering extensions + // A late test goroutine (machine load), longer than a horizon (1.5 x TTL): + // with the clock frozen under the hold, no volume can lose its lease here. + time.Sleep(3500 * time.Millisecond) // Handshake 2: renewals keep succeeding while it is held. // Progress, no timer (#227): every eligible volume gains a grant from a call // that STARTED while the extension write was held (a reply computed before From 385ad024f4e8f48b6887ee7af76204fc5147f19b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 05:51:34 -0800 Subject: [PATCH 5/6] test: #262 fold: one test-clock transaction per Now/Freeze/Resume; failure exits on the hold waits Review fold (codex01, test only): the frozen check, time.Now and the offset were separate reads, so a reader paused across freeze+release could see the clock go backwards. leaseTestClock serializes Now/Freeze/Resume/SetOffset under one mutex and never returns an earlier time than a previous Now. TestLeaseTestClockMonotonicAcrossFreezeResume runs readers across 50 freeze/resume transitions. The held-entered and under-hold progress waits get 30 s real-time failure exits (never a pass); the cleanup releases the hold and joins every worker. Co-Authored-By: Claude Opus 5.5 --- .../authority/workspace_lease_horizon_test.go | 191 +++++++++++++++--- 1 file changed, 162 insertions(+), 29 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index efb2111d50..56ad9facd5 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -624,22 +624,19 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // progress condition never holds), or before the writers run after the // release (a revoke ACK finds the lease expired). This test is about lock // and store ordering, not about lease expiry. - var frozenNS atomic.Int64 // 0 = running - // At the release the clock resumes from the frozen instant (the offset takes - // back the time spent held), so it neither jumps over a horizon nor runs - // backwards; extensions then run in real time alongside writers and Close. - var offNS atomic.Int64 + // At the release the clock resumes from the frozen instant, so it neither + // jumps over a horizon nor runs backwards; extensions then run in real time + // alongside writers and Close. Now/Freeze/Resume are one transaction each. + clock := &leaseTestClock{} releaseHold := func() { releaseOnce.Do(func() { - if f := frozenNS.Load(); f != 0 { - offNS.Add(-int64(time.Since(time.Unix(0, f)))) - frozenNS.Store(0) - } + clock.Resume() close(heldRelease) }) } var classifying atomic.Bool - var holding atomic.Bool // set when the extension write is held, before it blocks + var holding atomic.Bool // set when the extension write is held, before it blocks + var heldVol atomic.Value // string: the volume whose extension write is held hs.setBefore(func(r DurableRecord) error { time.Sleep(5 * time.Millisecond) // a slow store if !classifying.Load() || r.Workspace == nil || r.Workspace.Lease == nil { @@ -658,8 +655,9 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { first := false holdOnce.Do(func() { first = true }) if first { - frozenNS.Store(time.Now().Add(time.Duration(offNS.Load())).UnixNano()) - holding.Store(true) // before the hold: a renewal started after this saw it + clock.Freeze() + heldVol.Store(r.VolumeID) // the volume whose extension write is held + holding.Store(true) // before the hold: a renewal started after this saw it close(heldEntered) <-heldRelease } @@ -669,17 +667,12 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // The publisher clock is real time plus an offset. The forced-move volume // is granted at offset -10 s, so by offset 0 its horizon + skew barrier has // passed; the clock only moves forward. - offNS.Store(int64(-10 * time.Second)) - p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, func() time.Time { - if f := frozenNS.Load(); f != 0 { - return time.Unix(0, f) - } - return time.Now().Add(time.Duration(offNS.Load())) - })) + clock.SetOffset(-10 * time.Second) + p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, clock.Now)) t.Cleanup(p.CloseWorkspaceExtenders) ctx := context.Background() bindAndGrant(t, p, vol(forcedVol), "r") // never renewed again - offNS.Store(0) + clock.SetOffset(0) for i := 0; i < n; i++ { if i != forcedVol { bindAndGrant(t, p, vol(i), "r") @@ -692,7 +685,9 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { classifying.Store(true) var grants [n]atomic.Int64 - var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held + var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held + var returnedUnderHold [n]atomic.Int64 // calls (any outcome) that started while the extension write was held + var otherRefusals atomic.Value // string: a refusal under the hold that is not horizon exhaustion var maxGrant [n]atomic.Int64 var slowest atomic.Int64 stop := make(chan struct{}) @@ -745,6 +740,16 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { if d := int64(time.Since(start)); d > slowest.Load() { slowest.Store(d) } + if fresh { + returnedUnderHold[i].Add(1) + // With the clock frozen and every extension queued behind the + // held write, a horizon left without host validity is refused + // by design; any other refusal here is a failure. + if err != nil && !strings.Contains(err.Error(), "leaves no host validity") && + !strings.Contains(err.Error(), "expired or revoking") { + otherRefusals.CompareAndSwap(nil, fmt.Sprintf("%s: %v", vol(i), err)) + } + } if err == nil && !l.Revoking { grants[i].Add(1) if fresh { @@ -760,26 +765,44 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { } // Handshake 1: the first extension write is held inside the store. - <-heldEntered // progress, no timer (#227): renewers keep triggering extensions + // Progress handshakes (#227) with a real-time failure exit (never a pass): + // the cleanup releases the hold and joins every worker. + select { + case <-heldEntered: // renewers keep triggering extensions + case <-time.After(30 * time.Second): + t.Fatal("no extension write was held within 30 s") + } // A late test goroutine (machine load), longer than a horizon (1.5 x TTL): // with the clock frozen under the hold, no volume can lose its lease here. time.Sleep(3500 * time.Millisecond) - // Handshake 2: renewals keep succeeding while it is held. - // Progress, no timer (#227): every eligible volume gains a grant from a call - // that STARTED while the extension write was held (a reply computed before - // the hold does not count). Renewals that waited for it would never return. - for { + // Handshake 2: renewals never wait for the held store write (#205). + // Progress, no timer (#227): every eligible volume has a call that STARTED + // while the extension write was held and returned (a reply computed before + // the hold does not count); renewals that waited for it would never return. + // Grants under the hold are clamped to each volume's durable horizon: under + // the frozen clock a volume whose horizon leaves no host validity is refused + // by design, so grants are reported, and only horizon refusals are allowed. + held, _ := heldVol.Load().(string) + for give := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) { all := true for _, i := range eligible { - if underHold[i].Load() == 0 { + if returnedUnderHold[i].Load() == 0 { all = false } } if all { break } - time.Sleep(5 * time.Millisecond) + if time.Now().After(give) { + t.Fatalf("under the held extension of %s within 30 s: grants %v, returned calls %v", held, + underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible)) + } } + if r, _ := otherRefusals.Load().(string); r != "" { + t.Fatalf("under the held extension of %s: refusal other than horizon exhaustion: %s", held, r) + } + t.Logf("under the held extension of %s: grants %v, returned calls %v", held, + underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible)) // Writers and Close start while the extension write is held. writersStarted = true go func() { @@ -1007,3 +1030,113 @@ func TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite(t *testing.T) { t.Fatal("aborted extender left the single-flight flag set") } } + +// leaseTestClock is a test publisher clock: real time plus an offset, or a +// frozen instant. Now, Freeze, Resume and SetOffset are each one transaction +// under mu, and Now never returns an earlier time than a previous Now. +type leaseTestClock struct { + mu sync.Mutex + off time.Duration + frozen time.Time // zero = running + last time.Time +} + +func (c *leaseTestClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + t := c.frozen + if t.IsZero() { + t = time.Now().Add(c.off) + } + if t.Before(c.last) { + t = c.last + } + c.last = t + return t +} + +// Freeze stops the clock at its current reading. +func (c *leaseTestClock) Freeze() { + c.mu.Lock() + defer c.mu.Unlock() + if c.frozen.IsZero() { + c.frozen = time.Now().Add(c.off) + if c.frozen.Before(c.last) { + c.frozen = c.last + } + } +} + +// Resume restarts a frozen clock from its frozen instant. +func (c *leaseTestClock) Resume() { + c.mu.Lock() + defer c.mu.Unlock() + if !c.frozen.IsZero() { + c.off = c.frozen.Sub(time.Now()) + c.frozen = time.Time{} + } +} + +func (c *leaseTestClock) SetOffset(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.off = d +} + +func underHoldCounts(u *[8]atomic.Int64, eligible []int) []int64 { + out := make([]int64, 0, len(eligible)) + for _, i := range eligible { + out = append(out, u[i].Load()) + } + return out +} + +// Readers running across freeze/resume transitions never see the test clock +// go backwards, and a resume does not jump forward over the frozen interval. +func TestLeaseTestClockMonotonicAcrossFreezeResume(t *testing.T) { + c := &leaseTestClock{} + var stop atomic.Bool + var wg sync.WaitGroup + errs := make(chan string, 8) + for r := 0; r < 4; r++ { + wg.Add(1) + go func() { + defer wg.Done() + prev := c.Now() + for !stop.Load() { + now := c.Now() + if now.Before(prev) { + select { + case errs <- fmt.Sprintf("clock went backwards: %v after %v", now, prev): + default: + } + return + } + prev = now + } + }() + } + for k := 0; k < 50; k++ { + c.Freeze() + at := c.Now() + time.Sleep(2 * time.Millisecond) + if got := c.Now(); !got.Equal(at) { + t.Fatalf("frozen clock moved: %v -> %v", at, got) + } + r0 := time.Now() + c.Resume() + got := c.Now() + // After a resume the clock advances by at most the real time since the + // resume began (no jump over the frozen interval), and never backwards. + if got.Before(at) || got.Sub(at) > time.Since(r0) { + t.Fatalf("resume moved the clock by %v (real time since resume %v)", got.Sub(at), time.Since(r0)) + } + time.Sleep(time.Millisecond) + } + stop.Store(true) + wg.Wait() + close(errs) + for e := range errs { + t.Fatal(e) + } +} From 4f5be014cafc58546827180f6fbf7a1b25031f12 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:42:29 -0800 Subject: [PATCH 6/6] test: #262 under-hold oracle with witnessed headroom; set-up and revoke/ACK on a frozen clock - The extension write is held only when every eligible volume (and the clean volume) has positive host validity at the frozen instant, read from its own renewal view; under the hold every renewal started before the writers must grant (any refusal fails). - The clock is frozen through the set-up binds (fsync writes could outlast a TTL and expire the first-bound volume before its renewer started) and from the hold until the clean volume's revoke ACK (queued behind every extension write); it then resumes from the frozen instant. - The clock unit test registers stop + a bounded join before its readers start, so every exit settles them. Co-Authored-By: Claude Opus 5.5 --- .../authority/workspace_lease_horizon_test.go | 137 ++++++++++++++---- 1 file changed, 105 insertions(+), 32 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 56ad9facd5..2a43a9c5b9 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -616,7 +616,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { lastEpoch := map[string]uint64{} var extensions atomic.Int64 heldEntered, heldRelease := make(chan struct{}), make(chan struct{}) - var holdOnce, releaseOnce sync.Once + var releaseOnce sync.Once // The publisher clock is frozen while the extension write is held (#247 // hang): the held write holds p.mu, so every other volume's extender queues // and no horizon can move. With a running clock a late test goroutine could @@ -624,19 +624,53 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // progress condition never holds), or before the writers run after the // release (a revoke ACK finds the lease expired). This test is about lock // and store ordering, not about lease expiry. - // At the release the clock resumes from the frozen instant, so it neither - // jumps over a horizon nor runs backwards; extensions then run in real time - // alongside writers and Close. Now/Freeze/Resume are one transaction each. + // The clock stays frozen after the release until the clean volume's revoke + // ACK: the endpoint refreshes, the revocation and the ACK queue on p.mu + // behind every volume's extension write (fsync), which on a loaded machine + // can outlast the clean volume's grant, and a revoking lease is never + // extended (in-time ACK has its own tests). The writer then resumes the + // clock from the frozen instant, so it neither jumps over a horizon nor runs + // backwards; extensions run in real time alongside the moves and Close. + // Now/Freeze/Resume are one transaction each. clock := &leaseTestClock{} releaseHold := func() { - releaseOnce.Do(func() { - clock.Resume() - close(heldRelease) - }) + releaseOnce.Do(func() { close(heldRelease) }) } var classifying atomic.Bool var holding atomic.Bool // set when the extension write is held, before it blocks var heldVol atomic.Value // string: the volume whose extension write is held + var holdTaken atomic.Bool + var holdMu sync.Mutex + var skippedHolds atomic.Int64 // extension writes not held: some eligible volume lacked headroom + var p *Publisher + // headroom witnesses, at the frozen instant and from each volume's own + // renewal view (the fields RenewWorkspaceLease reads, under the leaf + // leaseMu), that a renewal of every eligible volume and of the clean volume + // grants positive host validity: lease present and live, durable horizon + // minus half the skew after now, and now before the granted deadline. The + // frozen clock and the queued extenders keep it so for the whole hold and, + // for the clean volume, through its revocation and ACK. + var noHeadroom atomic.Value // string: the last volume found without headroom, and why + headroom := func() bool { + now := clock.Now().UnixNano() + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + for _, i := range append(append([]int{}, eligible...), cleanVol) { // the clean volume is revoked and ACKed frozen + lv := p.leaseViews[vol(i)] + if lv == nil || !lv.d.bound || !lv.d.leasePresent || lv.d.revoking || lv.d.movePending || + lv.d.uncertain || lv.d.storeless || lv.d.horizon-lv.d.maxSkewNS/2 <= now || now >= lv.deadline.UnixNano() { + why := "no view" + if lv != nil { + why = fmt.Sprintf("bound=%v present=%v revoking=%v pending=%v uncertain=%v validity=%v deadline-now=%v", + lv.d.bound, lv.d.leasePresent, lv.d.revoking, lv.d.movePending, lv.d.uncertain, + time.Duration(lv.d.horizon-lv.d.maxSkewNS/2-now), time.Duration(lv.deadline.UnixNano()-now)) + } + noHeadroom.Store(vol(i) + ": " + why) + return false + } + } + return true + } hs.setBefore(func(r DurableRecord) error { time.Sleep(5 * time.Millisecond) // a slow store if !classifying.Load() || r.Workspace == nil || r.Workspace.Lease == nil { @@ -653,9 +687,21 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { if ext { extensions.Add(1) first := false - holdOnce.Do(func() { first = true }) + if !holdTaken.Load() { + holdMu.Lock() + if !holdTaken.Load() { + clock.Freeze() + if headroom() { + holdTaken.Store(true) + first = true + } else { + clock.Resume() // try again at a later extension write + skippedHolds.Add(1) + } + } + holdMu.Unlock() + } if first { - clock.Freeze() heldVol.Store(r.VolumeID) // the volume whose extension write is held holding.Store(true) // before the hold: a renewal started after this saw it close(heldEntered) @@ -668,11 +714,16 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // is granted at offset -10 s, so by offset 0 its horizon + skew barrier has // passed; the clock only moves forward. clock.SetOffset(-10 * time.Second) - p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, clock.Now)) + p = NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, clock.Now)) t.Cleanup(p.CloseWorkspaceExtenders) ctx := context.Background() bindAndGrant(t, p, vol(forcedVol), "r") // never renewed again clock.SetOffset(0) + // Set-up writes are real store writes (fsync): on a loaded machine binding + // the volumes can take longer than a TTL, and the first-bound volume would + // expire before its renewer starts (by design it never recovers). The clock + // stays frozen through the set-up and resumes just before the renewers. + clock.Freeze() for i := 0; i < n; i++ { if i != forcedVol { bindAndGrant(t, p, vol(i), "r") @@ -682,12 +733,14 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { st := p.WorkspaceState(vol(i)) lastH[vol(i)], lastEpoch[vol(i)] = st.Lease.ExpiresAtNS, st.Lease.Epoch } + clock.Resume() classifying.Store(true) var grants [n]atomic.Int64 var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held var returnedUnderHold [n]atomic.Int64 // calls (any outcome) that started while the extension write was held - var otherRefusals atomic.Value // string: a refusal under the hold that is not horizon exhaustion + var refusedUnderHold atomic.Value // string: a refusal of a call started under the hold, before the writers + var writersGo atomic.Bool // set before the writers start var maxGrant [n]atomic.Int64 var slowest atomic.Int64 stop := make(chan struct{}) @@ -701,6 +754,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // every worker, and only then let the fixtures close. t.Cleanup(func() { releaseHold() + clock.Resume() stopRenewers() settled := make(chan struct{}) go func() { wg.Wait(); close(settled) }() @@ -735,6 +789,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { default: } fresh := holding.Load() // the call starts while the extension write is held + beforeWriters := !writersGo.Load() start := time.Now() l, err := p.RenewWorkspaceLease(ctx, vol(i), "r", 1) if d := int64(time.Since(start)); d > slowest.Load() { @@ -742,12 +797,11 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { } if fresh { returnedUnderHold[i].Add(1) - // With the clock frozen and every extension queued behind the - // held write, a horizon left without host validity is refused - // by design; any other refusal here is a failure. - if err != nil && !strings.Contains(err.Error(), "leaves no host validity") && - !strings.Contains(err.Error(), "expired or revoking") { - otherRefusals.CompareAndSwap(nil, fmt.Sprintf("%s: %v", vol(i), err)) + // Headroom was witnessed at the frozen instant: until the + // writers start, every such renewal must grant (any refusal, + // a horizon error included, fails). + if beforeWriters && (err != nil || l.Revoking) { + refusedUnderHold.CompareAndSwap(nil, fmt.Sprintf("%s: %+v %v", vol(i), l, err)) } } if err == nil && !l.Revoking { @@ -770,23 +824,27 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { select { case <-heldEntered: // renewers keep triggering extensions case <-time.After(30 * time.Second): - t.Fatal("no extension write was held within 30 s") + nh, _ := noHeadroom.Load().(string) + t.Fatalf("no extension write was held within 30 s (%d extension writes, %d not held for lack of headroom; last: %s)", + extensions.Load(), skippedHolds.Load(), nh) } // A late test goroutine (machine load), longer than a horizon (1.5 x TTL): // with the clock frozen under the hold, no volume can lose its lease here. time.Sleep(3500 * time.Millisecond) - // Handshake 2: renewals never wait for the held store write (#205). - // Progress, no timer (#227): every eligible volume has a call that STARTED - // while the extension write was held and returned (a reply computed before + // Handshake 2: renewals keep succeeding while it is held. + // Progress, no timer (#227): every eligible volume gains a grant from a call + // that STARTED while the extension write was held (a reply computed before // the hold does not count); renewals that waited for it would never return. - // Grants under the hold are clamped to each volume's durable horizon: under - // the frozen clock a volume whose horizon leaves no host validity is refused - // by design, so grants are reported, and only horizon refusals are allowed. + // The hold was taken only with headroom witnessed for every eligible volume + // at the frozen instant, so no refusal is allowed here. held, _ := heldVol.Load().(string) for give := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) { + if r, _ := refusedUnderHold.Load().(string); r != "" { + t.Fatalf("under the held extension of %s, with headroom witnessed: refused %s", held, r) + } all := true for _, i := range eligible { - if returnedUnderHold[i].Load() == 0 { + if underHold[i].Load() == 0 { all = false } } @@ -798,12 +856,10 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible)) } } - if r, _ := otherRefusals.Load().(string); r != "" { - t.Fatalf("under the held extension of %s: refusal other than horizon exhaustion: %s", held, r) - } - t.Logf("under the held extension of %s: grants %v, returned calls %v", held, - underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible)) + t.Logf("under the held extension of %s (%d extension writes not held for lack of headroom): grants %v", held, + skippedHolds.Load(), underHoldCounts(&underHold, eligible)) // Writers and Close start while the extension write is held. + writersGo.Store(true) writersStarted = true go func() { for k := 0; k < 5; k++ { @@ -812,11 +868,16 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { return } } + // Still frozen since the hold (the refreshes above needed p.mu, which the + // held write owned); the clean volume's headroom was witnessed then. if err := p.BeginWorkspaceRevocation(ctx, vol(cleanVol), "r", 1); err != nil { + clock.Resume() writersDone <- fmt.Errorf("revocation: %w", err) return } - if err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil { + err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}) + clock.Resume() + if err != nil { writersDone <- fmt.Errorf("ack: %w", err) return } @@ -1098,6 +1159,18 @@ func TestLeaseTestClockMonotonicAcrossFreezeResume(t *testing.T) { var stop atomic.Bool var wg sync.WaitGroup errs := make(chan string, 8) + // Registered before launch: every exit, a Fatal included, stops and joins + // the readers (bounded). + t.Cleanup(func() { + stop.Store(true) + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(10 * time.Second): + t.Error("clock readers did not settle") + } + }) for r := 0; r < 4; r++ { wg.Add(1) go func() {