From a416b83089ea0ae9e55ae22c90d6705e9945920e Mon Sep 17 00:00:00 2001 From: Usein Mambediiev Date: Sat, 12 Sep 2026 16:56:21 -0700 Subject: [PATCH 1/3] fix issue 148 - sub-orchestrations cannot reuse existing instance ids --- src/DurableTask.SqlServer/Scripts/logic.sql | 18 +++++ .../Integration/Orchestrations.cs | 72 ++++++++++++++++++- 2 files changed, 89 insertions(+), 1 deletion(-) diff --git a/src/DurableTask.SqlServer/Scripts/logic.sql b/src/DurableTask.SqlServer/Scripts/logic.sql index 51f8bbf..74bab51 100644 --- a/src/DurableTask.SqlServer/Scripts/logic.sql +++ b/src/DurableTask.SqlServer/Scripts/logic.sql @@ -817,6 +817,24 @@ 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. + DECLARE @SubOrchestrationsToRecreate InstanceIDs + INSERT INTO @SubOrchestrationsToRecreate ([InstanceID]) + SELECT DISTINCT E.[InstanceID] + FROM @NewOrchestrationEvents E + INNER JOIN Instances I ON I.[TaskHub] = @TaskHub AND I.[InstanceID] = E.[InstanceID] + WHERE E.[EventType] = 'ExecutionStarted' + AND E.[InstanceID] <> @InstanceID -- never touch the instance being checkpointed + AND I.[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/Orchestrations.cs b/test/DurableTask.SqlServer.Tests/Integration/Orchestrations.cs index 27a0ef6..a264271 100644 --- a/test/DurableTask.SqlServer.Tests/Integration/Orchestrations.cs +++ b/test/DurableTask.SqlServer.Tests/Integration/Orchestrations.cs @@ -654,7 +654,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) { @@ -690,6 +690,76 @@ 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); + } + // 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 From 254f14367f3bf882d64e372f24887d6aa79e6946 Mon Sep 17 00:00:00 2001 From: Usein Mambediiev Date: Sun, 18 Oct 2026 20:52:25 -0700 Subject: [PATCH 2/3] rollback whole checkpoint on error --- src/DurableTask.SqlServer/Scripts/logic.sql | 3 + .../Integration/FaultTesting.cs | 82 +++++++++++++++++++ .../Utils/SharedTestHelpers.cs | 13 +++ 3 files changed, 98 insertions(+) diff --git a/src/DurableTask.SqlServer/Scripts/logic.sql b/src/DurableTask.SqlServer/Scripts/logic.sql index 6743815..a9e90a4 100644 --- a/src/DurableTask.SqlServer/Scripts/logic.sql +++ b/src/DurableTask.SqlServer/Scripts/logic.sql @@ -771,6 +771,9 @@ CREATE OR ALTER PROCEDURE __SchemaNamePlaceholder__._CheckpointOrchestration @NewLockExpiration datetime2 = NULL AS BEGIN + -- Roll back the whole checkpoint on any error (e.g. duplicate-execution PK violation). + SET XACT_ABORT ON + BEGIN TRANSACTION DECLARE @TaskHub varchar(50) = __SchemaNamePlaceholder__.CurrentTaskHub() diff --git a/test/DurableTask.SqlServer.Tests/Integration/FaultTesting.cs b/test/DurableTask.SqlServer.Tests/Integration/FaultTesting.cs index 7a4bf96..2a755b6 100644 --- a/test/DurableTask.SqlServer.Tests/Integration/FaultTesting.cs +++ b/test/DurableTask.SqlServer.Tests/Integration/FaultTesting.cs @@ -5,9 +5,13 @@ namespace DurableTask.SqlServer.Tests.Integration { using System; using System.Collections.Generic; + using System.Diagnostics; + using System.Linq; using System.Threading; using System.Threading.Tasks; using DurableTask.Core; + using DurableTask.Core.History; + using DurableTask.SqlServer.Logging; using DurableTask.SqlServer.Tests.Logging; using DurableTask.SqlServer.Tests.Utils; using Moq; @@ -18,10 +22,12 @@ namespace DurableTask.SqlServer.Tests.Integration public class FaultTesting : IAsyncLifetime { readonly TestService testService; + readonly ITestOutputHelper output; public FaultTesting(ITestOutputHelper output) { this.testService = new TestService(output); + this.output = output; } Task IAsyncLifetime.InitializeAsync() => this.testService.InitializeAsync(); @@ -288,5 +294,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/Utils/SharedTestHelpers.cs b/test/DurableTask.SqlServer.Tests/Utils/SharedTestHelpers.cs index 16d4f29..486678e 100644 --- a/test/DurableTask.SqlServer.Tests/Utils/SharedTestHelpers.cs +++ b/test/DurableTask.SqlServer.Tests/Utils/SharedTestHelpers.cs @@ -96,6 +96,19 @@ public static async Task ExecuteSqlAsync(ITestOutputHelper output, strin throw lastException; } + /// + /// Occupies the instance's next history sequence number so its next checkpoint hits a PK violation. + /// + public static Task OccupyNextHistorySlotAsync(ITestOutputHelper output, string instanceId) + { + return ExecuteSqlAsync( + output, + $@"INSERT INTO dt.[History] ([TaskHub], [InstanceID], [ExecutionID], [SequenceNumber], [EventType]) + SELECT TOP 1 [TaskHub], [InstanceID], [ExecutionID], [SequenceNumber] + 1, 'GenericEvent' + FROM dt.[History] WHERE [InstanceID] = '{instanceId}' + ORDER BY [SequenceNumber] DESC"); + } + public static async Task InitializeDatabaseAsync(string schema = DefaultSchema) { var options = new SqlOrchestrationServiceSettings(GetDefaultConnectionString(), schemaName: schema); From 705d14f4f4c67a2751586abc21e111c8a055d1ab Mon Sep 17 00:00:00 2001 From: Usein Mambediiev Date: Tue, 20 Oct 2026 21:41:22 -0700 Subject: [PATCH 3/3] fix - keep the terminal-state check stable through purge and recreation --- src/DurableTask.SqlServer/Scripts/logic.sql | 26 +++-- .../Integration/Orchestrations.cs | 103 ++++++++++++++++++ .../Utils/TestService.cs | 5 + 3 files changed, 127 insertions(+), 7 deletions(-) diff --git a/src/DurableTask.SqlServer/Scripts/logic.sql b/src/DurableTask.SqlServer/Scripts/logic.sql index a9e90a4..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 ) @@ -827,14 +829,24 @@ BEGIN -- 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 DISTINCT E.[InstanceID] - FROM @NewOrchestrationEvents E - INNER JOIN Instances I ON I.[TaskHub] = @TaskHub AND I.[InstanceID] = E.[InstanceID] - WHERE E.[EventType] = 'ExecutionStarted' - AND E.[InstanceID] <> @InstanceID -- never touch the instance being checkpointed - AND I.[RuntimeStatus] IN ('Completed', 'Failed', 'Terminated') + SELECT [InstanceID] + FROM @StartedSubOrchestrations + WHERE [RuntimeStatus] IN ('Completed', 'Failed', 'Terminated') IF EXISTS (SELECT 1 FROM @SubOrchestrationsToRecreate) BEGIN diff --git a/test/DurableTask.SqlServer.Tests/Integration/Orchestrations.cs b/test/DurableTask.SqlServer.Tests/Integration/Orchestrations.cs index a264271..9f85b29 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; @@ -760,6 +761,108 @@ public async Task CannotReuseRunningSubOrchestrationInstanceID() 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 5d21ea3..85ce21b 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;