From f7ea52cac2f634cd3d5b58f65f72feaf3fb5ff7d Mon Sep 17 00:00:00 2001 From: Abhilaksh Sharma Date: Mon, 16 Nov 2026 13:42:01 +0530 Subject: [PATCH] pubsub: nack unreturned messages on Subscription.Shutdown Shutdown now cancels in-flight ReceiveBatch calls, waits for them to finish (bounded by the Shutdown ctx), and nacks every message Receive never returned through the ack batcher, so they are redelivered without waiting for the ack deadline to expire. Drivers that can't nack are unchanged. --- pubsub/pubsub.go | 26 +++++++++++- pubsub/pubsub_test.go | 99 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+), 1 deletion(-) diff --git a/pubsub/pubsub.go b/pubsub/pubsub.go index bb75433300..4a42356814 100644 --- a/pubsub/pubsub.go +++ b/pubsub/pubsub.go @@ -374,6 +374,8 @@ type Subscription struct { canNack bool // true iff the driver supports Nack backgroundCtx context.Context // for background SendAcks and ReceiveBatch calls cancel func() // for canceling backgroundCtx + recvCtx context.Context // for background ReceiveBatch calls; child of backgroundCtx + recvCancel func() // for canceling recvCtx recvBatchOpts *batcher.Options @@ -704,7 +706,7 @@ type msgsOrError struct { // messages as they come from each independent batch, or an operation error func (s *Subscription) getNextBatch(batches []int) chan msgsOrError { result := make(chan msgsOrError, len(batches)) - g, ctx := errgroup.WithContext(s.backgroundCtx) + g, ctx := errgroup.WithContext(s.recvCtx) for _, maxMessagesInBatch := range batches { // Make a copy of the loop variable since it will be used by a goroutine. curMaxMessagesInBatch := maxMessagesInBatch @@ -748,6 +750,25 @@ func (s *Subscription) Shutdown(ctx context.Context) (err error) { return s.err } s.err = errSubscriptionShutdown + if s.canNack && s.ackBatcher != nil { + // Stop in-flight ReceiveBatch calls and wait for their messages to land + // in s.q, then nack everything Receive never returned, so it is + // redelivered without waiting for the ack deadline to expire. + s.recvCancel() + for s.fetches > 0 && ctx.Err() == nil { + waitc := s.waitc + s.mu.Unlock() + select { + case <-waitc: + case <-ctx.Done(): + } + s.mu.Lock() + } + for _, m := range s.q { + _ = s.ackBatcher.AddNoWait(&driver.AckInfo{AckID: m.AckID, IsAck: false}) + } + s.q = nil + } s.mu.Unlock() c := make(chan struct{}) go func() { @@ -803,11 +824,14 @@ var NewSubscription = newSubscription // defaults. func newSubscription(ds driver.Subscription, recvBatchOpts, ackBatcherOpts *batcher.Options) *Subscription { ctx, cancel := context.WithCancel(context.Background()) + recvCtx, recvCancel := context.WithCancel(ctx) s := &Subscription{ driver: ds, tracer: gcdkotel.NewTracer(pkgName, gcdkotel.ProviderName(ds)), cancel: cancel, backgroundCtx: ctx, + recvCtx: recvCtx, + recvCancel: recvCancel, recvBatchOpts: recvBatchOpts, runningBatchSize: initialBatchSize, canNack: ds.CanNack(), diff --git a/pubsub/pubsub_test.go b/pubsub/pubsub_test.go index 8dc8c7255d..f1cf6ab3d6 100644 --- a/pubsub/pubsub_test.go +++ b/pubsub/pubsub_test.go @@ -25,6 +25,7 @@ import ( "time" "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" "gocloud.dev/gcerrors" "gocloud.dev/internal/gcerr" "gocloud.dev/internal/testing/oteltest" @@ -338,6 +339,104 @@ func TestIndependentBatchReturn(t *testing.T) { m.Ack() } +// prefetchDriverSub returns all its messages on the first ReceiveBatch call +// and records what is acked and nacked. If late is set, that call returns only +// once its context is canceled, like a receive still in flight at Shutdown. +type prefetchDriverSub struct { + driver.Subscription + canNack bool + late bool + msgs []*driver.Message + + mu sync.Mutex + calls int + acks []driver.AckID + nacks []driver.AckID +} + +func (s *prefetchDriverSub) ReceiveBatch(ctx context.Context, _ int) ([]*driver.Message, error) { + s.mu.Lock() + s.calls++ + first := s.calls == 1 + s.mu.Unlock() + if !first || s.late { + <-ctx.Done() + } + if !first { + return nil, ctx.Err() + } + return s.msgs, nil +} + +func (s *prefetchDriverSub) SendAcks(_ context.Context, ids []driver.AckID) error { + s.mu.Lock() + defer s.mu.Unlock() + s.acks = append(s.acks, ids...) + return nil +} + +func (s *prefetchDriverSub) SendNacks(_ context.Context, ids []driver.AckID) error { + s.mu.Lock() + defer s.mu.Unlock() + s.nacks = append(s.nacks, ids...) + return nil +} + +func (s *prefetchDriverSub) CanNack() bool { return s.canNack } +func (*prefetchDriverSub) IsRetryable(error) bool { return false } +func (*prefetchDriverSub) Close() error { return nil } + +// TestShutdownNacksPrefetched verifies that Shutdown nacks messages that were +// prefetched but never returned by Receive, including ones from a ReceiveBatch +// call still in flight at Shutdown. +func TestShutdownNacksPrefetched(t *testing.T) { + for _, test := range []struct { + name string + canNack, late bool + wantAcks []driver.AckID + wantNacks []driver.AckID + }{ + {name: "queued", canNack: true, wantAcks: []driver.AckID{0}, wantNacks: []driver.AckID{1, 2, 3, 4}}, + {name: "in flight", canNack: true, late: true, wantNacks: []driver.AckID{0, 1, 2, 3, 4}}, + {name: "can't nack", wantAcks: []driver.AckID{0}}, + } { + t.Run(test.name, func(t *testing.T) { + ctx := context.Background() + ds := &prefetchDriverSub{canNack: test.canNack, late: test.late} + for i := 0; i < 5; i++ { + ds.msgs = append(ds.msgs, &driver.Message{AckID: i, Body: []byte("m")}) + } + s := NewSubscription(ds, nil, nil) + if test.late { + rctx, cancel := context.WithTimeout(ctx, 50*time.Millisecond) + defer cancel() + if _, err := s.Receive(rctx); err != context.DeadlineExceeded { + t.Fatalf("Receive: got %v, want context.DeadlineExceeded", err) + } + } else { + m, err := s.Receive(ctx) + if err != nil { + t.Fatal(err) + } + m.Ack() + } + if err := s.Shutdown(ctx); err != nil { + t.Fatal(err) + } + + ds.mu.Lock() + defer ds.mu.Unlock() + if diff := cmp.Diff(test.wantAcks, ds.acks, cmpopts.EquateEmpty()); diff != "" { + t.Errorf("acks (-want +got):\n%s", diff) + } + sortIDs := cmpopts.SortSlices(func(a, b driver.AckID) bool { return a.(int) < b.(int) }) + if diff := cmp.Diff(test.wantNacks, ds.nacks, sortIDs, cmpopts.EquateEmpty()); diff != "" { + t.Errorf("nacks (-want +got):\n%s", diff) + } + }) + } +} + func TestRetryTopic(t *testing.T) { // Test that Send is retried if the driver returns a retryable error. ctx := context.Background()