Files
seaweedfs/weed/wdclient/filer_client_breaker_test.go
T
0a1e337302 wdclient: keep a volume's live replicas readable while another volume cannot be found (#12814)
* wdclient: keep a volume's live replicas readable while another volume cannot be found

A filer's "volume not found" answer counted as a filer failure, so three
of them opened the circuit breaker on a healthy filer. With its only filer
in the cool-down, every lookup then failed without asking, as "all 1
filer(s) failed with non-retryable error: %!w(<nil>)". And a refresh whose
lookup failed left the cache without the volume's live replicas, since
InvalidateCache had already dropped them with the dead one.

The breaker now counts only failures to reach the filer, and asks the
filers anyway when all of them are in their cool-down. InvalidateCache keeps
what it removed; a lookup that errors puts it back unless the volume was
learned again, the epoch moved, or a reset would have expired it, and
leaves out locations fenced by a pushed removal.

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

* wdclient: set invalidated locations aside in the map instead of copying them out

The first commit kept what InvalidateCache removed in a side map and put it
back when the lookup failed. The copy left the map's lock, so a removal the
master pushed between the take and the put-back was undone: the removed
server came back into the cache.

The entry now stays in the map with a state. entryStale hides it from readers
and releases its server references, as a delete did. A pushed removal edits
it like any other entry. When the lookup after the invalidation returns an
error, the entry becomes entryRevived and is served again.

A stale or revived entry holds only what was known before the read failed,
so the next thing learned replaces it: a lookup answer drops it before the
answer is cached, including an answer with no locations and an answer to a
lookup that was in flight when another one failed, and a pushed add replaces
it instead of merging.

LookupVolumeIdsWithFallback returns no error when every volume it was asked
for has locations after the revive, so the filer's LookupVolume handler sends
its response instead of an error status.

The not-found breaker test now checks the failure count itself. Without
that, a regression of the classification passed, because a lone filer in its
cool-down is asked anyway.

On the first commit, TestPushedRemovalRacingFailedRefreshes failed in 8 of 8
runs under -race: four with "got [live:8080 old:8080], want [live:8080]",
four with "got [], want [live:8080]".

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* wdclient: retry a filer lookup pass that asked no filer

The pass decides once whether to skip unhealthy filers. A filer whose
breaker trips after that decision, as when a concurrent lookup records
its failure, is still skipped. With every filer skipped the pass ended
with no error and failed the lookup as non-retryable with
"%!w(<nil>)". Such a pass now counts as Unavailable, so the lookup
retries and the next pass asks the filers anyway.

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

* wdclient: believe a provider answer that reports errors for some volumes

The master provider answers a batch with a map of the volumes it knows
and an error naming the ones it does not. The failed-lookup branch took
that as no answer and revived what InvalidateCache had set aside, so a
volume the master reported as absent came back with its old locations,
and the batch could return them with a nil error. Only a nil map now
means no answer. Otherwise the answer replaces what was set aside, and
the provider's error is still returned.

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

* wdclient: keep set-aside locations learned after a lookup was asked

A successful lookup dropped every stale or revived entry of the volumes
it asked for, however old the answer was. A lookup asked before the
master confirmed new locations could, on finishing, delete those
locations after a read had set them aside and a failed refresh had
revived them, and its own answer was not cached because the epoch had
moved. Entries now record when their locations were learned, and an
answer drops only what was learned before it was asked.

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

* wdclient: keep an older answer from replacing locations set aside after it was asked

fdcde25 keeps dropSetAside from deleting set-aside locations that were
learned after a lookup was asked. The answer's insertion still replaced
them: fillLocations adds each location with vidMap.addLocation, and
addLocationToMap replaces a stale or revived entry whatever its learnedAt.
The epoch does not stop this when the newer locations came from another
lookup's answer or, on the master client, from a pushed add, since neither
moves it. The master client's provider also caches its answer itself,
before LookupVolumeIdsWithFallback reaches dropSetAside.

vidMap.addAnswer adds an answer's locations under one lock, and adds none
of them while vid has a stale or revived entry learned after the lookup was
asked. fillLocations uses it, and the master client's provider passes the
learned mark it takes next to its epoch. An answer with nothing newer in the
way still replaces what was set aside, with every location it reports.

On fdcde25, TestOlderAnswerDoesNotReplaceNewerRevivedLocations and the
"newer location revived during the lookup" case of
TestMasterAnswerAgainstSetAsideLocations fail with
"got [old:8080], want [new:8080]".

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

* wdclient: move addAnswer next to dropSetAside

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-19 22:34:35 -08:00

176 lines
6.5 KiB
Go

package wdclient
import (
"context"
"fmt"
"net"
"sync"
"sync/atomic"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// lookupFiler answers LookupVolume the way a filer does: volumes it knows get
// their locations, any other volume fails the call with the master's error.
// While unavailable is set it fails every call as an unreachable filer would.
type lookupFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
known map[string]string // volume id -> volume server url
unavailable atomic.Bool
calls atomic.Int32
}
func (f *lookupFiler) LookupVolume(ctx context.Context, req *filer_pb.LookupVolumeRequest) (*filer_pb.LookupVolumeResponse, error) {
f.calls.Add(1)
if f.unavailable.Load() {
return nil, status.Error(codes.Unavailable, "filer restarting")
}
resp := &filer_pb.LookupVolumeResponse{LocationsMap: make(map[string]*filer_pb.Locations)}
for _, vid := range req.VolumeIds {
url, found := f.known[vid]
if !found {
return nil, fmt.Errorf("provider lookup failed: master volume lookup errors: volume %s: volume id %s not found", vid, vid)
}
resp.LocationsMap[vid] = &filer_pb.Locations{Locations: []*filer_pb.Location{{Url: url, PublicUrl: url}}}
}
return resp, nil
}
func startLookupFiler(t *testing.T, f *lookupFiler) pb.ServerAddress {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(srv, f)
go srv.Serve(lis)
t.Cleanup(srv.Stop)
return pb.ServerAddress(fmt.Sprintf("127.0.0.1:1.%d", lis.Addr().(*net.TCPAddr).Port))
}
func newBreakerTestClient(t *testing.T, addr pb.ServerAddress) *FilerClient {
t.Helper()
fc := NewFilerClient([]pb.ServerAddress{addr}, grpc.WithTransportCredentials(insecure.NewCredentials()), "", &FilerClientOption{
GrpcTimeout: 2 * time.Second,
InitialRetryWait: time.Millisecond,
ResetTimeout: time.Minute, // longer than the test, so an open breaker stays open
})
t.Cleanup(fc.Close)
return fc
}
// A volume the master has no location for is an answer from the filer, not a
// sign the filer is down. Before the fix the third such answer opened the
// breaker, and every lookup of the next 30 seconds failed without asking the
// filer, including lookups of volumes whose other replica was serving.
func TestFilerNotFoundAnswersDoNotOpenBreaker(t *testing.T) {
filer := &lookupFiler{known: map[string]string{"8": "10.0.0.8:8080"}}
fc := newBreakerTestClient(t, startLookupFiler(t, filer))
ctx := context.Background()
for i := 0; i < 5; i++ {
if _, err := fc.LookupFileIdWithFallback(ctx, "7,0102"); err == nil {
t.Fatalf("lookup %d of volume 7 succeeded, want not found", i)
}
}
// Checked on its own: with the breaker open, the lookup below would
// still succeed, because a lone filer in its cool-down is asked anyway.
if n := atomic.LoadInt32(&fc.filerHealth[0].failureCount); n != 0 {
t.Fatalf("not-found answers counted as %d filer failures", n)
}
urls, err := fc.LookupFileIdWithFallback(ctx, "8,0102")
if err != nil {
t.Fatalf("volume 8 after not-found answers for volume 7: %v", err)
}
if len(urls) != 1 || urls[0] != "http://10.0.0.8:8080/8,0102" {
t.Fatalf("volume 8 urls = %v", urls)
}
}
// When every filer is in its cool-down the breaker has nowhere to steer, so
// the lookup asks them anyway instead of failing without asking anyone.
func TestOnlyFilerInCooldownIsStillAsked(t *testing.T) {
filer := &lookupFiler{known: map[string]string{"8": "10.0.0.8:8080"}}
fc := newBreakerTestClient(t, startLookupFiler(t, filer))
ctx := context.Background()
filer.unavailable.Store(true)
if _, err := fc.LookupFileIdWithFallback(ctx, "8,0102"); err == nil {
t.Fatal("lookup succeeded while the filer was unavailable")
}
if !fc.allFilersUnhealthy() {
t.Fatalf("breaker did not open after %d unavailable answers", filer.calls.Load())
}
filer.unavailable.Store(false)
before := filer.calls.Load()
if _, err := fc.LookupFileIdWithFallback(ctx, "8,0102"); err != nil {
t.Fatalf("lookup after the filer recovered: %v", err)
}
if filer.calls.Load() == before {
t.Fatal("the only filer was skipped instead of asked")
}
if fc.allFilersUnhealthy() {
t.Fatal("a successful answer did not close the breaker")
}
}
func TestFilerUnreachable(t *testing.T) {
for _, tc := range []struct {
name string
err error
want bool
}{
{"unavailable", status.Error(codes.Unavailable, "connection refused"), true},
{"deadline", status.Error(codes.DeadlineExceeded, "deadline exceeded"), true},
{"exhausted", status.Error(codes.ResourceExhausted, "too many requests"), true},
{"wrapped unavailable", fmt.Errorf("filer.LookupVolume failed: %w", status.Error(codes.Unavailable, "x")), true},
{"no status", fmt.Errorf("dial tcp: connection refused"), true},
{"answer naming a connection", fmt.Errorf("filer.LookupVolume failed: %w", status.Error(codes.Unknown, "master: connection refused")), false},
{"not found answer", status.Error(codes.Unknown, "volume id 7 not found"), false},
{"not found code", status.Error(codes.NotFound, "volume id 7 not found"), false},
} {
t.Run(tc.name, func(t *testing.T) {
if got := filerUnreachable(tc.err); got != tc.want {
t.Fatalf("filerUnreachable(%v) = %v, want %v", tc.err, got, tc.want)
}
})
}
}
// A filer can trip its breaker after the pass decided to skip unhealthy
// filers but before the pass reaches it, as when a concurrent lookup records
// its failure in between. A pass that asked nobody must be retried, not
// reported as a non-retryable failure with no error.
func TestFilerTrippedDuringPassIsRetried(t *testing.T) {
filer := &lookupFiler{known: map[string]string{"8": "10.0.0.8:8080"}}
fc := newBreakerTestClient(t, startLookupFiler(t, filer))
health := fc.filerHealth[0]
now := time.Now()
atomic.StoreInt32(&health.failureCount, fc.failureThreshold)
atomic.StoreInt64(&health.lastFailureTimeNs, now.Add(-2*fc.resetTimeout).UnixNano())
var trip sync.Once
fc.now = func() time.Time {
trip.Do(func() { atomic.StoreInt64(&health.lastFailureTimeNs, now.UnixNano()) })
return now
}
locations, err := (&filerVolumeProvider{filerClient: fc}).LookupVolumeIds(context.Background(), []string{"8"})
if err != nil {
t.Fatalf("lookup with the filer tripped mid-pass: %v", err)
}
if len(locations["8"]) != 1 || filer.calls.Load() == 0 {
t.Fatalf("locations = %v after %d filer calls", locations, filer.calls.Load())
}
}