From 2a8b916eeaa2a17dff720ed5e15ce2514d940019 Mon Sep 17 00:00:00 2001 From: Varshi Bachu Date: Tue, 3 Nov 2026 14:57:37 -0800 Subject: [PATCH 1/2] Add orchestration restart options and source instance metadata --- README.md | 26 +++ src/Abstractions/TaskOrchestrationContext.cs | 13 ++ src/Client/Core/DurableTaskClient.cs | 30 +++ .../Core/RestartOrchestrationOptions.cs | 24 ++ src/Client/Grpc/GrpcDurableTaskClient.cs | 69 ++++-- src/Grpc/orchestrator_service.proto | 13 ++ src/Grpc/versions.txt | 3 + .../Grpc/GrpcDurableTaskWorker.Processor.cs | 5 +- .../GrpcDurableTaskClientRestartTests.cs | 208 ++++++++++++++++++ .../TaskOrchestrationContextWrapperTests.cs | 39 ++++ .../Grpc.Tests/GrpcDurableTaskWorkerTests.cs | 66 ++++++ .../GrpcOrchestrationRunnerTests.cs | 63 ++++++ 12 files changed, 544 insertions(+), 15 deletions(-) create mode 100644 src/Client/Core/RestartOrchestrationOptions.cs create mode 100644 test/Client/Grpc.Tests/GrpcDurableTaskClientRestartTests.cs diff --git a/README.md b/README.md index 9941a8c48..468cb1c9a 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,32 @@ static class HelloSequenceUntyped You can find the full sample file, including detailed comments, at [samples/AzureFunctionsApp/HelloCitiesUntyped.cs](samples/AzureFunctionsApp/HelloCitiesUntyped.cs). +### Restarting as a clone + +With a backend that supports explicit restart IDs, restart an orchestration from the beginning with its original +name and input, a chosen target instance ID, and an optional version: + +```csharp +string cloneId = await client.RestartAsync( + "source-instance", + new RestartOrchestrationOptions { NewInstanceId = "clone-instance", Version = "v2" }); +``` + +Execution history is not copied. Inside the cloned orchestrator, `context.SourceInstanceId` identifies the immediate +source (`"source-instance"` above). Cloning that clone identifies `"clone-instance"` as the next clone's source. +Lineage is separate from `context.Parent` and is not inherited by sub-orchestrations. Without backend-supplied lineage, +`SourceInstanceId` is `null`. + +Omit `Version` (or use `null`) to use the backend's restart default, which is not necessarily the source version. +For example, Durable Functions uses its configured default version. Use `Version = ""` to explicitly request an +unversioned orchestration. The existing `RestartAsync(instanceId, restartWithNewInstanceId)` overload is unchanged. + +**Server compatibility:** Upgrade the Durable Functions extension or other backend to a version supporting these +options before calling this overload. Older gRPC servers may ignore the added fields and create an unintended +legacy restart with a generated instance ID. The client rejects a returned ID that differs from the requested target, but cannot undo that restart +or detect an ignored version override. Backends and clients without support can reject the operation; the +orchestration-service client shim does not implement this overload. + ### Class-based syntax **IMPORTANT**: class based syntax in Durable Functions relies on a package reference to `Microsoft.DurableTask.Generators`. This is still in "preview" and may be subject to significant change before 1.0 or even post-1.0. It is recommended to stick with function-syntax for now. diff --git a/src/Abstractions/TaskOrchestrationContext.cs b/src/Abstractions/TaskOrchestrationContext.cs index 6f6fa793a..d3a05bc4f 100644 --- a/src/Abstractions/TaskOrchestrationContext.cs +++ b/src/Abstractions/TaskOrchestrationContext.cs @@ -25,6 +25,19 @@ public abstract class TaskOrchestrationContext /// public abstract string InstanceId { get; } + /// + /// Gets the immediate source instance ID when this orchestration was restarted as a clone, or null + /// when no source lineage was supplied by the backend. + /// + /// + /// This is distinct from and is not inherited by sub-orchestrations. + /// Cloning a clone identifies that clone as the immediate source, not its original ancestor. + /// + public virtual string? SourceInstanceId => + this.Properties.TryGetValue("sourceInstanceId", out object? source) && source is string instanceId + ? instanceId + : null; + /// /// Gets the parent instance or null if there is no parent orchestration. /// diff --git a/src/Client/Core/DurableTaskClient.cs b/src/Client/Core/DurableTaskClient.cs index 033038005..d6f1c2318 100644 --- a/src/Client/Core/DurableTaskClient.cs +++ b/src/Client/Core/DurableTaskClient.cs @@ -465,6 +465,36 @@ public virtual Task RestartAsync( CancellationToken cancellation = default) => throw new NotSupportedException($"{this.GetType()} does not support orchestration restart."); + /// + /// Restarts an orchestration from the beginning using its original name and input and a caller-selected instance ID. + /// + /// + /// + /// This operation does not copy execution history. A supporting backend makes the immediate source instance ID + /// available through on the restarted orchestration. + /// The version is selected using , including backend-specific + /// defaults when no override is provided. + /// + /// + /// This overload requires a backend that supports explicit restart IDs and version overrides. Older gRPC servers + /// may ignore these options and perform a legacy restart with a generated instance ID instead. + /// Upgrade the server before using this overload; a returned instance ID cannot verify whether a version override + /// was honored. + /// + /// + /// The ID of the source orchestration. + /// The restart options, including the required, nonblank target instance ID. + /// Cancels enqueueing the request, not execution once enqueued. + /// The instance ID of the restarted orchestration. + /// The source was not found or an instance ID is invalid. + /// is null. + /// The client or backend does not support these restart options. + public virtual Task RestartAsync( + string instanceId, + RestartOrchestrationOptions options, + CancellationToken cancellation = default) + => throw new NotSupportedException($"{this.GetType()} does not support orchestration restart options."); + /// /// Rewinds the specified orchestration instance by re-executing any failed Activities, and recursively rewinding /// any failed suborchestrations with failed Activities. diff --git a/src/Client/Core/RestartOrchestrationOptions.cs b/src/Client/Core/RestartOrchestrationOptions.cs new file mode 100644 index 000000000..2c44b2b9d --- /dev/null +++ b/src/Client/Core/RestartOrchestrationOptions.cs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.DurableTask.Client; + +/// +/// Options for restarting an orchestration from the beginning with a caller-selected instance ID. +/// +public sealed record RestartOrchestrationOptions +{ + /// + /// Gets the required, nonblank instance ID of the restarted orchestration. + /// + public string NewInstanceId { get; init; } = string.Empty; + + /// + /// Gets the optional version override for the restarted orchestration. + /// + /// + /// A null value uses the backend's restart default, which need not be the original version. + /// An empty string explicitly selects the unversioned orchestration. + /// + public string? Version { get; init; } +} diff --git a/src/Client/Grpc/GrpcDurableTaskClient.cs b/src/Client/Grpc/GrpcDurableTaskClient.cs index f18c75653..80bd6fed5 100644 --- a/src/Client/Grpc/GrpcDurableTaskClient.cs +++ b/src/Client/Grpc/GrpcDurableTaskClient.cs @@ -532,25 +532,42 @@ public override async Task RestartAsync( RestartWithNewInstanceId = restartWithNewInstanceId, }; - try - { - P.RestartInstanceResponse result = await this.sidecarClient.RestartInstanceAsync( - request, cancellationToken: cancellation); - return result.InstanceId; - } - catch (RpcException e) when (e.StatusCode == StatusCode.NotFound) + return await this.RestartInstanceCoreAsync(request, cancellation); + } + + /// + public override async Task RestartAsync( + string instanceId, + RestartOrchestrationOptions options, + CancellationToken cancellation = default) + { + Check.NotNullOrEmpty(instanceId); + Check.NotEntity(this.options.EnableEntitySupport, instanceId); + Check.NotNull(options); + if (string.IsNullOrWhiteSpace(options.NewInstanceId)) { - throw new ArgumentException($"An orchestration with the instanceId {instanceId} was not found.", e); + throw new ArgumentException("A nonblank target instance ID is required.", nameof(options)); } - catch (RpcException e) when (e.StatusCode == StatusCode.FailedPrecondition) + + Check.NotEntity(this.options.EnableEntitySupport, options.NewInstanceId); + P.RestartInstanceRequest request = new() { - throw new InvalidOperationException($"An orchestration with the instanceId {instanceId} cannot be restarted.", e); - } - catch (RpcException e) when (e.StatusCode == StatusCode.Cancelled) + InstanceId = instanceId, + RestartWithNewInstanceId = true, + NewInstanceId = options.NewInstanceId, + Version = options.Version, + }; + + string result = await this.RestartInstanceCoreAsync(request, cancellation); + if (!string.Equals(result, options.NewInstanceId, StringComparison.Ordinal)) { - throw new OperationCanceledException( - $"The {nameof(this.RestartAsync)} operation was canceled.", e, cancellation); + throw new NotSupportedException( + $"The backend returned restart instance ID '{result}' instead of the requested ID " + + $"'{options.NewInstanceId}'. It may not support explicit restart instance IDs. " + + "A legacy restart may already have occurred."); } + + return result; } /// @@ -764,6 +781,30 @@ static GrpcChannel GetChannel(string? address) } #endif + async Task RestartInstanceCoreAsync(P.RestartInstanceRequest request, CancellationToken cancellation) + { + string instanceId = request.InstanceId; + try + { + P.RestartInstanceResponse result = await this.sidecarClient.RestartInstanceAsync( + request, cancellationToken: cancellation); + return result.InstanceId; + } + catch (RpcException e) when (e.StatusCode == StatusCode.NotFound) + { + throw new ArgumentException($"An orchestration with the instanceId {instanceId} was not found.", e); + } + catch (RpcException e) when (e.StatusCode == StatusCode.FailedPrecondition) + { + throw new InvalidOperationException($"An orchestration with the instanceId {instanceId} cannot be restarted.", e); + } + catch (RpcException e) when (e.StatusCode == StatusCode.Cancelled) + { + throw new OperationCanceledException( + $"The {nameof(this.RestartAsync)} operation was canceled.", e, cancellation); + } + } + async Task PurgeInstancesCoreAsync( P.PurgeInstancesRequest request, CancellationToken cancellation = default) { diff --git a/src/Grpc/orchestrator_service.proto b/src/Grpc/orchestrator_service.proto index 2429fff46..b9f9f63d3 100644 --- a/src/Grpc/orchestrator_service.proto +++ b/src/Grpc/orchestrator_service.proto @@ -533,9 +533,22 @@ message PurgeInstancesResponse { google.protobuf.BoolValue isComplete = 2; } +// Restarts an orchestration from the beginning with its original name and input, +// without copying its history. message RestartInstanceRequest { string instanceId = 1; + + // When newInstanceId is absent, true generates a new instance ID and false + // restarts using instanceId. bool restartWithNewInstanceId = 2; + + // An explicit target instance ID. When present, takes precedence over + // restartWithNewInstanceId. + google.protobuf.StringValue newInstanceId = 3; + + // Overrides the restarted orchestration's version, including an empty string. + // When absent, preserves the server's default restart behavior. + google.protobuf.StringValue version = 4; } message RestartInstanceResponse { diff --git a/src/Grpc/versions.txt b/src/Grpc/versions.txt index 6f9983e3b..693290d94 100644 --- a/src/Grpc/versions.txt +++ b/src/Grpc/versions.txt @@ -1,4 +1,7 @@ # The following files were downloaded from branch main at 2026-10-20 19:46:22 UTC +# RestartInstanceRequest patch imported from local durabletask-protobuf commit +# 962a493037e72b5e08f07a55eff0f121c1aaae80 (not yet published upstream). +# Base download URLs below remain unchanged; refresh after that commit is published upstream. https://raw.githubusercontent.com/microsoft/durabletask-protobuf/20d2aadae358d8aa526190cbf78fb6c313b0b3db/protos/orchestrator_service.proto https://raw.githubusercontent.com/microsoft/durabletask-protobuf/20d2aadae358d8aa526190cbf78fb6c313b0b3db/protos/durable-task-scheduler/sandbox_service.proto https://raw.githubusercontent.com/microsoft/durabletask-protobuf/20d2aadae358d8aa526190cbf78fb6c313b0b3db/protos/durable-task-scheduler/large_payload_purge.proto diff --git a/src/Worker/Grpc/GrpcDurableTaskWorker.Processor.cs b/src/Worker/Grpc/GrpcDurableTaskWorker.Processor.cs index abfba18a4..1680d225e 100644 --- a/src/Worker/Grpc/GrpcDurableTaskWorker.Processor.cs +++ b/src/Worker/Grpc/GrpcDurableTaskWorker.Processor.cs @@ -877,7 +877,10 @@ await this.ExecuteWithRetryAsync( _ => null, }; - TaskOrchestration shim = this.shimFactory.CreateOrchestration(name, orchestrator, parent); + Dictionary properties = request.Properties.ToDictionary( + pair => pair.Key, + pair => ProtoUtils.ConvertValueToObject(pair.Value)); + TaskOrchestration shim = this.shimFactory.CreateOrchestration(name, orchestrator, properties, parent); TaskOrchestrationExecutor executor = new( runtimeState, shim, diff --git a/test/Client/Grpc.Tests/GrpcDurableTaskClientRestartTests.cs b/test/Client/Grpc.Tests/GrpcDurableTaskClientRestartTests.cs new file mode 100644 index 000000000..c269264e3 --- /dev/null +++ b/test/Client/Grpc.Tests/GrpcDurableTaskClientRestartTests.cs @@ -0,0 +1,208 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Google.Protobuf; +using Grpc.Core; +using Microsoft.Extensions.Logging.Abstractions; +using P = Microsoft.DurableTask.Protobuf; + +namespace Microsoft.DurableTask.Client.Grpc.Tests; + +public class GrpcDurableTaskClientRestartTests +{ + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("v2")] + public async Task RestartAsync_Options_ForwardsExplicitTargetAndVersion(string? version) + { + // Arrange + using CancellationTokenSource cancellation = new(); + P.RestartInstanceRequest? captured = null; + CancellationToken capturedCancellation = default; + Mock invoker = CreateInvoker((request, callOptions) => + { + captured = P.RestartInstanceRequest.Parser.ParseFrom(request.ToByteArray()); + capturedCancellation = callOptions.CancellationToken; + return Task.FromResult(new P.RestartInstanceResponse { InstanceId = "target" }); + }); + await using GrpcDurableTaskClient client = CreateClient(invoker); + + // Act + string result = await client.RestartAsync( + "source", new RestartOrchestrationOptions { NewInstanceId = "target", Version = version }, cancellation.Token); + + // Assert + result.Should().Be("target"); + captured.Should().NotBeNull(); + captured!.InstanceId.Should().Be("source"); + captured.NewInstanceId.Should().Be("target"); + captured.Version.Should().Be(version); + captured.RestartWithNewInstanceId.Should().BeTrue(); + capturedCancellation.Should().Be(cancellation.Token); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task RestartAsync_LegacyBool_PreservesRequest(bool newInstanceId) + { + // Arrange + P.RestartInstanceRequest? captured = null; + Mock invoker = CreateInvoker((request, _) => + { + captured = P.RestartInstanceRequest.Parser.ParseFrom(request.ToByteArray()); + return Task.FromResult(new P.RestartInstanceResponse { InstanceId = "returned-id" }); + }); + await using GrpcDurableTaskClient client = CreateClient(invoker); + + // Act + string result = await client.RestartAsync("source", newInstanceId); + + // Assert + result.Should().Be("returned-id"); + captured!.InstanceId.Should().Be("source"); + captured.RestartWithNewInstanceId.Should().Be(newInstanceId); + captured.NewInstanceId.Should().BeNull(); + captured.Version.Should().BeNull(); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task RestartAsync_InvalidTarget_DoesNotSendRequest(string? target) + { + // Arrange + Mock invoker = new(MockBehavior.Strict); + await using GrpcDurableTaskClient client = CreateClient(invoker); + + // Act + Func act = () => client.RestartAsync("source", new RestartOrchestrationOptions { NewInstanceId = target! }); + + // Assert + await act.Should().ThrowAsync(); + invoker.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public async Task RestartAsync_InvalidSource_DoesNotSendRequest(string? source) + { + // Arrange + Mock invoker = new(MockBehavior.Strict); + await using GrpcDurableTaskClient client = CreateClient(invoker); + + // Act + Func act = () => client.RestartAsync(source!, new RestartOrchestrationOptions { NewInstanceId = "target" }); + + // Assert + await act.Should().ThrowAsync(); + invoker.VerifyNoOtherCalls(); + } + + [Fact] + public async Task RestartAsync_NullOptions_DoesNotSendRequest() + { + // Arrange + Mock invoker = new(MockBehavior.Strict); + await using GrpcDurableTaskClient client = CreateClient(invoker); + + // Act + Func act = () => client.RestartAsync("source", (RestartOrchestrationOptions)null!); + + // Assert + await act.Should().ThrowAsync(); + invoker.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData("@counter@source", "target")] + [InlineData("source", "@counter@target")] + public async Task RestartAsync_EntityId_DoesNotSendRequest(string source, string target) + { + // Arrange + Mock invoker = new(MockBehavior.Strict); + await using GrpcDurableTaskClient client = CreateClient(invoker); + + // Act + Func act = () => client.RestartAsync(source, new RestartOrchestrationOptions { NewInstanceId = target }); + + // Assert + await act.Should().ThrowAsync(); + invoker.VerifyNoOtherCalls(); + } + + [Fact] + public async Task RestartAsync_ServerIgnoresExplicitTarget_ThrowsNotSupported() + { + // Arrange + Mock invoker = CreateInvoker((_, _) => + Task.FromResult(new P.RestartInstanceResponse { InstanceId = "generated-id" })); + await using GrpcDurableTaskClient client = CreateClient(invoker); + + // Act + Func act = () => client.RestartAsync("source", new RestartOrchestrationOptions { NewInstanceId = "target" }); + + // Assert + await act.Should().ThrowAsync().WithMessage("*legacy restart may already have occurred*"); + } + + [Theory] + [InlineData(StatusCode.NotFound, typeof(ArgumentException))] + [InlineData(StatusCode.FailedPrecondition, typeof(InvalidOperationException))] + [InlineData(StatusCode.Cancelled, typeof(OperationCanceledException))] + [InlineData(StatusCode.Unimplemented, typeof(RpcException))] + public async Task RestartAsync_RpcError_PreservesErrorMapping(StatusCode status, Type expectedException) + { + // Arrange + using CancellationTokenSource cancellation = new(); + Mock invoker = CreateInvoker((_, _) => + Task.FromException(new RpcException(new Status(status, "test failure")))); + await using GrpcDurableTaskClient client = CreateClient(invoker); + + // Act + Func act = () => client.RestartAsync( + "source", new RestartOrchestrationOptions { NewInstanceId = "target" }, cancellation.Token); + + // Assert + Exception exception = (await act.Should().ThrowAsync()).Which; + exception.GetType().Should().Be(expectedException); + if (exception is OperationCanceledException canceled) + { + canceled.CancellationToken.Should().Be(cancellation.Token); + } + } + + [Fact] + public void RestartAsync_BaseImplementation_DoesNotSilentlyIgnoreOptions() + { + // Arrange + Mock client = new("test") { CallBase = true }; + + // Act + Action act = () => client.Object.RestartAsync("source", new RestartOrchestrationOptions { NewInstanceId = "target" }); + + // Assert + act.Should().Throw(); + } + + static GrpcDurableTaskClient CreateClient(Mock invoker) => + new("test", new GrpcDurableTaskClientOptions { CallInvoker = invoker.Object, EnableEntitySupport = true }, + NullLogger.Instance); + + static Mock CreateInvoker(Func> response) + { + Mock invoker = new(MockBehavior.Strict); + invoker.Setup(x => x.AsyncUnaryCall( + It.IsAny>(), + It.IsAny(), It.IsAny(), It.IsAny())) + .Returns((Method _, string? _, CallOptions options, + P.RestartInstanceRequest request) => + new AsyncUnaryCall( + response(request, options), Task.FromResult(new Metadata()), () => Status.DefaultSuccess, + () => new Metadata(), () => { })); + return invoker; + } +} diff --git a/test/Worker/Core.Tests/Shims/TaskOrchestrationContextWrapperTests.cs b/test/Worker/Core.Tests/Shims/TaskOrchestrationContextWrapperTests.cs index 6854438cc..822525d63 100644 --- a/test/Worker/Core.Tests/Shims/TaskOrchestrationContextWrapperTests.cs +++ b/test/Worker/Core.Tests/Shims/TaskOrchestrationContextWrapperTests.cs @@ -27,6 +27,45 @@ public void Ctor_NullParent_Populates() VerifyWrapper(wrapper, innerContext, invocationContext, input); } + [Theory] + [InlineData(null)] + [InlineData("original-instance")] + [InlineData("previous-clone")] + public void SourceInstanceId_ReadsImmediateSourceFromProperties(string? source) + { + // Arrange + TestOrchestrationContext innerContext = new(); + OrchestrationInvocationContext invocationContext = new("Test", new(), NullLoggerFactory.Instance, null); + Dictionary properties = new(); + if (source is not null) + { + properties["sourceInstanceId"] = source; + } + + TaskOrchestrationContextWrapper wrapper = new(innerContext, invocationContext, "input", properties); + + // Act + string? actual = wrapper.SourceInstanceId; + + // Assert + actual.Should().Be(source); + wrapper.Parent.Should().BeNull(); + } + + [Fact] + public void SourceInstanceId_WithoutProperties_IsNull() + { + // Arrange + TaskOrchestrationContextWrapper wrapper = new( + new TestOrchestrationContext(), new("Test", new(), NullLoggerFactory.Instance, null), "input"); + + // Act + string? source = wrapper.SourceInstanceId; + + // Assert + source.Should().BeNull(); + } + [Fact] public void Ctor_NonNullParent_Populates() { diff --git a/test/Worker/Grpc.Tests/GrpcDurableTaskWorkerTests.cs b/test/Worker/Grpc.Tests/GrpcDurableTaskWorkerTests.cs index 61c3cdf83..304eab40f 100644 --- a/test/Worker/Grpc.Tests/GrpcDurableTaskWorkerTests.cs +++ b/test/Worker/Grpc.Tests/GrpcDurableTaskWorkerTests.cs @@ -48,6 +48,72 @@ public class GrpcDurableTaskWorkerTests .GetNestedType("Processor", BindingFlags.NonPublic)! .GetMethod("OnRunOrchestratorAsync", BindingFlags.Instance | BindingFlags.NonPublic)!; + [Theory] + [InlineData(null)] + [InlineData("original-instance")] + [InlineData("previous-clone")] + public async Task OnRunOrchestratorAsync_Properties_ExposeImmediateSource(string? source) + { + // Arrange + P.OrchestratorRequest request = new() + { + InstanceId = "clone", + ExecutionId = "clone-execution", + NewEvents = + { + new P.HistoryEvent + { + Timestamp = Timestamp.FromDateTime(DateTime.UtcNow), + ExecutionStarted = new P.ExecutionStartedEvent + { + Name = "CloneOrchestration", + OrchestrationInstance = new P.OrchestrationInstance + { + InstanceId = "clone", + ExecutionId = "clone-execution", + }, + }, + }, + }, + }; + if (source is not null) + { + request.Properties.Add("sourceInstanceId", Value.ForString(source)); + } + + P.OrchestratorResponse? completed = null; + Mock clientMock = new( + MockBehavior.Strict, new object[] { Mock.Of() }); + clientMock.Setup(client => client.CompleteOrchestratorTaskAsync( + It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny())) + .Callback( + (response, _, _, _) => completed = response) + .Returns(CreateUnaryCall(Task.FromResult(new P.CompleteTaskResponse()))); + ITaskOrchestrator? orchestrator = FuncTaskOrchestrator.Create( + (context, _) => Task.FromResult(context.SourceInstanceId)); + Mock factoryMock = new(MockBehavior.Strict); + factoryMock.Setup(factory => factory.TryCreateOrchestrator( + new TaskName("CloneOrchestration"), It.IsAny(), out orchestrator)) + .Returns(true); + using ServiceProvider services = new ServiceCollection().BuildServiceProvider(); + GrpcDurableTaskWorker worker = CreateWorker( + new GrpcDurableTaskWorkerOptions(), new DurableTaskWorkerOptions(), NullLoggerFactory.Instance, + factoryMock.Object, services); + + // Act + await InvokeOnRunOrchestratorAsync( + CreateProcessor(worker, clientMock.Object), request, "completion-token", CancellationToken.None); + + // Assert + completed.Should().NotBeNull(); + completed!.Actions.Should().ContainSingle(); + completed.Actions[0].CompleteOrchestration.OrchestrationStatus.Should().Be(P.OrchestrationStatus.Completed); + completed.Actions[0].CompleteOrchestration.Result.Should().Be(source is null ? null : $"\"{source}\""); + clientMock.VerifyAll(); + factoryMock.VerifyAll(); + } + [Fact] public async Task ExecuteAsync_ConnectFailureThreshold_RecreatesConfiguredChannel() { diff --git a/test/Worker/Grpc.Tests/GrpcOrchestrationRunnerTests.cs b/test/Worker/Grpc.Tests/GrpcOrchestrationRunnerTests.cs index 0bb6be24a..0381549cf 100644 --- a/test/Worker/Grpc.Tests/GrpcOrchestrationRunnerTests.cs +++ b/test/Worker/Grpc.Tests/GrpcOrchestrationRunnerTests.cs @@ -498,6 +498,69 @@ public void Null_ExtendedSessionsCache_IsOkay() Assert.Equal(Protobuf.OrchestrationStatus.Completed, response.Actions[0].CompleteOrchestration.OrchestrationStatus); } + [Theory] + [InlineData(null, false)] + [InlineData("original-instance", false)] + [InlineData("previous-clone", false)] + [InlineData(null, true)] + [InlineData("original-instance", true)] + [InlineData("previous-clone", true)] + public void SourceInstanceId_FlowsThroughPropertiesOnExecutionAndReplay(string? source, bool replay) + { + // Arrange + Protobuf.HistoryEvent started = new() + { + EventId = -1, + Timestamp = Timestamp.FromDateTime(DateTime.UtcNow), + ExecutionStarted = new() + { + Name = "CloneOrchestration", + Input = "\"original-input\"", + OrchestrationInstance = new() + { + InstanceId = TestInstanceId, + ExecutionId = TestExecutionId, + }, + }, + }; + Protobuf.OrchestratorRequest request = CreateOrchestratorRequest(replay ? [] : [started]); + if (replay) + { + request.PastEvents.Add(started); + } + + if (source is not null) + { + request.Properties.Add("sourceInstanceId", Value.ForString(source)); + } + + string? actualSource = null; + bool? actualReplay = null; + string? actualInput = null; + ITaskOrchestrator orchestrator = FuncTaskOrchestrator.Create((context, _) => + { + actualSource = context.SourceInstanceId; + actualReplay = context.IsReplaying; + actualInput = context.GetInput(); + return Task.FromResult(context.SourceInstanceId); + }); + + // Act + string encodedResponse = GrpcOrchestrationRunner.LoadAndRun( + Convert.ToBase64String(request.ToByteArray()), orchestrator); + Protobuf.OrchestratorResponse response = Protobuf.OrchestratorResponse.Parser.ParseFrom( + Convert.FromBase64String(encodedResponse)); + + // Assert + actualSource.Should().Be(source); + actualReplay.Should().Be(replay); + actualInput.Should().Be("original-input"); + response.Actions.Should().ContainSingle(); + response.Actions[0].CompleteOrchestration.OrchestrationStatus.Should().Be(Protobuf.OrchestrationStatus.Completed); + response.Actions[0].CompleteOrchestration.Result.Should().Be( + source is null ? null : $"\"{source}\""); + } + static Protobuf.OrchestratorRequest CreateOrchestratorRequest(IEnumerable newEvents) { var orchestratorRequest = new Protobuf.OrchestratorRequest() From 844a78ebcbafd78aecf29238eec1d072c5959f2d Mon Sep 17 00:00:00 2001 From: Varshi Bachu Date: Tue, 10 Nov 2026 09:44:17 -0800 Subject: [PATCH 2/2] Use clone RPC and address restart API review feedback --- README.md | 22 +- src/Abstractions/TaskOrchestrationContext.cs | 1 + src/Client/Core/DurableTaskClient.cs | 32 +-- .../Core/RestartOrchestrationOptions.cs | 24 --- src/Client/Grpc/GrpcDurableTaskClient.cs | 86 +++++--- src/Grpc/orchestrator_service.proto | 42 ++-- src/Grpc/versions.txt | 11 +- src/Shared/Grpc/ProtoUtils.cs | 14 ++ .../Grpc/GrpcDurableTaskWorker.Processor.cs | 4 +- src/Worker/Grpc/GrpcOrchestrationRunner.cs | 4 +- .../GrpcDurableTaskClientRestartTests.cs | 189 +++++++++++++----- .../GrpcDurableTaskClientIntegrationTests.cs | 28 +++ .../Grpc.Tests/GrpcDurableTaskWorkerTests.cs | 19 +- .../GrpcOrchestrationRunnerTests.cs | 16 +- 14 files changed, 329 insertions(+), 163 deletions(-) delete mode 100644 src/Client/Core/RestartOrchestrationOptions.cs diff --git a/README.md b/README.md index 468cb1c9a..d0e1157a5 100644 --- a/README.md +++ b/README.md @@ -90,30 +90,14 @@ You can find the full sample file, including detailed comments, at [samples/Azur ### Restarting as a clone -With a backend that supports explicit restart IDs, restart an orchestration from the beginning with its original -name and input, a chosen target instance ID, and an optional version: - ```csharp string cloneId = await client.RestartAsync( "source-instance", - new RestartOrchestrationOptions { NewInstanceId = "clone-instance", Version = "v2" }); + "clone-instance", + version: "v2", + cancellation: CancellationToken.None); ``` -Execution history is not copied. Inside the cloned orchestrator, `context.SourceInstanceId` identifies the immediate -source (`"source-instance"` above). Cloning that clone identifies `"clone-instance"` as the next clone's source. -Lineage is separate from `context.Parent` and is not inherited by sub-orchestrations. Without backend-supplied lineage, -`SourceInstanceId` is `null`. - -Omit `Version` (or use `null`) to use the backend's restart default, which is not necessarily the source version. -For example, Durable Functions uses its configured default version. Use `Version = ""` to explicitly request an -unversioned orchestration. The existing `RestartAsync(instanceId, restartWithNewInstanceId)` overload is unchanged. - -**Server compatibility:** Upgrade the Durable Functions extension or other backend to a version supporting these -options before calling this overload. Older gRPC servers may ignore the added fields and create an unintended -legacy restart with a generated instance ID. The client rejects a returned ID that differs from the requested target, but cannot undo that restart -or detect an ignored version override. Backends and clients without support can reject the operation; the -orchestration-service client shim does not implement this overload. - ### Class-based syntax **IMPORTANT**: class based syntax in Durable Functions relies on a package reference to `Microsoft.DurableTask.Generators`. This is still in "preview" and may be subject to significant change before 1.0 or even post-1.0. It is recommended to stick with function-syntax for now. diff --git a/src/Abstractions/TaskOrchestrationContext.cs b/src/Abstractions/TaskOrchestrationContext.cs index d3a05bc4f..a128b785b 100644 --- a/src/Abstractions/TaskOrchestrationContext.cs +++ b/src/Abstractions/TaskOrchestrationContext.cs @@ -32,6 +32,7 @@ public abstract class TaskOrchestrationContext /// /// This is distinct from and is not inherited by sub-orchestrations. /// Cloning a clone identifies that clone as the immediate source, not its original ancestor. + /// The ID is an opaque string, even when it resembles a serialized timestamp. /// public virtual string? SourceInstanceId => this.Properties.TryGetValue("sourceInstanceId", out object? source) && source is string instanceId diff --git a/src/Client/Core/DurableTaskClient.cs b/src/Client/Core/DurableTaskClient.cs index d6f1c2318..8135037ef 100644 --- a/src/Client/Core/DurableTaskClient.cs +++ b/src/Client/Core/DurableTaskClient.cs @@ -470,30 +470,38 @@ public virtual Task RestartAsync( /// /// /// - /// This operation does not copy execution history. A supporting backend makes the immediate source instance ID - /// available through on the restarted orchestration. - /// The version is selected using , including backend-specific + /// This operation does not copy execution history. When the source and target IDs differ, a supporting backend + /// makes the immediate source instance ID available through + /// on the restarted orchestration. + /// The version is selected using , including backend-specific /// defaults when no override is provided. /// /// - /// This overload requires a backend that supports explicit restart IDs and version overrides. Older gRPC servers - /// may ignore these options and perform a legacy restart with a generated instance ID instead. + /// This overload requires a backend that supports cloning with explicit restart IDs and version overrides. + /// Older gRPC servers reject the separate clone request without performing a legacy restart. /// Upgrade the server before using this overload; a returned instance ID cannot verify whether a version override /// was honored. /// /// - /// The ID of the source orchestration. - /// The restart options, including the required, nonblank target instance ID. + /// The required, nonblank ID of the source orchestration. + /// The required, nonblank ID of the restarted orchestration. + /// + /// The version override for the restarted orchestration. A null value uses the backend's restart default, + /// which need not be the original version. An empty string explicitly selects the unversioned orchestration. + /// /// Cancels enqueueing the request, not execution once enqueued. /// The instance ID of the restarted orchestration. /// The source was not found or an instance ID is invalid. - /// is null. - /// The client or backend does not support these restart options. + /// is null. + /// The target instance ID conflicts with an existing instance. + /// The backend rejected the operation or returned an unexpected instance ID. + /// The client or backend does not support explicit restart IDs and version overrides. public virtual Task RestartAsync( string instanceId, - RestartOrchestrationOptions options, - CancellationToken cancellation = default) - => throw new NotSupportedException($"{this.GetType()} does not support orchestration restart options."); + string newInstanceId, + string? version, + CancellationToken cancellation) + => throw new NotSupportedException($"{this.GetType()} does not support explicit restart IDs and version overrides."); /// /// Rewinds the specified orchestration instance by re-executing any failed Activities, and recursively rewinding diff --git a/src/Client/Core/RestartOrchestrationOptions.cs b/src/Client/Core/RestartOrchestrationOptions.cs deleted file mode 100644 index 2c44b2b9d..000000000 --- a/src/Client/Core/RestartOrchestrationOptions.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace Microsoft.DurableTask.Client; - -/// -/// Options for restarting an orchestration from the beginning with a caller-selected instance ID. -/// -public sealed record RestartOrchestrationOptions -{ - /// - /// Gets the required, nonblank instance ID of the restarted orchestration. - /// - public string NewInstanceId { get; init; } = string.Empty; - - /// - /// Gets the optional version override for the restarted orchestration. - /// - /// - /// A null value uses the backend's restart default, which need not be the original version. - /// An empty string explicitly selects the unversioned orchestration. - /// - public string? Version { get; init; } -} diff --git a/src/Client/Grpc/GrpcDurableTaskClient.cs b/src/Client/Grpc/GrpcDurableTaskClient.cs index 80bd6fed5..75b9858db 100644 --- a/src/Client/Grpc/GrpcDurableTaskClient.cs +++ b/src/Client/Grpc/GrpcDurableTaskClient.cs @@ -123,11 +123,14 @@ public override async Task ScheduleNewOrchestrationInstanceAsync( } DateTimeOffset? startAt = options?.StartAt; - this.logger.SchedulingOrchestration( - request.InstanceId ?? string.Empty, - orchestratorName, - sizeInBytes: request.Input != null ? Encoding.UTF8.GetByteCount(request.Input) : 0, - startAt.GetValueOrDefault(DateTimeOffset.UtcNow)); + if (this.logger.IsEnabled(LogLevel.Information)) + { + this.logger.SchedulingOrchestration( + request.InstanceId ?? string.Empty, + orchestratorName, + sizeInBytes: request.Input != null ? Encoding.UTF8.GetByteCount(request.Input) : 0, + startAt.GetValueOrDefault(DateTimeOffset.UtcNow)); + } if (startAt.HasValue) { @@ -532,42 +535,69 @@ public override async Task RestartAsync( RestartWithNewInstanceId = restartWithNewInstanceId, }; - return await this.RestartInstanceCoreAsync(request, cancellation); + P.RestartInstanceResponse result = await this.InvokeRestartRpcAsync( + instanceId, + () => this.sidecarClient.RestartInstanceAsync(request, cancellationToken: cancellation).ResponseAsync, + cancellation); + return result.InstanceId; } /// public override async Task RestartAsync( string instanceId, - RestartOrchestrationOptions options, - CancellationToken cancellation = default) + string newInstanceId, + string? version, + CancellationToken cancellation) { Check.NotNullOrEmpty(instanceId); + if (string.IsNullOrWhiteSpace(instanceId)) + { + throw new ArgumentException("A nonblank source instance ID is required.", nameof(instanceId)); + } + Check.NotEntity(this.options.EnableEntitySupport, instanceId); - Check.NotNull(options); - if (string.IsNullOrWhiteSpace(options.NewInstanceId)) + if (string.IsNullOrWhiteSpace(newInstanceId)) { - throw new ArgumentException("A nonblank target instance ID is required.", nameof(options)); + throw new ArgumentException("A nonblank target instance ID is required.", nameof(newInstanceId)); } - Check.NotEntity(this.options.EnableEntitySupport, options.NewInstanceId); - P.RestartInstanceRequest request = new() + Check.NotEntity(this.options.EnableEntitySupport, newInstanceId); + P.CloneInstanceRequest request = new() { - InstanceId = instanceId, - RestartWithNewInstanceId = true, - NewInstanceId = options.NewInstanceId, - Version = options.Version, + SourceInstanceId = instanceId, + NewInstanceId = newInstanceId, + Version = version, }; - string result = await this.RestartInstanceCoreAsync(request, cancellation); - if (!string.Equals(result, options.NewInstanceId, StringComparison.Ordinal)) + P.CloneInstanceResponse response; + try + { + response = await this.InvokeRestartRpcAsync( + instanceId, + () => this.sidecarClient.CloneInstanceAsync(request, cancellationToken: cancellation).ResponseAsync, + cancellation); + } + catch (RpcException e) when (e.StatusCode == StatusCode.AlreadyExists) { - throw new NotSupportedException( - $"The backend returned restart instance ID '{result}' instead of the requested ID " - + $"'{options.NewInstanceId}'. It may not support explicit restart instance IDs. " - + "A legacy restart may already have occurred."); + throw new OrchestrationAlreadyExistsException(e.Status.Detail); + } + catch (RpcException e) when (e.StatusCode == StatusCode.InvalidArgument) + { + throw new ArgumentException(e.Status.Detail, e); + } + catch (RpcException e) when (e.StatusCode == StatusCode.Unimplemented) + { + throw new NotSupportedException("The backend does not support orchestration cloning.", e); } - return result; + if (!string.Equals(response.InstanceId, newInstanceId, StringComparison.Ordinal)) + { + throw new InvalidOperationException( + $"The backend returned clone instance ID '{response.InstanceId}' instead of the requested ID " + + $"'{newInstanceId}'."); + } + + return response.InstanceId; } /// @@ -781,14 +811,12 @@ static GrpcChannel GetChannel(string? address) } #endif - async Task RestartInstanceCoreAsync(P.RestartInstanceRequest request, CancellationToken cancellation) + async Task InvokeRestartRpcAsync( + string instanceId, Func> operation, CancellationToken cancellation) { - string instanceId = request.InstanceId; try { - P.RestartInstanceResponse result = await this.sidecarClient.RestartInstanceAsync( - request, cancellationToken: cancellation); - return result.InstanceId; + return await operation(); } catch (RpcException e) when (e.StatusCode == StatusCode.NotFound) { diff --git a/src/Grpc/orchestrator_service.proto b/src/Grpc/orchestrator_service.proto index b9f9f63d3..faa2aea60 100644 --- a/src/Grpc/orchestrator_service.proto +++ b/src/Grpc/orchestrator_service.proto @@ -533,25 +533,35 @@ message PurgeInstancesResponse { google.protobuf.BoolValue isComplete = 2; } -// Restarts an orchestration from the beginning with its original name and input, -// without copying its history. message RestartInstanceRequest { string instanceId = 1; - - // When newInstanceId is absent, true generates a new instance ID and false - // restarts using instanceId. bool restartWithNewInstanceId = 2; +} + +message RestartInstanceResponse { + string instanceId = 1; +} + +// Restarts an orchestration from the beginning with the source's original name +// and input, without copying its history. When source and target IDs differ, the +// clone's source lineage identifies sourceInstanceId (the immediate source), not +// an earlier ancestor. Sub-orchestrations must not inherit this source lineage. +message CloneInstanceRequest { + // Required, nonblank ID of the source orchestration. + string sourceInstanceId = 1; - // An explicit target instance ID. When present, takes precedence over - // restartWithNewInstanceId. - google.protobuf.StringValue newInstanceId = 3; + // Required, nonblank target ID; may equal sourceInstanceId. + // Target conflicts follow the backend's existing instance-ID conflict behavior. + string newInstanceId = 2; - // Overrides the restarted orchestration's version, including an empty string. - // When absent, preserves the server's default restart behavior. - google.protobuf.StringValue version = 4; + // Overrides the cloned orchestration's version when present. An explicit + // empty string selects an unversioned orchestration; absence preserves the + // backend's default restart behavior. + google.protobuf.StringValue version = 3; } -message RestartInstanceResponse { +message CloneInstanceResponse { + // The requested target instance ID. string instanceId = 1; } @@ -773,6 +783,14 @@ service TaskHubSidecarService { // Restarts an orchestration instance. rpc RestartInstance(RestartInstanceRequest) returns (RestartInstanceResponse); + // Clones an orchestration to an explicit target instance ID. + // Implementations must reject invalid requests and unsupported cloning or + // version semantics before scheduling or creating any orchestration. + // Options must not be ignored, and callers and servers must not fall back + // to RestartInstance. Servers without this RPC return UNIMPLEMENTED without + // invoking RestartInstance. + rpc CloneInstance(CloneInstanceRequest) returns (CloneInstanceResponse); + // Waits for an orchestration instance to reach a running or completion state. rpc WaitForInstanceStart(GetInstanceRequest) returns (GetInstanceResponse); diff --git a/src/Grpc/versions.txt b/src/Grpc/versions.txt index 693290d94..db9e88c3b 100644 --- a/src/Grpc/versions.txt +++ b/src/Grpc/versions.txt @@ -1,7 +1,4 @@ -# The following files were downloaded from branch main at 2026-10-20 19:46:22 UTC -# RestartInstanceRequest patch imported from local durabletask-protobuf commit -# 962a493037e72b5e08f07a55eff0f121c1aaae80 (not yet published upstream). -# Base download URLs below remain unchanged; refresh after that commit is published upstream. -https://raw.githubusercontent.com/microsoft/durabletask-protobuf/20d2aadae358d8aa526190cbf78fb6c313b0b3db/protos/orchestrator_service.proto -https://raw.githubusercontent.com/microsoft/durabletask-protobuf/20d2aadae358d8aa526190cbf78fb6c313b0b3db/protos/durable-task-scheduler/sandbox_service.proto -https://raw.githubusercontent.com/microsoft/durabletask-protobuf/20d2aadae358d8aa526190cbf78fb6c313b0b3db/protos/durable-task-scheduler/large_payload_purge.proto +# The following files were downloaded from branch vabachu/orchestration-clone-protocol at 2026-11-10 05:20:38 UTC +https://raw.githubusercontent.com/microsoft/durabletask-protobuf/4fb1fb241603166f4283a5d61842f0ff55c5da84/protos/orchestrator_service.proto +https://raw.githubusercontent.com/microsoft/durabletask-protobuf/4fb1fb241603166f4283a5d61842f0ff55c5da84/protos/durable-task-scheduler/sandbox_service.proto +https://raw.githubusercontent.com/microsoft/durabletask-protobuf/4fb1fb241603166f4283a5d61842f0ff55c5da84/protos/durable-task-scheduler/large_payload_purge.proto diff --git a/src/Shared/Grpc/ProtoUtils.cs b/src/Shared/Grpc/ProtoUtils.cs index 45779e676..9a867eb13 100644 --- a/src/Shared/Grpc/ProtoUtils.cs +++ b/src/Shared/Grpc/ProtoUtils.cs @@ -1122,6 +1122,20 @@ internal static T Base64Decode(this MessageParser parser, string encodedMessa kvp => ConvertValueToObject(kvp.Value)); } + /// + /// Converts orchestration request properties, preserving source instance IDs as opaque strings. + /// + /// The orchestration request properties to convert. + /// The converted orchestration properties. + internal static Dictionary ConvertOrchestrationProperties(MapField properties) + { + return properties.ToDictionary( + pair => pair.Key, + pair => pair.Key == "sourceInstanceId" && pair.Value.KindCase == Value.KindOneofCase.StringValue + ? pair.Value.StringValue + : ConvertValueToObject(pair.Value)); + } + /// /// Converts a C# object to a protobuf Value. /// diff --git a/src/Worker/Grpc/GrpcDurableTaskWorker.Processor.cs b/src/Worker/Grpc/GrpcDurableTaskWorker.Processor.cs index 1680d225e..e8f95a639 100644 --- a/src/Worker/Grpc/GrpcDurableTaskWorker.Processor.cs +++ b/src/Worker/Grpc/GrpcDurableTaskWorker.Processor.cs @@ -877,9 +877,7 @@ await this.ExecuteWithRetryAsync( _ => null, }; - Dictionary properties = request.Properties.ToDictionary( - pair => pair.Key, - pair => ProtoUtils.ConvertValueToObject(pair.Value)); + Dictionary properties = ProtoUtils.ConvertOrchestrationProperties(request.Properties); TaskOrchestration shim = this.shimFactory.CreateOrchestration(name, orchestrator, properties, parent); TaskOrchestrationExecutor executor = new( runtimeState, diff --git a/src/Worker/Grpc/GrpcOrchestrationRunner.cs b/src/Worker/Grpc/GrpcOrchestrationRunner.cs index 5fbe2228d..17567227f 100644 --- a/src/Worker/Grpc/GrpcOrchestrationRunner.cs +++ b/src/Worker/Grpc/GrpcOrchestrationRunner.cs @@ -126,9 +126,7 @@ public static string LoadAndRun( List pastEvents = request.PastEvents.Select(ProtoUtils.ConvertHistoryEvent).ToList(); IEnumerable newEvents = request.NewEvents.Select(ProtoUtils.ConvertHistoryEvent); - Dictionary properties = request.Properties.ToDictionary( - pair => pair.Key, - pair => ProtoUtils.ConvertValueToObject(pair.Value)); + Dictionary properties = ProtoUtils.ConvertOrchestrationProperties(request.Properties); OrchestratorExecutionResult? result = null; diff --git a/test/Client/Grpc.Tests/GrpcDurableTaskClientRestartTests.cs b/test/Client/Grpc.Tests/GrpcDurableTaskClientRestartTests.cs index c269264e3..07f8c8038 100644 --- a/test/Client/Grpc.Tests/GrpcDurableTaskClientRestartTests.cs +++ b/test/Client/Grpc.Tests/GrpcDurableTaskClientRestartTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using DurableTask.Core.Exceptions; using Google.Protobuf; using Grpc.Core; using Microsoft.Extensions.Logging.Abstractions; @@ -11,35 +12,83 @@ namespace Microsoft.DurableTask.Client.Grpc.Tests; public class GrpcDurableTaskClientRestartTests { [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("v2")] - public async Task RestartAsync_Options_ForwardsExplicitTargetAndVersion(string? version) + [InlineData("target", null)] + [InlineData("target", "")] + [InlineData("target", "v2")] + [InlineData("source", null)] + public async Task RestartAsync_ExplicitInstanceId_UsesCloneRpcAndForwardsTargetAndVersion(string target, string? version) { // Arrange using CancellationTokenSource cancellation = new(); - P.RestartInstanceRequest? captured = null; + P.CloneInstanceRequest? captured = null; CancellationToken capturedCancellation = default; - Mock invoker = CreateInvoker((request, callOptions) => + Mock invoker = CreateInvoker((request, callOptions) => { - captured = P.RestartInstanceRequest.Parser.ParseFrom(request.ToByteArray()); + captured = P.CloneInstanceRequest.Parser.ParseFrom(request.ToByteArray()); capturedCancellation = callOptions.CancellationToken; - return Task.FromResult(new P.RestartInstanceResponse { InstanceId = "target" }); + return Task.FromResult(new P.CloneInstanceResponse { InstanceId = target }); }); await using GrpcDurableTaskClient client = CreateClient(invoker); // Act string result = await client.RestartAsync( - "source", new RestartOrchestrationOptions { NewInstanceId = "target", Version = version }, cancellation.Token); + "source", target, version, cancellation.Token); // Assert - result.Should().Be("target"); + result.Should().Be(target); captured.Should().NotBeNull(); - captured!.InstanceId.Should().Be("source"); - captured.NewInstanceId.Should().Be("target"); + captured!.SourceInstanceId.Should().Be("source"); + captured.NewInstanceId.Should().Be(target); captured.Version.Should().Be(version); - captured.RestartWithNewInstanceId.Should().BeTrue(); capturedCancellation.Should().Be(cancellation.Token); + invoker.Verify(x => x.AsyncUnaryCall( + It.Is>(method => method.Name == "CloneInstance"), + It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); + invoker.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task RestartAsync_LegacyDefaultArguments_UseRestartRpc(bool useBaseClient) + { + // Arrange + using CancellationTokenSource cancellation = new(); + List<(P.RestartInstanceRequest Request, CancellationToken Cancellation)> captured = new(); + Mock invoker = CreateInvoker((request, callOptions) => + { + captured.Add((P.RestartInstanceRequest.Parser.ParseFrom(request.ToByteArray()), callOptions.CancellationToken)); + return Task.FromResult(new P.RestartInstanceResponse { InstanceId = "source" }); + }); + await using GrpcDurableTaskClient grpcClient = CreateClient(invoker); + DurableTaskClient client = grpcClient; + + // Act + string[] results = useBaseClient + ? new[] + { + await client.RestartAsync("source"), + await client.RestartAsync("source", default), + await client.RestartAsync("source", default, default), + await client.RestartAsync("source", default, cancellation.Token), + } + : new[] + { + await grpcClient.RestartAsync("source"), + await grpcClient.RestartAsync("source", default), + await grpcClient.RestartAsync("source", default, default), + await grpcClient.RestartAsync("source", default, cancellation.Token), + }; + + // Assert + results.Should().Equal("source", "source", "source", "source"); + captured.Should().HaveCount(4); + captured.Should().OnlyContain(call => call.Request.InstanceId == "source" && !call.Request.RestartWithNewInstanceId); + captured.Select(call => call.Cancellation).Should().Equal(default, default, default, cancellation.Token); + invoker.Verify(x => x.AsyncUnaryCall( + It.Is>(method => method.Name == "RestartInstance"), + It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(4)); + invoker.VerifyNoOtherCalls(); } [Theory] @@ -49,7 +98,7 @@ public async Task RestartAsync_LegacyBool_PreservesRequest(bool newInstanceId) { // Arrange P.RestartInstanceRequest? captured = null; - Mock invoker = CreateInvoker((request, _) => + Mock invoker = CreateInvoker((request, _) => { captured = P.RestartInstanceRequest.Parser.ParseFrom(request.ToByteArray()); return Task.FromResult(new P.RestartInstanceResponse { InstanceId = "returned-id" }); @@ -63,8 +112,10 @@ public async Task RestartAsync_LegacyBool_PreservesRequest(bool newInstanceId) result.Should().Be("returned-id"); captured!.InstanceId.Should().Be("source"); captured.RestartWithNewInstanceId.Should().Be(newInstanceId); - captured.NewInstanceId.Should().BeNull(); - captured.Version.Should().BeNull(); + invoker.Verify(x => x.AsyncUnaryCall( + It.Is>(method => method.Name == "RestartInstance"), + It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); + invoker.VerifyNoOtherCalls(); } [Theory] @@ -78,16 +129,18 @@ public async Task RestartAsync_InvalidTarget_DoesNotSendRequest(string? target) await using GrpcDurableTaskClient client = CreateClient(invoker); // Act - Func act = () => client.RestartAsync("source", new RestartOrchestrationOptions { NewInstanceId = target! }); + Func act = () => client.RestartAsync("source", target!, null, default); // Assert - await act.Should().ThrowAsync(); + await act.Should().ThrowAsync().WithParameterName("newInstanceId"); invoker.VerifyNoOtherCalls(); } [Theory] [InlineData(null)] [InlineData("")] + [InlineData(" ")] + [InlineData("\t")] public async Task RestartAsync_InvalidSource_DoesNotSendRequest(string? source) { // Arrange @@ -95,58 +148,73 @@ public async Task RestartAsync_InvalidSource_DoesNotSendRequest(string? source) await using GrpcDurableTaskClient client = CreateClient(invoker); // Act - Func act = () => client.RestartAsync(source!, new RestartOrchestrationOptions { NewInstanceId = "target" }); + Func act = () => client.RestartAsync(source!, "target", null, default); // Assert await act.Should().ThrowAsync(); invoker.VerifyNoOtherCalls(); } - [Fact] - public async Task RestartAsync_NullOptions_DoesNotSendRequest() + [Theory] + [InlineData("@counter@source", "target")] + [InlineData("source", "@counter@target")] + public async Task RestartAsync_EntityId_DoesNotSendRequest(string source, string target) { // Arrange Mock invoker = new(MockBehavior.Strict); await using GrpcDurableTaskClient client = CreateClient(invoker); // Act - Func act = () => client.RestartAsync("source", (RestartOrchestrationOptions)null!); + Func act = () => client.RestartAsync(source, target, null, default); // Assert - await act.Should().ThrowAsync(); + await act.Should().ThrowAsync(); invoker.VerifyNoOtherCalls(); } - [Theory] - [InlineData("@counter@source", "target")] - [InlineData("source", "@counter@target")] - public async Task RestartAsync_EntityId_DoesNotSendRequest(string source, string target) + [Fact] + public async Task RestartAsync_CloneResponseWithWrongTarget_ThrowsInvalidOperation() { // Arrange - Mock invoker = new(MockBehavior.Strict); + Mock invoker = CreateInvoker((_, _) => + Task.FromResult(new P.CloneInstanceResponse { InstanceId = "unexpected-id" })); await using GrpcDurableTaskClient client = CreateClient(invoker); // Act - Func act = () => client.RestartAsync(source, new RestartOrchestrationOptions { NewInstanceId = target }); + Func act = () => client.RestartAsync("source", "target", null, default); // Assert - await act.Should().ThrowAsync(); - invoker.VerifyNoOtherCalls(); + await act.Should().ThrowAsync() + .WithMessage("*unexpected-id*target*"); } - [Fact] - public async Task RestartAsync_ServerIgnoresExplicitTarget_ThrowsNotSupported() + [Theory] + [InlineData(StatusCode.NotFound, typeof(ArgumentException))] + [InlineData(StatusCode.FailedPrecondition, typeof(InvalidOperationException))] + [InlineData(StatusCode.InvalidArgument, typeof(ArgumentException))] + [InlineData(StatusCode.AlreadyExists, typeof(OrchestrationAlreadyExistsException))] + [InlineData(StatusCode.Cancelled, typeof(OperationCanceledException))] + [InlineData(StatusCode.Unimplemented, typeof(NotSupportedException))] + [InlineData(StatusCode.Unavailable, typeof(RpcException))] + public async Task RestartAsync_ExplicitInstanceId_RpcError_MapsError(StatusCode status, Type expectedException) { // Arrange - Mock invoker = CreateInvoker((_, _) => - Task.FromResult(new P.RestartInstanceResponse { InstanceId = "generated-id" })); + using CancellationTokenSource cancellation = new(); + Mock invoker = CreateInvoker((_, _) => + Task.FromException(new RpcException(new Status(status, "test failure")))); await using GrpcDurableTaskClient client = CreateClient(invoker); // Act - Func act = () => client.RestartAsync("source", new RestartOrchestrationOptions { NewInstanceId = "target" }); + Func act = () => client.RestartAsync( + "source", "target", null, cancellation.Token); // Assert - await act.Should().ThrowAsync().WithMessage("*legacy restart may already have occurred*"); + Exception exception = (await act.Should().ThrowAsync()).Which; + exception.GetType().Should().Be(expectedException); + if (exception is OperationCanceledException canceled) + { + canceled.CancellationToken.Should().Be(cancellation.Token); + } } [Theory] @@ -154,17 +222,17 @@ public async Task RestartAsync_ServerIgnoresExplicitTarget_ThrowsNotSupported() [InlineData(StatusCode.FailedPrecondition, typeof(InvalidOperationException))] [InlineData(StatusCode.Cancelled, typeof(OperationCanceledException))] [InlineData(StatusCode.Unimplemented, typeof(RpcException))] - public async Task RestartAsync_RpcError_PreservesErrorMapping(StatusCode status, Type expectedException) + [InlineData(StatusCode.AlreadyExists, typeof(RpcException))] + public async Task RestartAsync_LegacyBool_RpcError_PreservesErrorMapping(StatusCode status, Type expectedException) { // Arrange using CancellationTokenSource cancellation = new(); - Mock invoker = CreateInvoker((_, _) => + Mock invoker = CreateInvoker((_, _) => Task.FromException(new RpcException(new Status(status, "test failure")))); await using GrpcDurableTaskClient client = CreateClient(invoker); // Act - Func act = () => client.RestartAsync( - "source", new RestartOrchestrationOptions { NewInstanceId = "target" }, cancellation.Token); + Func act = () => client.RestartAsync("source", true, cancellation.Token); // Assert Exception exception = (await act.Should().ThrowAsync()).Which; @@ -176,13 +244,35 @@ public async Task RestartAsync_RpcError_PreservesErrorMapping(StatusCode status, } [Fact] - public void RestartAsync_BaseImplementation_DoesNotSilentlyIgnoreOptions() + public async Task RestartAsync_ExplicitInstanceId_UnsupportedServer_DoesNotFallbackToRestart() + { + // Arrange + Mock invoker = CreateInvoker((_, _) => + Task.FromException( + new RpcException(new Status(StatusCode.Unimplemented, "unknown method")))); + await using GrpcDurableTaskClient client = CreateClient(invoker); + + // Act + Func act = () => client.RestartAsync("source", "target", null, default); + + // Assert + NotSupportedException exception = (await act.Should().ThrowAsync()).Which; + exception.InnerException.Should().BeOfType() + .Which.StatusCode.Should().Be(StatusCode.Unimplemented); + invoker.Verify(x => x.AsyncUnaryCall( + It.Is>(method => method.Name == "CloneInstance"), + It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); + invoker.VerifyNoOtherCalls(); + } + + [Fact] + public void RestartAsync_BaseImplementation_DoesNotSilentlyIgnoreExplicitInstanceId() { // Arrange Mock client = new("test") { CallBase = true }; // Act - Action act = () => client.Object.RestartAsync("source", new RestartOrchestrationOptions { NewInstanceId = "target" }); + Action act = () => client.Object.RestartAsync("source", "target", null, default); // Assert act.Should().Throw(); @@ -192,15 +282,16 @@ static GrpcDurableTaskClient CreateClient(Mock invoker) => new("test", new GrpcDurableTaskClientOptions { CallInvoker = invoker.Object, EnableEntitySupport = true }, NullLogger.Instance); - static Mock CreateInvoker(Func> response) + static Mock CreateInvoker(Func> response) + where TRequest : class + where TResponse : class { Mock invoker = new(MockBehavior.Strict); invoker.Setup(x => x.AsyncUnaryCall( - It.IsAny>(), - It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((Method _, string? _, CallOptions options, - P.RestartInstanceRequest request) => - new AsyncUnaryCall( + It.IsAny>(), + It.IsAny(), It.IsAny(), It.IsAny())) + .Returns((Method _, string? _, CallOptions options, TRequest request) => + new AsyncUnaryCall( response(request, options), Task.FromResult(new Metadata()), () => Status.DefaultSuccess, () => new Metadata(), () => { })); return invoker; diff --git a/test/Grpc.IntegrationTests/GrpcDurableTaskClientIntegrationTests.cs b/test/Grpc.IntegrationTests/GrpcDurableTaskClientIntegrationTests.cs index 5fd9dc009..36cca5a76 100644 --- a/test/Grpc.IntegrationTests/GrpcDurableTaskClientIntegrationTests.cs +++ b/test/Grpc.IntegrationTests/GrpcDurableTaskClientIntegrationTests.cs @@ -280,6 +280,34 @@ public async Task RestartAsync_EndToEnd(bool restartWithNewInstanceId) restartedMetadata!.RuntimeStatus.Should().Be(OrchestrationRuntimeStatus.Completed); } + [Fact] + public async Task RestartAsync_ExplicitInstanceId_UnsupportedServer_DoesNotRestartOrCreateInstance() + { + // Arrange + await using HostTestLifetime server = await this.StartAsync(); + string source = await server.Client.ScheduleNewOrchestrationInstanceAsync( + OrchestrationName, input: false, cancellation: this.TimeoutToken); + await server.Client.WaitForInstanceStartAsync(source, this.TimeoutToken); + await server.Client.RaiseEventAsync(source, "event", cancellation: this.TimeoutToken); + OrchestrationMetadata original = await server.Client.WaitForInstanceCompletionAsync(source, this.TimeoutToken); + List before = await server.Client.GetAllInstancesAsync().ToListAsync(this.TimeoutToken); + string target = Guid.NewGuid().ToString("N"); + + // Act + Func act = () => server.Client.RestartAsync( + source, target, null, this.TimeoutToken); + + // Assert + await act.Should().ThrowAsync(); + List after = await server.Client.GetAllInstancesAsync().ToListAsync(this.TimeoutToken); + after.Select(instance => instance.InstanceId).Should().BeEquivalentTo(before.Select(instance => instance.InstanceId)); + (await server.Client.GetInstanceAsync(target, cancellation: this.TimeoutToken)).Should().BeNull(); + OrchestrationMetadata? sourceAfter = await server.Client.GetInstanceAsync(source, cancellation: this.TimeoutToken); + sourceAfter.Should().NotBeNull(); + sourceAfter!.RuntimeStatus.Should().Be(OrchestrationRuntimeStatus.Completed); + sourceAfter.CreatedAt.Should().Be(original.CreatedAt); + } + [Fact] public async Task RestartAsync_InstanceNotFound_ThrowsArgumentException() { diff --git a/test/Worker/Grpc.Tests/GrpcDurableTaskWorkerTests.cs b/test/Worker/Grpc.Tests/GrpcDurableTaskWorkerTests.cs index 304eab40f..0e1d0c729 100644 --- a/test/Worker/Grpc.Tests/GrpcDurableTaskWorkerTests.cs +++ b/test/Worker/Grpc.Tests/GrpcDurableTaskWorkerTests.cs @@ -10,6 +10,7 @@ using Google.Protobuf.WellKnownTypes; using Grpc.Core; using Microsoft.DurableTask; +using Microsoft.DurableTask.Converters; using Microsoft.DurableTask.Tests.Logging; using Microsoft.DurableTask.Worker; using Microsoft.DurableTask.Worker.Grpc.Internal; @@ -52,6 +53,8 @@ public class GrpcDurableTaskWorkerTests [InlineData(null)] [InlineData("original-instance")] [InlineData("previous-clone")] + [InlineData("dt:2026-01-01T00:00:00.0000000Z")] + [InlineData("dto:2026-01-01T00:00:00.0000000+00:00")] public async Task OnRunOrchestratorAsync_Properties_ExposeImmediateSource(string? source) { // Arrange @@ -81,6 +84,8 @@ public async Task OnRunOrchestratorAsync_Properties_ExposeImmediateSource(string request.Properties.Add("sourceInstanceId", Value.ForString(source)); } + request.Properties.Add("dateTime", Value.ForString("dt:2026-01-01T00:00:00.0000000Z")); + request.Properties.Add("dateTimeOffset", Value.ForString("dto:2026-01-01T00:00:00.0000000+00:00")); P.OrchestratorResponse? completed = null; Mock clientMock = new( MockBehavior.Strict, new object[] { Mock.Of() }); @@ -90,8 +95,14 @@ public async Task OnRunOrchestratorAsync_Properties_ExposeImmediateSource(string .Callback( (response, _, _, _) => completed = response) .Returns(CreateUnaryCall(Task.FromResult(new P.CompleteTaskResponse()))); - ITaskOrchestrator? orchestrator = FuncTaskOrchestrator.Create( - (context, _) => Task.FromResult(context.SourceInstanceId)); + object? actualDateTime = null; + object? actualDateTimeOffset = null; + ITaskOrchestrator? orchestrator = FuncTaskOrchestrator.Create((context, _) => + { + actualDateTime = context.Properties["dateTime"]; + actualDateTimeOffset = context.Properties["dateTimeOffset"]; + return Task.FromResult(context.SourceInstanceId); + }); Mock factoryMock = new(MockBehavior.Strict); factoryMock.Setup(factory => factory.TryCreateOrchestrator( new TaskName("CloneOrchestration"), It.IsAny(), out orchestrator)) @@ -109,7 +120,9 @@ await InvokeOnRunOrchestratorAsync( completed.Should().NotBeNull(); completed!.Actions.Should().ContainSingle(); completed.Actions[0].CompleteOrchestration.OrchestrationStatus.Should().Be(P.OrchestrationStatus.Completed); - completed.Actions[0].CompleteOrchestration.Result.Should().Be(source is null ? null : $"\"{source}\""); + JsonDataConverter.Default.Deserialize(completed.Actions[0].CompleteOrchestration.Result).Should().Be(source); + actualDateTime.Should().BeOfType().Which.Should().Be(new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)); + actualDateTimeOffset.Should().BeOfType().Which.Should().Be(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)); clientMock.VerifyAll(); factoryMock.VerifyAll(); } diff --git a/test/Worker/Grpc.Tests/GrpcOrchestrationRunnerTests.cs b/test/Worker/Grpc.Tests/GrpcOrchestrationRunnerTests.cs index 0381549cf..b71b645f2 100644 --- a/test/Worker/Grpc.Tests/GrpcOrchestrationRunnerTests.cs +++ b/test/Worker/Grpc.Tests/GrpcOrchestrationRunnerTests.cs @@ -4,6 +4,7 @@ using Google.Protobuf; using Google.Protobuf.Collections; using Google.Protobuf.WellKnownTypes; +using Microsoft.DurableTask.Converters; using Microsoft.Extensions.Caching.Memory; namespace Microsoft.DurableTask.Worker.Grpc.Tests; @@ -502,9 +503,13 @@ public void Null_ExtendedSessionsCache_IsOkay() [InlineData(null, false)] [InlineData("original-instance", false)] [InlineData("previous-clone", false)] + [InlineData("dt:2026-01-01T00:00:00.0000000Z", false)] + [InlineData("dto:2026-01-01T00:00:00.0000000+00:00", false)] [InlineData(null, true)] [InlineData("original-instance", true)] [InlineData("previous-clone", true)] + [InlineData("dt:2026-01-01T00:00:00.0000000Z", true)] + [InlineData("dto:2026-01-01T00:00:00.0000000+00:00", true)] public void SourceInstanceId_FlowsThroughPropertiesOnExecutionAndReplay(string? source, bool replay) { // Arrange @@ -534,14 +539,20 @@ public void SourceInstanceId_FlowsThroughPropertiesOnExecutionAndReplay(string? request.Properties.Add("sourceInstanceId", Value.ForString(source)); } + request.Properties.Add("dateTime", Value.ForString("dt:2026-01-01T00:00:00.0000000Z")); + request.Properties.Add("dateTimeOffset", Value.ForString("dto:2026-01-01T00:00:00.0000000+00:00")); string? actualSource = null; bool? actualReplay = null; string? actualInput = null; + object? actualDateTime = null; + object? actualDateTimeOffset = null; ITaskOrchestrator orchestrator = FuncTaskOrchestrator.Create((context, _) => { actualSource = context.SourceInstanceId; actualReplay = context.IsReplaying; actualInput = context.GetInput(); + actualDateTime = context.Properties["dateTime"]; + actualDateTimeOffset = context.Properties["dateTimeOffset"]; return Task.FromResult(context.SourceInstanceId); }); @@ -555,10 +566,11 @@ public void SourceInstanceId_FlowsThroughPropertiesOnExecutionAndReplay(string? actualSource.Should().Be(source); actualReplay.Should().Be(replay); actualInput.Should().Be("original-input"); + actualDateTime.Should().BeOfType().Which.Should().Be(new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)); + actualDateTimeOffset.Should().BeOfType().Which.Should().Be(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)); response.Actions.Should().ContainSingle(); response.Actions[0].CompleteOrchestration.OrchestrationStatus.Should().Be(Protobuf.OrchestrationStatus.Completed); - response.Actions[0].CompleteOrchestration.Result.Should().Be( - source is null ? null : $"\"{source}\""); + JsonDataConverter.Default.Deserialize(response.Actions[0].CompleteOrchestration.Result).Should().Be(source); } static Protobuf.OrchestratorRequest CreateOrchestratorRequest(IEnumerable newEvents)