mount: review fixes for the metadata follow shutdown (on top of #13092) (#13097)

* mount: drop the issue number from the shutdown test comment

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

* mount: end the filer walk when the consumer stopped following

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

* pb: end the follow when a retried event reports a stop

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

* mount: check the subscriber is gone before the late event can end it

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

* mount: never retry a filer call whose consumer stopped following

The walk already stopped on pb.ErrStopFollowing, but RetryOnError still
classified the wrapped error by its cause, so a transport-looking cause
reran the whole filer walk.

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

* pb: keep the cursor behind an event whose retry the follow ended

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

* mount: close the meta cache after the follow-cancel test joins it

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chris LuandClaude Opus 5.5 authored and GitHub committed 2026-11-28 16:10:26 -08:00
1 parent 63ab6c6190
commit 663af6fccb
5 files changed
+191 -27

No files matched your search

@@ -144,10 +144,9 @@ func createdEvent(name string) *filer_pb.SubscribeMetadataResponse {
}
}
// TestMountMetaSubscriberEndsWhenMetaCacheCloses reproduces issue #5289: a
// metadata event that arrives after the metadata cache was closed reached
// glog.Fatalf, so the mount aborted with a goroutine dump instead of exiting
// cleanly. glog.Fatalf cannot be intercepted from another package (glog's
// TestMountMetaSubscriberEndsWhenMetaCacheCloses: a metadata event that
// arrives after the metadata cache was closed must not reach glog.Fatalf and
// abort the mount with a goroutine dump. glog.Fatalf cannot be intercepted from another package (glog's
// logExitFunc is unexported), so the child runs in its own process and the
// parent reads the exit code: 255 is glog's fatal exit.
func TestMountMetaSubscriberEndsWhenMetaCacheCloses(t *testing.T) {
@@ -287,11 +286,21 @@ func TestMountMetaFollowCancelIsAStop(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
stopped := make(chan error, 1)
joined := make(chan struct{})
var retries atomic.Int32
go func() {
defer close(joined)
stopped <- meta_cache.SubscribeMetaEvents(ctx, wfs.metaCache, wfs.signature, wfs, nil, "/", 0, false,
func(int64, error) { retries.Add(1) })
}()
t.Cleanup(func() {
cancel()
select {
case <-joined:
wfs.metaCache.Shutdown()
case <-time.After(10 * time.Second):
}
})
select {
case <-filer.subscribed:
@@ -317,8 +326,8 @@ func TestMountMetaFollowCancelIsAStop(t *testing.T) {
// TestMountClearCacheDirStopsTheFollowFirst drives the production unmount entry
// point, so the ordering it guards cannot rot: if stopMetadataFollow is dropped
// from ClearCacheDir (or moved after metaCache.Shutdown), the follow is still
// running when the cache closes and the late event aborts the mount again.
// from ClearCacheDir, the subscriber is still running when ClearCacheDir
// returns. The late event after that must not abort the mount either.
func TestMountClearCacheDirStopsTheFollowFirst(t *testing.T) {
if os.Getenv(subscriberChildEnv) == "1" {
runClearCacheDirOrdering(t)
@@ -358,10 +367,10 @@ func runClearCacheDirOrdering(t *testing.T) {
}
wfs.ClearCacheDir()
filer.push(createdEvent("late"))
time.Sleep(500 * time.Millisecond)
if stack := metadataSubscriberStack(); stack != "" {
t.Fatalf("ClearCacheDir left the metadata subscriber running against a closed cache:\n%s", headLines(stack, 20))
}
filer.push(createdEvent("late"))
time.Sleep(500 * time.Millisecond)
}
+8 -5
View File
@@ -2,6 +2,7 @@ package mount
import (
"context"
"errors"
"fmt"
"sync/atomic"
"time"
@@ -24,10 +25,11 @@ func (wfs *WFS) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFile
}
// isRetryableFilerCall decides whether withFilerClient tries a failed call
// again. A filer verdict, such as a read-only path, is final whatever its
// message says, and the path it names can contain "transport".
// again. A filer verdict, such as a read-only path, and a consumer that
// stopped following are final whatever their message says, and the path or
// cause they name can contain "transport".
func isRetryableFilerCall(err error) bool {
return !filer_pb.IsFilerVerdict(err) && util.IsTransientError(err)
return !filer_pb.IsFilerVerdict(err) && !errors.Is(err, pb.ErrStopFollowing) && util.IsTransientError(err)
}
// withFilerClient walks the filer addresses until one answers fn. callWait
@@ -53,8 +55,9 @@ func (wfs *WFS) withFilerClient(ctx context.Context, streamingMode bool, callWai
// glog.V(0).Infof("WithFilerClient %d %v: %v", x, filerGrpcAddress, err)
// A verdict is the filer's answer, and another filer would give
// the same one. Stop here, so that a later filer's transport
// error cannot replace it and turn it into a retry.
if filer_pb.IsFilerVerdict(err) {
// error cannot replace it and turn it into a retry. A consumer
// that stopped following is done with every filer.
if filer_pb.IsFilerVerdict(err) || errors.Is(err, pb.ErrStopFollowing) {
atomic.StoreInt32(&wfs.option.filerIndex, i)
return err
}
@@ -3,6 +3,7 @@ package mount
import (
"context"
"errors"
"fmt"
"net"
"sync/atomic"
"testing"
@@ -78,3 +79,50 @@ func TestWithFilerClientKeepsTheFirstFilersVerdict(t *testing.T) {
t.Fatalf("withFilerClient took %v for a verdict", elapsed)
}
}
// A consumer that stopped following is done with every filer, so the walk must
// not open the call again on the next address.
func TestWithFilerClientStopsTheWalkOnStopFollowing(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = listener.Close() })
server := pb.NewGrpcServer()
filer_pb.RegisterSeaweedFilerServer(server, &readOnlyCreateFiler{})
go server.Serve(listener)
t.Cleanup(server.Stop)
port := listener.Addr().(*net.TCPAddr).Port
wfs := &WFS{
option: &Option{
FilerAddresses: []pb.ServerAddress{
pb.NewServerAddressWithGrpcPort("127.0.0.1:1", port),
pb.NewServerAddressWithGrpcPort("127.0.0.1:2", port),
},
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
},
}
var calls atomic.Int32
err = wfs.withFilerClient(context.Background(), true, 0, func(context.Context, filer_pb.SeaweedFilerClient) error {
calls.Add(1)
return fmt.Errorf("meta cache closed: %w", pb.ErrStopFollowing)
})
if !errors.Is(err, pb.ErrStopFollowing) {
t.Fatalf("withFilerClient error = %v, want ErrStopFollowing", err)
}
if n := calls.Load(); n != 1 {
t.Fatalf("the call ran on %d filers, want 1", n)
}
}
// A stopped follow stays final when its cause reads as a transport failure.
func TestIsRetryableFilerCallStopFollowing(t *testing.T) {
for _, cause := range []string{"transport is closing", "connection refused"} {
err := fmt.Errorf("%w: %w", pb.ErrStopFollowing, errors.New(cause))
if isRetryableFilerCall(err) {
t.Fatalf("isRetryableFilerCall(%v) = true, want false", err)
}
}
}
+27 -13
View File
@@ -159,7 +159,16 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
}()
}
handleErr := func(resp *filer_pb.SubscribeMetadataResponse, err error) {
resubscribeOr := func(err error) error {
select {
case <-option.Resubscribe:
return ErrResubscribe
default:
}
return err
}
handleErr := func(resp *filer_pb.SubscribeMetadataResponse, err error) error {
sourcePath := filer_pb.MetadataEventSourceFullPath(resp)
targetPath := filer_pb.MetadataEventTargetFullPath(resp)
switch option.EventErrorType {
@@ -170,11 +179,14 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
case RetryForeverOnError:
waitTime := time.Second
for ctx.Err() == nil {
if err := processEventFn(resp); err == nil {
break
} else {
glog.Errorf("process %s -> %s ts_ns=%d: %v", sourcePath, targetPath, resp.TsNs, err)
err := processEventFn(resp)
if err == nil {
return nil
}
if errors.Is(err, ErrStopFollowing) {
return err
}
glog.Errorf("process %s -> %s ts_ns=%d: %v", sourcePath, targetPath, resp.TsNs, err)
select {
case <-ctx.Done():
case <-time.After(waitTime):
@@ -183,11 +195,14 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
waitTime += waitTime / 2
}
}
// The follow ended before the event applied: keep the cursor behind it.
return resubscribeOr(ctx.Err())
case DontLogError:
// pass
default:
glog.Errorf("process %s -> %s ts_ns=%d: %v", sourcePath, targetPath, resp.TsNs, err)
}
return nil
}
// handleOneEvent processes a single response, whether it arrived as the
@@ -211,7 +226,9 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
if errors.Is(err, ErrStopFollowing) {
return err
}
handleErr(resp, err)
if err := handleErr(resp, err); err != nil {
return err
}
}
} else {
option.StartTsNs = resp.TsNs
@@ -226,7 +243,9 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
if errors.Is(err, ErrStopFollowing) {
return err
}
handleErr(resp, err)
if err := handleErr(resp, err); err != nil {
return err
}
// RetryForeverOnError only returns once the event was handled;
// other modes leave it failed and the cursor stays behind it.
if option.EventErrorType != RetryForeverOnError {
@@ -293,12 +312,7 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
return drainPendingRefs()
}
if listenErr != nil {
select {
case <-option.Resubscribe:
return ErrResubscribe
default:
}
return listenErr
return resubscribeOr(listenErr)
}
// Accumulate log file chunk references (metadata chunks mode)
+90
View File
@@ -647,6 +647,96 @@ func TestStopFollowingEndsStreamAndKeepsCursor(t *testing.T) {
}
}
// A consumer that stops while RetryForeverOnError retries an event ends the
// follow too: the retry must not log the stop and try the event again.
func TestStopFollowingDuringRetryEndsStream(t *testing.T) {
const firstTs = int64(100)
option := &MetadataFollowOption{
ClientName: "syncFrom_A_To_B",
StartTsNs: firstTs,
EventErrorType: RetryForeverOnError,
}
stream := &fakeSubscribeStream{
responses: []*filer_pb.SubscribeMetadataResponse{
{Directory: "/watched", TsNs: 200, EventNotification: &filer_pb.EventNotification{NewEntry: &filer_pb.Entry{Name: "stop"}}},
{Directory: "/watched", TsNs: 201, EventNotification: &filer_pb.EventNotification{NewEntry: &filer_pb.Entry{Name: "next"}}},
},
}
var calls atomic.Int32
fn := makeSubscribeMetadataFunc(option, func(resp *filer_pb.SubscribeMetadataResponse) error {
if calls.Add(1) == 1 {
return io.ErrUnexpectedEOF
}
return fmt.Errorf("%w: metadata cache is shut down", ErrStopFollowing)
})
done := make(chan error, 1)
go func() { done <- fn(&fakeFilerClient{stream: stream}) }()
select {
case err := <-done:
if !errors.Is(err, ErrStopFollowing) {
t.Fatalf("expected the follow to end with ErrStopFollowing, got %v", err)
}
case <-time.After(5 * time.Second):
t.Fatalf("the retry kept going after the consumer asked to stop (%d calls)", calls.Load())
}
if got := calls.Load(); got != 2 {
t.Fatalf("calls = %d, want 2: the failed attempt and the retry that stopped", got)
}
if option.StartTsNs != firstTs {
t.Fatalf("StartTsNs advanced to %d past the stopped event, want it to stay at %d", option.StartTsNs, firstTs)
}
}
// A follow that ends while RetryForeverOnError retries an event never applied
// it, so the cursor stays behind the event and no later event runs.
func TestParentContextCancelDuringRetryKeepsCursor(t *testing.T) {
const firstTs = int64(100)
parent, cancel := context.WithCancel(context.Background())
defer cancel()
option := &MetadataFollowOption{
ClientName: "syncFrom_A_To_B",
StartTsNs: firstTs,
EventErrorType: RetryForeverOnError,
ParentContext: parent,
}
stream := &fakeSubscribeStream{
responses: []*filer_pb.SubscribeMetadataResponse{{
Directory: "/watched", TsNs: 200, EventNotification: &filer_pb.EventNotification{NewEntry: &filer_pb.Entry{Name: "failed"}},
Events: []*filer_pb.SubscribeMetadataResponse{
{Directory: "/watched", TsNs: 201, EventNotification: &filer_pb.EventNotification{NewEntry: &filer_pb.Entry{Name: "next"}}},
},
}},
}
var calls atomic.Int32
fn := makeSubscribeMetadataFunc(option, func(resp *filer_pb.SubscribeMetadataResponse) error {
if calls.Add(1) == 1 {
cancel()
return io.ErrUnexpectedEOF
}
return nil
})
done := make(chan error, 1)
go func() { done <- fn(&fakeFilerClient{stream: stream}) }()
select {
case err := <-done:
if !errors.Is(err, context.Canceled) {
t.Fatalf("expected the follow to end with context.Canceled, got %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("the follow kept running after its parent context was cancelled")
}
if got := calls.Load(); got != 1 {
t.Fatalf("calls = %d, want 1: nothing runs after the follow ended", got)
}
if option.StartTsNs != firstTs {
t.Fatalf("StartTsNs advanced to %d past the event that never applied, want it to stay at %d", option.StartTsNs, firstTs)
}
}
// Cancelling the caller's context must end the stream, so a consumer can
// quiesce the follow before closing what the events are applied to.
func TestParentContextCancelEndsStream(t *testing.T) {