diff --git a/src/DurableTask.SqlServer/Scripts/logic.sql b/src/DurableTask.SqlServer/Scripts/logic.sql index 9502206..ec83c63 100644 --- a/src/DurableTask.SqlServer/Scripts/logic.sql +++ b/src/DurableTask.SqlServer/Scripts/logic.sql @@ -253,9 +253,11 @@ BEGIN BEGIN BEGIN TRANSACTION + -- UPDLOCK waits for a checkpoint that is recreating this ID as a sub-orchestration. + -- No HOLDLOCK: its key-range locks would block unrelated instances with adjacent IDs. DECLARE @existingStatus varchar(30) = ( SELECT TOP 1 existing.[RuntimeStatus] - FROM Instances existing WITH (HOLDLOCK) + FROM Instances existing WITH (UPDLOCK) WHERE [TaskHub] = @TaskHub AND [InstanceID] = @InstanceID ) @@ -823,6 +825,34 @@ BEGIN SET @IsContinueAsNew = 1 END + -- Sub-orchestration instance ID reuse case: https://github.com/microsoft/durabletask-mssql/issues/148 + -- Purge the existing instance data so that the "Create sub-orchestration instances" statement further below can overwrite it. + -- NOTE: This must happen before any new payloads or events are written below, otherwise the + -- incoming sub-orchestration state would be purged along with the existing state. + -- UPDLOCK keeps the rows locked until commit, so a concurrent checkpoint or CreateInstance can't recreate + -- an instance between this status check and the purge. Status is filtered separately to lock non-terminal rows too. + DECLARE @StartedSubOrchestrations TABLE ([InstanceID] varchar(100) NOT NULL, [RuntimeStatus] varchar(30) NULL) + INSERT INTO @StartedSubOrchestrations ([InstanceID], [RuntimeStatus]) + SELECT I.[InstanceID], I.[RuntimeStatus] + FROM Instances I WITH (UPDLOCK) + WHERE I.[TaskHub] = @TaskHub + AND I.[InstanceID] IN ( + SELECT E.[InstanceID] + FROM @NewOrchestrationEvents E + WHERE E.[EventType] = 'ExecutionStarted' + AND E.[InstanceID] <> @InstanceID) -- never touch the instance being checkpointed + + DECLARE @SubOrchestrationsToRecreate InstanceIDs + INSERT INTO @SubOrchestrationsToRecreate ([InstanceID]) + SELECT [InstanceID] + FROM @StartedSubOrchestrations + WHERE [RuntimeStatus] IN ('Completed', 'Failed', 'Terminated') + + IF EXISTS (SELECT 1 FROM @SubOrchestrationsToRecreate) + BEGIN + EXEC __SchemaNamePlaceholder__.PurgeInstanceStateByID @SubOrchestrationsToRecreate + END + -- Custom status case #1: Setting the custom status for the first time IF @ExistingCustomStatusPayload IS NULL AND @CustomStatusPayload IS NOT NULL BEGIN diff --git a/test/DurableTask.SqlServer.Tests/Integration/FaultTesting.cs b/test/DurableTask.SqlServer.Tests/Integration/FaultTesting.cs index 54b5412..493b390 100644 --- a/test/DurableTask.SqlServer.Tests/Integration/FaultTesting.cs +++ b/test/DurableTask.SqlServer.Tests/Integration/FaultTesting.cs @@ -362,5 +362,81 @@ public async Task ActivityHang() LogAssert.CheckpointCompleted(orchestrationName), LogAssert.DuplicateExecutionDetected("SayHello")); } + + [Fact] + public async Task DuplicateCheckpointDoesNotPurgeCompletedSubOrchestration() + { + // The rolled-back checkpoint keeps the lock, so the retry waits for it to expire. + this.testService.OrchestrationServiceOptions.WorkItemLockTimeout = TimeSpan.FromSeconds(5); + + string subOrchestrationName = "CountedSubOrchestration"; + string subInstanceId = $"sub-{Guid.NewGuid():N}"; + int subInvocations = 0; + bool injected = false; + + this.testService.RegisterInlineOrchestration( + subOrchestrationName, + implementation: (ctx, input) => + { + Interlocked.Increment(ref subInvocations); + return Task.FromResult($"Hello, {input}!"); + }); + + this.testService.OrchestrationServiceMock.Setup( + svc => svc.CompleteTaskOrchestrationWorkItemAsync( + It.IsAny(), + It.IsAny(), + It.IsAny>(), + It.IsAny>(), + It.IsAny>(), + It.IsAny(), + It.IsAny())) + .Callback, IList, IList, TaskMessage, OrchestrationState>( + (workItem, _, _, _, _, _, _) => + { + if (!injected && workItem.NewMessages.Any(m => m.Event.EventType == EventType.SubOrchestrationInstanceCompleted)) + { + // Inject the conflict into the parent turn that reuses the completed sub-orchestration's ID. + injected = true; + SharedTestHelpers.OccupyNextHistorySlotAsync(this.output, workItem.InstanceId).GetAwaiter().GetResult(); + } + }); + + TestInstance parentInstance = await this.testService.RunOrchestration( + null, + "ReuseSubOrchestrationParent", + implementation: async (ctx, input) => + { + string first = await ctx.CreateSubOrchestrationInstance( + subOrchestrationName, string.Empty, subInstanceId, "first"); + string second = await ctx.CreateSubOrchestrationInstance( + subOrchestrationName, string.Empty, subInstanceId, "second"); + return new[] { first, second }; + }); + + Stopwatch sw = Stopwatch.StartNew(); + while (!HasDuplicateExecutionLog() && sw.Elapsed < TimeSpan.FromSeconds(30)) + { + await Task.Delay(TimeSpan.FromMilliseconds(200)); + } + + Assert.True(HasDuplicateExecutionLog(), "The injected history conflict was never hit."); + + // The rejected checkpoint must not have purged and restarted the completed sub-orchestration. + OrchestrationState subState = await this.testService.GetOrchestrationStateAsync(subInstanceId); + Assert.NotNull(subState); + Assert.Equal(OrchestrationStatus.Completed, subState.OrchestrationStatus); + Assert.Equal("\"Hello, first!\"", subState.Output); + + // The retried checkpoint reuses the ID as usual. + await parentInstance.WaitForCompletion( + timeout: TimeSpan.FromSeconds(30), + expectedOutput: new[] { "Hello, first!", "Hello, second!" }); + Assert.Equal(2, subInvocations); + + bool HasDuplicateExecutionLog() => + this.testService.LogProvider.TryGetLogs("DurableTask.SqlServer", out var logs) && + logs.Any(entry => entry.EventId.Id == EventIds.DuplicateExecutionDetected); + } } } diff --git a/test/DurableTask.SqlServer.Tests/Integration/Orchestrations.cs b/test/DurableTask.SqlServer.Tests/Integration/Orchestrations.cs index e3aa84d..f69d3c0 100644 --- a/test/DurableTask.SqlServer.Tests/Integration/Orchestrations.cs +++ b/test/DurableTask.SqlServer.Tests/Integration/Orchestrations.cs @@ -15,6 +15,7 @@ namespace DurableTask.SqlServer.Tests.Integration using DurableTask.Core.Middleware; using DurableTask.SqlServer.Tests.Logging; using DurableTask.SqlServer.Tests.Utils; + using Microsoft.Data.SqlClient; using Moq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -766,7 +767,7 @@ public async Task RecreateRunningInstance() } [Theory] - //[InlineData(true)] // BUG: https://github.com/microsoft/durabletask-mssql/issues/148 + [InlineData(true)] [InlineData(false)] public async Task RetryFailedSubOrchestration(bool userSpecifiedInstanceId) { @@ -802,6 +803,178 @@ public async Task RetryFailedSubOrchestration(bool userSpecifiedInstanceId) await parentInstance.WaitForCompletion(expectedOutput: true); } + [Fact] + public async Task ReuseCompletedSubOrchestrationInstanceID() + { + string subOrchestrationName = "RecreatableSubOrchestration"; + string subInstanceId = $"sub-{Guid.NewGuid():N}"; + + this.testService.RegisterInlineOrchestration( + subOrchestrationName, + implementation: (ctx, input) => Task.FromResult($"Hello, {input}!")); + + // The second run is only possible if the terminal state of the first run gets overwritten. + TestInstance parentInstance = await this.testService.RunOrchestration( + null, + "RecreateSubOrchestrationParent", + implementation: async (ctx, input) => + { + string first = await ctx.CreateSubOrchestrationInstance( + subOrchestrationName, string.Empty, subInstanceId, "first"); + string second = await ctx.CreateSubOrchestrationInstance( + subOrchestrationName, string.Empty, subInstanceId, "second"); + return new[] { first, second }; + }); + + await parentInstance.WaitForCompletion( + timeout: TimeSpan.FromSeconds(30), + expectedOutput: new[] { "Hello, first!", "Hello, second!" }); + + // Only the second run should remain. + OrchestrationState subState = await this.testService.GetOrchestrationStateAsync(subInstanceId); + Assert.NotNull(subState); + Assert.Equal(OrchestrationStatus.Completed, subState.OrchestrationStatus); + Assert.Equal("\"Hello, second!\"", subState.Output); + } + + [Fact] + public async Task CannotReuseRunningSubOrchestrationInstanceID() + { + string subOrchestrationName = "BlockedSubOrchestration"; + string subInstanceId = $"sub-{Guid.NewGuid():N}"; + TimeSpan delay = TimeSpan.FromSeconds(30); + + // Block on a long timer so that the instance stays active. + TestInstance blockedInstance = await this.testService.RunOrchestration( + "blocked", + subOrchestrationName, + version: null, + subInstanceId, + implementation: (ctx, input) => ctx.CreateTimer(ctx.CurrentUtcDateTime.Add(delay), input)); + OrchestrationState startedState = await blockedInstance.WaitForStart(); + + // Starting a sub-orchestration with the ID of an active instance must not overwrite it. + TestInstance parentInstance = await this.testService.RunOrchestration( + null, + "RunningSubOrchestrationParent", + implementation: (ctx, input) => ctx.CreateSubOrchestrationInstance( + subOrchestrationName, string.Empty, subInstanceId, "overwrite")); + + await parentInstance.WaitForStart(); + + // Give the sub-orchestration start event time to be processed. + await Task.Delay(TimeSpan.FromSeconds(5)); + + // CreatedTime is only assigned when a row is created, so an unchanged value proves the + // instance wasn't recreated. What happens to the duplicate start event is out of scope. + OrchestrationState subState = await this.testService.GetOrchestrationStateAsync(subInstanceId); + Assert.NotNull(subState); + Assert.Equal(startedState.CreatedTime, subState.CreatedTime); + Assert.Equal(startedState.OrchestrationInstance.ExecutionId, subState.OrchestrationInstance.ExecutionId); + } + + [Fact] + public async Task ConcurrentReuseOfCompletedSubOrchestrationInstanceID() + { + string subOrchestrationName = "ConcurrentlyReusedSubOrchestration"; + string subInstanceId = $"sub-{Guid.NewGuid():N}"; + string parentInstanceId = Guid.NewGuid().ToString("N"); + Task checkpointStarted = this.WatchCheckpoint(parentInstanceId); + + TestInstance completedInstance = await this.testService.RunOrchestration( + "first", + subOrchestrationName, + version: null, + subInstanceId, + implementation: (ctx, input) => Task.FromResult($"Hello, {input}!")); + await completedInstance.WaitForCompletion(expectedOutput: "Hello, first!"); + + (SqlConnection blocker, SqlTransaction blockerTransaction) = await HoldUncommittedEventAsync(subInstanceId); + await using (blocker) + { + // The parent's checkpoint pauses while replacing the completed sub-orchestration. + TestInstance parentInstance = await this.testService.RunOrchestration( + "parent", + "ConcurrentReuseParent", + version: null, + parentInstanceId, + implementation: (ctx, input) => ctx.CreateSubOrchestrationInstance( + subOrchestrationName, string.Empty, subInstanceId, input)); + await WaitUntilPausedAsync(checkpointStarted); + + // Meanwhile a client must not overwrite the checkpoint's new instance. + Task createTask = this.testService.CreateOrchestrationInstanceAsync( + subOrchestrationName, string.Empty, subInstanceId, "client"); + await Task.Delay(CheckpointPauseDelay); + + await blockerTransaction.RollbackAsync(); + + // The checkpoint wins. + await Assert.ThrowsAsync(() => createTask); + + await parentInstance.WaitForCompletion( + timeout: TimeSpan.FromSeconds(30), + expectedOutput: "Hello, parent!"); + } + + OrchestrationState subState = await this.testService.GetOrchestrationStateAsync(subInstanceId); + Assert.NotNull(subState); + Assert.Equal(OrchestrationStatus.Completed, subState.OrchestrationStatus); + Assert.Equal("\"Hello, parent!\"", subState.Output); + } + + // Time for a started checkpoint to reach the held event. + static readonly TimeSpan CheckpointPauseDelay = TimeSpan.FromSeconds(1); + + /// Completes when the instance starts checkpointing. + Task WatchCheckpoint(string instanceId) + { + TaskCompletionSource started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + this.testService.OrchestrationServiceMock.Setup( + svc => svc.CompleteTaskOrchestrationWorkItemAsync( + It.IsAny(), + It.IsAny(), + It.IsAny>(), + It.IsAny>(), + It.IsAny>(), + It.IsAny(), + It.IsAny())) + .Callback, IList, IList, TaskMessage, OrchestrationState>( + (workItem, _, _, _, _, _, _) => + { + if (workItem.InstanceId == instanceId) + { + started.TrySetResult(true); + } + }); + + return started.Task; + } + + static async Task WaitUntilPausedAsync(Task checkpointStarted) + { + await checkpointStarted.WaitAsync(TimeSpan.FromSeconds(30)); + await Task.Delay(CheckpointPauseDelay); + } + + /// Holds an uncommitted event for the instance, so purging it waits for the transaction. + static async Task<(SqlConnection, SqlTransaction)> HoldUncommittedEventAsync(string instanceId) + { + SqlConnection connection = new SqlConnection(SharedTestHelpers.GetDefaultConnectionString()); + await connection.OpenAsync(); + SqlTransaction transaction = (SqlTransaction)await connection.BeginTransactionAsync(); + + await using SqlCommand command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = + @"INSERT INTO dt.[NewEvents] ([TaskHub], [InstanceID], [EventType]) + SELECT [TaskHub], [InstanceID], 'GenericEvent' FROM dt.[Instances] WHERE [InstanceID] = @InstanceID"; + command.Parameters.AddWithValue("@InstanceID", instanceId); + await command.ExecuteNonQueryAsync(); + return (connection, transaction); + } + // This regression locks down the expected DurableTask span shape for a simple // parent orchestration -> sub-orchestration -> activity flow. The important // nuance is that an activity under a sub-orchestration is nested via an diff --git a/test/DurableTask.SqlServer.Tests/Utils/TestService.cs b/test/DurableTask.SqlServer.Tests/Utils/TestService.cs index a212fa9..a0357db 100644 --- a/test/DurableTask.SqlServer.Tests/Utils/TestService.cs +++ b/test/DurableTask.SqlServer.Tests/Utils/TestService.cs @@ -108,6 +108,11 @@ public Task GetOrchestrationStateAsync(string instanceId) return this.client.GetOrchestrationStateAsync(new OrchestrationInstance { InstanceId = instanceId }); } + public Task CreateOrchestrationInstanceAsync(string name, string version, string instanceId, object input) + { + return this.client.CreateOrchestrationInstanceAsync(name, version, instanceId, input); + } + public Task StartWorkerAsync() => this.worker?.StartAsync() ?? Task.CompletedTask; public Task StopWorkerAsync(bool isForced = false) => this.worker?.StopAsync(isForced) ?? Task.CompletedTask;