Files
seaweedfs/weed/server/master_grpc_server_collection_test.go
T
Chris LuandClaude Opus 5.5 f2e9e49842 master: stop volume growth from leaking volumes into a just-deleted collection (#13035)
* topology: stop a grow once a delete fences its collection

A grow request creates its volumes one after another and resolves the
collection by name for each, so once the collection was deleted the rest of
the request recreated it. The request now keeps the collection it started
in and holds a per-collection fence shared while it creates each volume. A
delete can raise the fence exclusively, which waits out the volume in
flight, and the request stops at its next volume. A collection dropped only
because its last layout emptied is followed to the one published under its
name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: fence volume growth before deleting a collection

The delete listed the collection's servers, fanned out DeleteCollection, and
only then dropped the collection from the topology. A grow still running
created its next volumes during or after the fan-out, on servers that had
already been cleaned or were not in the list, and those volumes registered a
new layout for the deleted collection that nothing removed. A bucket deleted
right after its first write leaked most of its initial volumes this way.

The delete now raises the collection's growth fence first, so the volume in
flight registers and is deleted with the rest, and the grow stops. A failed
fan-out lifts the fence, since the collection stays in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: refuse assigns from a collection being deleted

The delete waits for the volume a grow is creating before it lists the
collection's servers, and the collection's writable volumes stayed
assignable meanwhile, so a write could land in a volume about to be
deleted. The delete now raises the fence before it waits, and assigns
check it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: list only collections that hold a volume layout

A grow request publishes its collection before its first volume
registers, so one that created nothing left a collection with no
volume in the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: queue no grow for a collection being deleted

PickForWrite returned the layout's shouldGrow before it checked the
fence, so an assign on an empty layout of a collection being deleted
still queued a grow. That grow could run after the delete finished and
recreate the collection. Check the fence right after the pick, before
any early return.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: keep an emptied collection published while growth holds it

DeleteLayout unpublished a collection as soon as its last layout
emptied, even while a grow held it or a delete had fenced it. The
volume in flight then registered by name into a new collection that
the delete never listed servers for, and the delete's final
DeleteCollection dropped it from the topology while it stayed on disk.
Unpublish an empty collection only when no grow or delete holds it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: fence the collection still published under the name

An emptied-layout cleanup that passed its fence check could unpublish the
collection while the delete waited to fence it. The delete then fenced and
listed an orphaned object, while growth published a new collection under
the name that no fence held. Topology.FenceGrowth re-checks publication
once the fence is up and moves to the collection published since.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: run one delete of a collection at a time

Two deletes of one collection both fenced it and fanned out by name. Once
the first removed it, a write could recreate the collection, and the
second delete removed the new one's volumes and topology entry.
FenceGrowth now waits for a delete already running on the collection and
finds nothing once that delete removed it; a delete that failed hands
the collection to the one waiting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: stop a delete another delete beat to the collection

A delete that fenced the collection but had not yet checked that it was
still published retried when it was not, for the collection an emptied
layout drops. A delete that removed it in between also left it
unpublished, so the retry fenced and returned the collection a write had
recreated under the name since. finish(true) now marks the collection
deleted before it unpublishes it, and the retry stops at that mark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: keep the name fenced through the EC pass of a delete

The normal pass unpublished the collection and let growth back in before
the EC pass ran. The EC pass deletes by name on every server holding the
collection's shards, and DeleteCollection on a server also drops its
normal volumes, so a write recreating the bucket in between could land a
volume that the EC pass then deleted. A second delete of the name, finding
no collection, also ran its own EC pass by name.

deleteCollection now fences the name once, before either pass, and lifts
or ends the fence after both. finish(true) unpublishes the collection then.
A name with EC shards only gets an empty collection to fence, so an assign
under it is refused too, and a delete that finds nothing skips both passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: wait for the second delete's lock instead of sleeping

The overlapping-delete tests slept before acting on the first delete. A
second delete scheduled late started after the collection was replaced, or
after the first delete was already over, so the tests could fail or pass
without the overlap they check. They now wait until the second delete is
blocked on the delete lock, read from the goroutine stacks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: empty the layout through UnRegisterVolumeLayout in the test

The test called DeleteLayout, whose signature differs in builds that key
layouts by more than replication, TTL and disk type. UnRegisterVolumeLayout
reaches the same cleanup from a VolumeInfo and has one signature everywhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:46:28 -08:00

531 lines
18 KiB
Go

package weed_server
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/seaweedfs/raft"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/sequence"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/topology"
)
// recordingVolumeServer reports what each DeleteCollection arrived carrying.
// failWith answers an error at once; hang holds the call until the caller gives
// up or the test releases it, the way a server that is still reachable but
// wedged behaves.
type recordingVolumeServer struct {
volume_server_pb.UnimplementedVolumeServerServer
hang bool
failWith error
calls chan deleteCollectionCall
release chan struct{}
releaseOnce sync.Once
}
type deleteCollectionCall struct {
collection string
// budget is the time the RPC arrived with, or 0 when it carried no deadline.
budget time.Duration
}
func newRecordingVolumeServer() *recordingVolumeServer {
return &recordingVolumeServer{
calls: make(chan deleteCollectionCall, 8),
release: make(chan struct{}),
}
}
func (s *recordingVolumeServer) DeleteCollection(ctx context.Context, req *volume_server_pb.DeleteCollectionRequest) (*volume_server_pb.DeleteCollectionResponse, error) {
call := deleteCollectionCall{collection: req.Collection}
if deadline, ok := ctx.Deadline(); ok {
call.budget = time.Until(deadline)
}
s.calls <- call
if s.failWith != nil {
return nil, s.failWith
}
if s.hang {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-s.release:
}
}
return &volume_server_pb.DeleteCollectionResponse{}, nil
}
// Release unblocks every held DeleteCollection. Safe to call more than once.
func (s *recordingVolumeServer) Release() {
s.releaseOnce.Do(func() { close(s.release) })
}
// addVolumeServer publishes stub on a fresh listener and registers it as a data
// node of topo. Only the grpc port is dialed; the http port just has to stay
// distinct per server so the topology does not treat two nodes as one address.
func addVolumeServer(t *testing.T, topo *topology.Topology, id string, stub *recordingVolumeServer) *topology.DataNode {
t.Helper()
t.Cleanup(stub.Release)
grpcPort := serveGrpc(t, func(s *grpc.Server) {
volume_server_pb.RegisterVolumeServerServer(s, stub)
})
return topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1").
GetOrCreateDataNode("127.0.0.1", grpcPort-10000, grpcPort, "", id, map[string]uint32{"": 10})
}
func newCollectionTestMaster(topo *topology.Topology) *MasterServer {
return &MasterServer{
Topo: topo,
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}
}
// awaitCall waits for one DeleteCollection to reach the stub.
func awaitCall(t *testing.T, stub *recordingVolumeServer, what string) deleteCollectionCall {
t.Helper()
select {
case call := <-stub.calls:
return call
case <-time.After(15 * time.Second):
t.Fatalf("%s: the volume server never received DeleteCollection", what)
return deleteCollectionCall{}
}
}
// A caller with no deadline of its own must still not wait forever: the master
// has to bound each RPC, or one wedged volume server holds the fan-out open with
// nothing to end it.
func TestDoDeleteNormalCollectionBoundsEachVolumeServerRPC(t *testing.T) {
const collection = "bucket-a"
stub := newRecordingVolumeServer()
stub.hang = true
topo := topology.NewTopology("test", nil, 32*1024, 5, false)
dn := addVolumeServer(t, topo, "vs1", stub)
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{
{Id: 1, Collection: collection, Version: 3},
}, dn)
ms := newCollectionTestMaster(topo)
done := make(chan error, 1)
go func() { done <- ms.deleteCollection(context.Background(), collection) }()
call := awaitCall(t, stub, "bounded RPC")
if call.budget <= 0 {
t.Fatal("DeleteCollection reached the volume server with no deadline: a wedged server holds the fan-out open with nothing to end it")
}
if call.budget > deleteCollectionTimeout {
t.Errorf("DeleteCollection budget = %v, want at most deleteCollectionTimeout %v", call.budget, deleteCollectionTimeout)
}
stub.Release()
select {
case err := <-done:
if err != nil {
t.Errorf("deleteCollection returned %v, want nil once the volume server answers", err)
}
case <-time.After(15 * time.Second):
t.Fatal("deleteCollection did not return after the volume server answered")
}
}
// The fan-out must outlive the caller. A collection can span many servers and
// the deletes are sequential, so letting an inbound cancellation end the loop
// would abandon a large delete part-done, with volumes left behind and no
// request still running to come back for them.
func TestDeleteCollectionOutlivesTheCallersCancellation(t *testing.T) {
const collection = "bucket-b"
normal := newRecordingVolumeServer()
ec := newRecordingVolumeServer()
topo := topology.NewTopology("test", nil, 32*1024, 5, false)
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{
{Id: 1, Collection: collection, Version: 3},
}, addVolumeServer(t, topo, "vs-normal", normal))
topo.SyncDataNodeEcShards([]*master_pb.VolumeEcShardInformationMessage{
{Id: 9, Collection: collection, EcIndexBits: 0x1f},
}, addVolumeServer(t, topo, "vs-ec", ec))
ms := newCollectionTestMaster(topo)
// The caller is already gone by the time the delete starts.
expired, cancel := context.WithCancel(context.Background())
cancel()
if err := ms.deleteCollection(expired, collection); err != nil {
t.Fatalf("deleteCollection returned %v; a cancelled caller must not fail the fan-out", err)
}
// The EC pass runs second, so it is the one most likely to find the caller
// already gone.
for _, tc := range []struct {
stub *recordingVolumeServer
what string
}{{normal, "normal pass"}, {ec, "ec pass"}} {
call := awaitCall(t, tc.stub, "cancelled caller, "+tc.what)
if call.collection != collection {
t.Errorf("%s: server was told to delete %q, want %q", tc.what, call.collection, collection)
}
if call.budget <= 0 {
t.Errorf("%s: DeleteCollection arrived with no deadline; each RPC should still be bounded", tc.what)
}
}
if _, found := topo.FindCollection(collection); found {
t.Error("the collection was left in the topology; the delete did not run to completion")
}
}
// ListVolumeServers reports a node once per replica it holds. DeleteCollection
// removes the whole collection from the server it reaches, so the master must
// send it once per server, not once per replica.
func TestDoDeleteNormalCollectionSendsOneRPCPerVolumeServer(t *testing.T) {
const collection = "bucket-c"
stub := newRecordingVolumeServer()
topo := topology.NewTopology("test", nil, 32*1024, 5, false)
dn := addVolumeServer(t, topo, "vs1", stub)
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{
{Id: 1, Collection: collection, Version: 3},
{Id: 2, Collection: collection, Version: 3},
{Id: 3, Collection: collection, Version: 3},
}, dn)
collectionInTopology, found := topo.FindCollection(collection)
if !found {
t.Fatalf("test setup: collection %s was not registered", collection)
}
if listed := len(collectionInTopology.ListVolumeServers()); listed < 2 {
t.Fatalf("test setup: the one node is listed %d times, expected once per replica", listed)
}
ms := newCollectionTestMaster(topo)
if err := ms.deleteCollection(context.Background(), collection); err != nil {
t.Fatalf("deleteCollection: %v", err)
}
awaitCall(t, stub, "one RPC per server")
select {
case extra := <-stub.calls:
t.Errorf("the same server was told to delete %q more than once", extra.collection)
default:
}
}
// One server refusing must not leave the collection on every server after it in
// the list: returning at the first failure meant a single node that was down
// stranded the rest, and the failure is reported either way.
func TestDoDeleteNormalCollectionKeepsGoingPastAFailingServer(t *testing.T) {
const collection = "bucket-d"
failing := newRecordingVolumeServer()
failing.failWith = errors.New("volume server is out of disk")
healthy := newRecordingVolumeServer()
topo := topology.NewTopology("test", nil, 32*1024, 5, false)
failingNode := addVolumeServer(t, topo, "vs-failing", failing)
healthyNode := addVolumeServer(t, topo, "vs-healthy", healthy)
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{
{Id: 1, Collection: collection, Version: 3},
}, failingNode)
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{
{Id: 1, Collection: collection, Version: 3},
}, healthyNode)
ms := newCollectionTestMaster(topo)
if err := ms.deleteCollection(context.Background(), collection); err == nil {
t.Fatal("deleteCollection reported success while a server refused")
}
awaitCall(t, failing, "failing server")
awaitCall(t, healthy, "server behind the failing one")
if _, found := topo.FindCollection(collection); !found {
t.Error("the collection was dropped from the topology despite failing; nothing would come back for the rest")
}
}
// A collection can hold normal volumes and EC shards at once. Returning after a
// failed normal pass left the EC shards in place with no request left to come
// back for them, so both passes have to run.
func TestDeleteCollectionRunsTheEcPassWhenTheNormalPassFails(t *testing.T) {
const collection = "bucket-e"
normal := newRecordingVolumeServer()
normal.failWith = errors.New("volume server is out of disk")
ec := newRecordingVolumeServer()
topo := topology.NewTopology("test", nil, 32*1024, 5, false)
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{
{Id: 1, Collection: collection, Version: 3},
}, addVolumeServer(t, topo, "vs-normal", normal))
topo.SyncDataNodeEcShards([]*master_pb.VolumeEcShardInformationMessage{
{Id: 9, Collection: collection, EcIndexBits: 0x1f},
}, addVolumeServer(t, topo, "vs-ec", ec))
ms := newCollectionTestMaster(topo)
if err := ms.deleteCollection(context.Background(), collection); err == nil {
t.Fatal("deleteCollection reported success while the normal pass failed")
}
// The failure is reported, and the EC shards are cleaned up anyway.
awaitCall(t, ec, "ec pass after a failed normal pass")
if _, found := topo.FindCollection(collection); !found {
t.Error("the normal collection was dropped from the topology despite failing; nothing would retry it")
}
}
// growingVolumeServer keeps the volumes AllocateVolume creates until
// DeleteCollection drops them. The holdAt-th allocation, counted from 1, waits
// for release before it creates its volume, and the holdDeleteAt-th
// DeleteCollection waits for deleteRelease before it drops any.
type growingVolumeServer struct {
volume_server_pb.UnimplementedVolumeServerServer
holdAt int
held chan struct{}
release chan struct{}
holdDeleteAt int
deleteHeld chan struct{}
deleteRelease chan struct{}
mu sync.Mutex
allocations int
deletes int
volumes map[uint32]string
}
func (s *growingVolumeServer) AllocateVolume(ctx context.Context, req *volume_server_pb.AllocateVolumeRequest) (*volume_server_pb.AllocateVolumeResponse, error) {
s.mu.Lock()
s.allocations++
hold := s.allocations == s.holdAt
s.mu.Unlock()
if hold {
close(s.held)
<-s.release
}
s.mu.Lock()
s.volumes[req.VolumeId] = req.Collection
s.mu.Unlock()
return &volume_server_pb.AllocateVolumeResponse{}, nil
}
func (s *growingVolumeServer) DeleteCollection(ctx context.Context, req *volume_server_pb.DeleteCollectionRequest) (*volume_server_pb.DeleteCollectionResponse, error) {
s.mu.Lock()
s.deletes++
hold := s.deletes == s.holdDeleteAt
s.mu.Unlock()
if hold {
close(s.deleteHeld)
<-s.deleteRelease
}
s.mu.Lock()
defer s.mu.Unlock()
for vid, collection := range s.volumes {
if collection == req.Collection {
delete(s.volumes, vid)
}
}
return &volume_server_pb.DeleteCollectionResponse{}, nil
}
// growthRaftServer answers as leader and applies the volume id bound growth asks for.
type growthRaftServer struct {
raft.Server
topo *topology.Topology
}
func (growthRaftServer) State() string { return raft.Leader }
func (s growthRaftServer) Do(c raft.Command) (interface{}, error) {
if command, ok := c.(*topology.MaxVolumeIdCommand); ok {
s.topo.UpAdjustMaxVolumeId(command.MaxVolumeId)
}
return nil, nil
}
// A bucket's first write starts a grow of several volumes, and the bucket can be
// deleted before that grow is done. The volumes created after the delete
// recreated the collection and were never removed.
func TestDeleteCollectionStopsAGrowInFlight(t *testing.T) {
const collection = "bucket-g"
stub := &growingVolumeServer{
holdAt: 2,
held: make(chan struct{}),
release: make(chan struct{}),
volumes: make(map[uint32]string),
}
releaseOnce := sync.OnceFunc(func() { close(stub.release) })
t.Cleanup(releaseOnce)
topo := topology.NewTopology("test", sequence.NewMemorySequencer(), 32*1024, 5, false)
topo.RaftServer = growthRaftServer{topo: topo}
grpcPort := serveGrpc(t, func(s *grpc.Server) {
volume_server_pb.RegisterVolumeServerServer(s, stub)
})
topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1").
GetOrCreateDataNode("127.0.0.1", grpcPort-10000, grpcPort, "", "vs1", map[string]uint32{"": 10})
ms := newCollectionTestMaster(topo)
rp, _ := super_block.NewReplicaPlacementFromString("000")
option := &topology.VolumeGrowOption{
Collection: collection,
ReplicaPlacement: rp,
Ttl: needle.EMPTY_TTL,
Version: uint32(needle.GetCurrentVersion()),
}
grown := make(chan struct{})
go func() {
defer close(grown)
topology.NewDefaultVolumeGrowth().GrowByCountAndType(ms.grpcDialOption, 7, option, topo)
}()
select {
case <-stub.held:
case <-time.After(15 * time.Second):
t.Fatal("the grow never reached its second volume")
}
deleted := make(chan error, 1)
go func() { deleted <- ms.deleteCollection(context.Background(), collection) }()
// The delete waits for the volume being created rather than racing it.
time.Sleep(200 * time.Millisecond)
stub.mu.Lock()
early := stub.deletes
stub.mu.Unlock()
if early != 0 {
t.Error("the delete reached the volume server while the grow was still creating a volume")
}
releaseOnce()
select {
case <-grown:
case <-time.After(15 * time.Second):
t.Fatal("the grow did not finish")
}
select {
case err := <-deleted:
if err != nil {
t.Fatalf("deleteCollection: %v", err)
}
case <-time.After(15 * time.Second):
t.Fatal("the delete did not finish")
}
stub.mu.Lock()
left := len(stub.volumes)
stub.mu.Unlock()
if left != 0 {
t.Errorf("%d volumes of the deleted collection are left on the volume server", left)
}
if _, found := topo.FindCollection(collection); found {
t.Error("the grow recreated the deleted collection in the topology")
}
}
// The EC pass deletes by name after the normal pass, on servers that can also
// hold normal volumes, so the name stays fenced until both passes are done: a
// write recreating the bucket in between would place a volume the EC pass then
// deletes. A second delete of the name waits, then finds nothing left to do.
func TestDeleteCollectionKeepsTheNameFencedThroughTheEcPass(t *testing.T) {
const collection = "bucket-h"
stub := &growingVolumeServer{
holdDeleteAt: 2,
deleteHeld: make(chan struct{}),
deleteRelease: make(chan struct{}),
volumes: map[uint32]string{1: collection},
}
releaseOnce := sync.OnceFunc(func() { close(stub.deleteRelease) })
t.Cleanup(releaseOnce)
topo := topology.NewTopology("test", sequence.NewMemorySequencer(), 32*1024, 5, false)
topo.RaftServer = growthRaftServer{topo: topo}
grpcPort := serveGrpc(t, func(s *grpc.Server) {
volume_server_pb.RegisterVolumeServerServer(s, stub)
})
dn := topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1").
GetOrCreateDataNode("127.0.0.1", grpcPort-10000, grpcPort, "", "vs1", map[string]uint32{"": 10})
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{
{Id: 1, Collection: collection, Version: 3},
}, dn)
topo.SyncDataNodeEcShards([]*master_pb.VolumeEcShardInformationMessage{
{Id: 9, Collection: collection, EcIndexBits: 0x1f},
}, dn)
ms := newCollectionTestMaster(topo)
rp, _ := super_block.NewReplicaPlacementFromString("000")
grow := func() error {
_, err := topology.NewDefaultVolumeGrowth().GrowByCountAndType(ms.grpcDialOption, 1, &topology.VolumeGrowOption{
Collection: collection,
ReplicaPlacement: rp,
Ttl: needle.EMPTY_TTL,
Version: uint32(needle.GetCurrentVersion()),
}, topo)
return err
}
first := make(chan error, 1)
go func() { first <- ms.deleteCollection(context.Background(), collection) }()
select {
case <-stub.deleteHeld:
case <-time.After(15 * time.Second):
t.Fatal("the EC pass never reached the volume server")
}
if err := grow(); err == nil {
t.Error("a grow under the name went ahead while the EC pass was deleting it")
}
second := make(chan error, 1)
go func() { second <- ms.deleteCollection(context.Background(), collection) }()
waitForLockWaiter(t, "(*Topology).FenceGrowth")
releaseOnce()
for _, done := range []chan error{first, second} {
select {
case err := <-done:
if err != nil {
t.Fatalf("deleteCollection: %v", err)
}
case <-time.After(15 * time.Second):
t.Fatal("a delete did not finish")
}
}
stub.mu.Lock()
allocations, deletes, left := stub.allocations, stub.deletes, len(stub.volumes)
stub.mu.Unlock()
if allocations != 0 {
t.Errorf("%d volumes were created under the name while it was being deleted", allocations)
}
if deletes != 2 {
t.Errorf("the volume server got %d DeleteCollection calls, want 2: the second delete came back after the first removed the collection", deletes)
}
if left != 0 {
t.Errorf("%d volumes of the deleted collection are left on the volume server", left)
}
if _, found := topo.FindCollection(collection); found {
t.Error("the collection is still in the topology after the delete")
}
if err := grow(); err != nil {
t.Errorf("a grow under the name failed once the delete was done: %v", err)
}
}