diff --git a/CHANGELOG.md b/CHANGELOG.md index 9083bcc1..3f2011d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -101,7 +101,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Worker completion and abandon RPCs no longer retry `NotFound` responses ten times. A completion whose work item is already unavailable is dropped for normal DTS redelivery without a second, guaranteed-failing abandon RPC. - The gRPC worker no longer deep-clones freshly owned orchestrator and entity executor results before adding transport fields and externalizing payloads. - Streamed orchestration histories are now bounded before retention to 100,000 events and 64 MiB by default, with configurable limits up to the public history maxima. -- DTS connections now apply explicit 64 MiB send/receive message limits and active-stream keepalive settings. Local message-size failures are non-retryable instead of entering a reconnect loop. +- DTS connections use a 64 MiB receive limit for unary responses and individual stream chunks, with active-stream keepalive settings. `MaxSendMessageSize` defaults to zero, leaving outgoing message-size enforcement to the server and the gRPC-Go transport's own default maximum; positive values opt into a client-side send limit. The separate 3.9 MiB orchestration-response safety bound remains in place. Local message-size failures are non-retryable instead of entering a reconnect loop. - gRPC worker reconnect delays now use bounded jitter to prevent synchronized reconnect storms while always remaining inside the configured `[baseDelay, maxDelay]` interval. Exponential growth still saturates instead of overflowing for very large configured maximums. - A work item that the service delivers concurrently with the gRPC worker's silent-disconnect timeout is now processed instead of dropped. Previously the racing message was discarded without being abandoned, so the service considered it dispatched and it could only be redelivered after its lock expired. - `client.WithMaxConcurrentOrchestrationWorkItems`, `WithMaxConcurrentActivityWorkItems`, and `WithMaxConcurrentEntityWorkItems` now reject limits above `math.MaxInt32`. Previously such a limit silently wrapped to a negative value in the 32-bit `GetWorkItems` fields advertised to the service. diff --git a/durabletaskscheduler/README.md b/durabletaskscheduler/README.md index 574d43df..f85bd9e5 100644 --- a/durabletaskscheduler/README.md +++ b/durabletaskscheduler/README.md @@ -155,9 +155,17 @@ lifecycle operations are not automatically retried: a failed acknowledgement can follow a successful service-side change. Worker channels do not use this policy, because the worker owns its own reconnect loop. -Individual gRPC messages are bounded to 64 MiB by default through -`Options.MaxReceiveMessageSize` and `Options.MaxSendMessageSize`. The worker uses a -3.9 MiB safety bound below the service ceiling. When +Incoming gRPC messages are bounded to 64 MiB by default through +`Options.MaxReceiveMessageSize`, providing generous headroom for unary responses +and individual stream chunks. The limit applies to each message, not the total +stream; the total streamed history limit is separate. By default, +`Options.MaxSendMessageSize` is zero and the SDK does not set a transport send +limit, leaving message-size enforcement to the server. The gRPC-Go transport's +own default maximum (approximately 2 GiB) still applies. A positive +`Options.MaxSendMessageSize` opts into an explicit client-side send limit. + +The worker retains a separate 3.9 MiB safety bound for orchestration +responses, regardless of the default transport send behavior. When a positive `Options.MaxSendMessageSize` is lower, that configured send limit becomes the bound instead. The worker validates the final response after large-payload externalization and fails an orchestration once diff --git a/durabletaskscheduler/connection.go b/durabletaskscheduler/connection.go index 96039be6..28939860 100644 --- a/durabletaskscheduler/connection.go +++ b/durabletaskscheduler/connection.go @@ -444,9 +444,6 @@ func prepareOptionsWith(options *Options, factory credentialFactory) (Options, e if prepared.MaxReceiveMessageSize == 0 { prepared.MaxReceiveMessageSize = DefaultMaxReceiveMessageSize } - if prepared.MaxSendMessageSize == 0 { - prepared.MaxSendMessageSize = DefaultMaxSendMessageSize - } if prepared.KeepaliveTime > 0 && prepared.KeepaliveTimeout == 0 { prepared.KeepaliveTimeout = DefaultKeepaliveTimeout } @@ -520,9 +517,13 @@ func connect( grpc.WithPerRPCCredentials(newPerRPCCredentials(options, role, workerID)), grpc.WithDefaultCallOptions( grpc.MaxCallRecvMsgSize(options.MaxReceiveMessageSize), - grpc.MaxCallSendMsgSize(options.MaxSendMessageSize), ), } + if options.MaxSendMessageSize > 0 { + dialOptions = append(dialOptions, grpc.WithDefaultCallOptions( + grpc.MaxCallSendMsgSize(options.MaxSendMessageSize), + )) + } if options.KeepaliveTime > 0 { dialOptions = append(dialOptions, grpc.WithKeepaliveParams(keepalive.ClientParameters{ Time: options.KeepaliveTime, diff --git a/durabletaskscheduler/connection_test.go b/durabletaskscheduler/connection_test.go index 0a4820df..ed62138e 100644 --- a/durabletaskscheduler/connection_test.go +++ b/durabletaskscheduler/connection_test.go @@ -3,6 +3,7 @@ package durabletaskscheduler import ( "context" "errors" + "fmt" "net" "strings" "sync" @@ -25,6 +26,7 @@ import ( "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/emptypb" "google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/wrapperspb" @@ -132,6 +134,27 @@ type metadataServer struct { state *protos.OrchestrationState } +type messageSizeHistoryServer struct { + protos.UnimplementedTaskHubSidecarServiceServer +} + +func (*messageSizeHistoryServer) StreamInstanceHistory( + _ *protos.StreamInstanceHistoryRequest, + stream protos.TaskHubSidecarService_StreamInstanceHistoryServer, +) error { + for _, size := range []int{2 << 20, 2 << 20, 2 << 20, 4 << 20} { + err := stream.Send(&protos.HistoryChunk{Events: []*protos.HistoryEvent{{ + EventType: &protos.HistoryEvent_GenericEvent{GenericEvent: &protos.GenericEvent{ + Data: wrapperspb.String(strings.Repeat("x", size)), + }}, + }}}) + if err != nil { + return err + } + } + return nil +} + func (s *metadataServer) GetInstance( ctx context.Context, _ *protos.GetInstanceRequest, @@ -577,7 +600,7 @@ func TestNewClientFailsFastWhenHelloIsRejected(t *testing.T) { require.ErrorContains(t, err, "PermissionDenied") } -func TestNewClientReceivesMessagesLargerThanGrpcDefault(t *testing.T) { +func TestNewClientAppliesConfiguredReceiveMessageSize(t *testing.T) { const payloadSize = 5 * 1024 * 1024 server := &metadataServer{ metadata: make(chan metadata.MD, 4), @@ -597,13 +620,12 @@ func TestNewClientReceivesMessagesLargerThanGrpcDefault(t *testing.T) { options.Authentication = AuthenticationNone options.AllowInsecureConnection = true options.dialer = bufconnDialer(listener) - managementClient, err := NewClient(context.Background(), options, api.DefaultLogger()) + defaultClient, err := NewClient(context.Background(), options, api.DefaultLogger()) require.NoError(t, err) defer func() { - require.NoError(t, managementClient.Close()) + require.NoError(t, defaultClient.Close()) }() - - result, err := managementClient.FetchOrchestrationMetadata( + result, err := defaultClient.FetchOrchestrationMetadata( context.Background(), "large-message", api.WithFetchPayloads(true), @@ -612,12 +634,13 @@ func TestNewClientReceivesMessagesLargerThanGrpcDefault(t *testing.T) { require.Len(t, result.SerializedInput, payloadSize) limitedOptions := *options - limitedOptions.MaxReceiveMessageSize = 1024 * 1024 + limitedOptions.MaxReceiveMessageSize = 4 * 1024 * 1024 limitedClient, err := NewClient(context.Background(), &limitedOptions, api.DefaultLogger()) require.NoError(t, err) defer func() { require.NoError(t, limitedClient.Close()) }() + _, err = limitedClient.FetchOrchestrationMetadata( context.Background(), "large-message", @@ -626,6 +649,102 @@ func TestNewClientReceivesMessagesLargerThanGrpcDefault(t *testing.T) { require.Equal(t, codes.ResourceExhausted, status.Code(err)) } +func TestConnectionAppliesConfiguredSendMessageSize(t *testing.T) { + const limit = 4 * 1024 * 1024 + listener := bufconn.Listen(1024 * 1024) + server := grpc.NewServer(grpc.MaxRecvMsgSize(8 * 1024 * 1024)) + protos.RegisterTaskHubSidecarServiceServer(server, &metadataServer{metadata: make(chan metadata.MD, 4)}) + go func() { _ = server.Serve(listener) }() + defer func() { + server.Stop() + require.NoError(t, listener.Close()) + }() + + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + for _, testCase := range []struct { + name string + sendLimit int + messageBytes int + wantCode codes.Code + }{ + {"default leaves send limit unset", 0, limit + 1, codes.OK}, + {"explicit limit accepts boundary", limit, limit, codes.OK}, + {"explicit limit rejects oversized message", limit, limit + 1, codes.ResourceExhausted}, + {"raised explicit limit", 2 * limit, limit + 1, codes.OK}, + {"server enforces its receive limit", 0, 2*limit + 1, codes.ResourceExhausted}, + } { + t.Run(testCase.name, func(t *testing.T) { + options := NewOptions("http://bufconn", "default") + options.Authentication = AuthenticationNone + options.AllowInsecureConnection = true + options.MaxSendMessageSize = testCase.sendLimit + options.dialer = bufconnDialer(listener) + var sendLimitSet bool + options.UnaryInterceptors = []grpc.UnaryClientInterceptor{ + func(ctx context.Context, method string, request, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, callOptions ...grpc.CallOption) error { + for _, option := range callOptions { + if _, ok := option.(grpc.MaxSendMsgSizeCallOption); ok { + sendLimitSet = true + } + } + return invoker(ctx, method, request, reply, cc, callOptions...) + }, + } + prepared, err := prepareOptions(options) + require.NoError(t, err) + conn, err := connect(&prepared, clientRole, "") + require.NoError(t, err) + defer func() { require.NoError(t, conn.Close()) }() + + request := &protos.GetInstanceRequest{InstanceId: strings.Repeat("x", testCase.messageBytes-5)} + require.Equal(t, testCase.messageBytes, proto.Size(request)) + _, err = protos.NewTaskHubSidecarServiceClient(conn).GetInstance(ctx, request) + require.Equal(t, testCase.wantCode, status.Code(err)) + require.Equal(t, testCase.sendLimit > 0, sendLimitSet) + }) + } +} + +func TestConnectionReceiveLimitAppliesPerStreamMessage(t *testing.T) { + listener, stop := startBufconnServer(t, &messageSizeHistoryServer{}) + defer stop() + options := NewOptions("http://bufconn", "default") + options.Authentication = AuthenticationNone + options.AllowInsecureConnection = true + options.dialer = bufconnDialer(listener) + prepared, err := prepareOptions(options) + require.NoError(t, err) + + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + for _, limited := range []bool{false, true} { + t.Run(fmt.Sprintf("limited=%t", limited), func(t *testing.T) { + streamOptions := prepared + if limited { + streamOptions.MaxReceiveMessageSize = 4 * 1024 * 1024 + } + conn, err := connect(&streamOptions, clientRole, "") + require.NoError(t, err) + defer func() { require.NoError(t, conn.Close()) }() + stream, err := protos.NewTaskHubSidecarServiceClient(conn).StreamInstanceHistory(ctx, &protos.StreamInstanceHistoryRequest{}) + require.NoError(t, err) + for range 3 { + chunk, err := stream.Recv() + require.NoError(t, err) + require.Len(t, chunk.GetEvents()[0].GetGenericEvent().GetData().GetValue(), 2<<20) + } + chunk, err := stream.Recv() + if limited { + require.Equal(t, codes.ResourceExhausted, status.Code(err)) + } else { + require.NoError(t, err) + require.Len(t, chunk.GetEvents()[0].GetGenericEvent().GetData().GetValue(), 4<<20) + } + }) + } +} + func TestNewClientRecreatesChannelAndPreservesConfiguration(t *testing.T) { firstServer := &metadataServer{ getErr: status.Error(codes.Unavailable, "replace this channel"), diff --git a/durabletaskscheduler/options.go b/durabletaskscheduler/options.go index 9ccc9ff5..62141e5f 100644 --- a/durabletaskscheduler/options.go +++ b/durabletaskscheduler/options.go @@ -24,10 +24,11 @@ const ( // GovernmentResourceID is the token audience for DTS in US Government and DoD regions. GovernmentResourceID = "https://durabletask.azure.us" - // DefaultMaxReceiveMessageSize and DefaultMaxSendMessageSize are the default - // per-message gRPC bounds. + // DefaultMaxReceiveMessageSize provides headroom for unary responses and + // individual messages of a stream. DefaultMaxReceiveMessageSize = 64 * 1024 * 1024 - DefaultMaxSendMessageSize = 64 * 1024 * 1024 + // DefaultMaxSendMessageSize leaves the gRPC send limit unset. + DefaultMaxSendMessageSize = 0 // DefaultKeepaliveTime and DefaultKeepaliveTimeout configure pings while a // gRPC stream is active. DefaultKeepaliveTime = 2 * time.Minute @@ -110,10 +111,14 @@ type Options struct { // HelloTimeout controls fail-fast connectivity checks. HelloTimeout time.Duration - // MaxReceiveMessageSize and MaxSendMessageSize bound individual gRPC + // MaxReceiveMessageSize bounds individual unary responses and streamed // messages. Zero uses the 64 MiB SDK default. MaxReceiveMessageSize int - MaxSendMessageSize int + + // MaxSendMessageSize optionally bounds individual outgoing gRPC messages. + // Zero leaves the gRPC send limit unset, allowing the server to enforce its + // receive limit. The gRPC-Go transport's own default maximum still applies. + MaxSendMessageSize int // KeepaliveTime controls client pings while a gRPC stream is active. Zero // disables keepalive, in which case KeepaliveTimeout is ignored. diff --git a/durabletaskscheduler/worker.go b/durabletaskscheduler/worker.go index 0889b0b2..21709515 100644 --- a/durabletaskscheduler/worker.go +++ b/durabletaskscheduler/worker.go @@ -34,14 +34,15 @@ func NewWorker( } return connection, connection, nil } + completionLimit := durabletaskclient.DefaultMaxOrchestratorCompletionBytes + if prepared.MaxSendMessageSize > 0 { + completionLimit = min(completionLimit, prepared.MaxSendMessageSize) + } configuredOptions := []durabletaskclient.TaskHubGrpcWorkerOption{ durabletaskclient.WithWorkerHelloTimeout(prepared.HelloTimeout), durabletaskclient.WithWorkerDataConverter(prepared.DataConverter), durabletaskclient.WithMaximumTimerInterval(prepared.MaximumTimerInterval), - durabletaskclient.WithMaxOrchestratorCompletionBytes(min( - prepared.MaxSendMessageSize, - durabletaskclient.DefaultMaxOrchestratorCompletionBytes, - )), + durabletaskclient.WithMaxOrchestratorCompletionBytes(completionLimit), } if prepared.LargePayloads != nil { configuredOptions = append(