Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion src/DurableTask.SqlServer/Scripts/logic.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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
)

Expand Down Expand Up @@ -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
Comment thread
andystaples marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Reject stale child checkpoints after reusing an instance ID

Purging the completed child's history removes the duplicate-checkpoint protection for its previous execution. If a delayed checkpoint from that execution arrives after the child has been recreated, _CheckpointOrchestration treats the execution ID mismatch as ContinueAsNew. It deletes the new execution's history and writes the old execution ID and status back to Instances, while the new ExecutionStarted event remains queued. The new child can be stranded, and any history it has already written can be lost.

Please prevent checkpoints for a previous execution from modifying the replacement while preserving legitimate ContinueAsNew behavior, and add a regression that checkpoints the old child after its ID is reused.

END

-- Custom status case #1: Setting the custom status for the first time
IF @ExistingCustomStatusPayload IS NULL AND @CustomStatusPayload IS NOT NULL
BEGIN
Expand Down
76 changes: 76 additions & 0 deletions test/DurableTask.SqlServer.Tests/Integration/FaultTesting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>(
subOrchestrationName,
implementation: (ctx, input) =>
{
Interlocked.Increment(ref subInvocations);
return Task.FromResult($"Hello, {input}!");
});

this.testService.OrchestrationServiceMock.Setup(
svc => svc.CompleteTaskOrchestrationWorkItemAsync(
It.IsAny<TaskOrchestrationWorkItem>(),
It.IsAny<OrchestrationRuntimeState>(),
It.IsAny<IList<TaskMessage>>(),
It.IsAny<IList<TaskMessage>>(),
It.IsAny<IList<TaskMessage>>(),
It.IsAny<TaskMessage>(),
It.IsAny<OrchestrationState>()))
.Callback<TaskOrchestrationWorkItem, OrchestrationRuntimeState, IList<TaskMessage>, IList<TaskMessage>, IList<TaskMessage>, 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<string> parentInstance = await this.testService.RunOrchestration<string[], string>(
null,
"ReuseSubOrchestrationParent",
implementation: async (ctx, input) =>
{
string first = await ctx.CreateSubOrchestrationInstance<string>(
subOrchestrationName, string.Empty, subInstanceId, "first");
string second = await ctx.CreateSubOrchestrationInstance<string>(
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);
}
}
}
175 changes: 174 additions & 1 deletion test/DurableTask.SqlServer.Tests/Integration/Orchestrations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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<string, string>(
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<string> parentInstance = await this.testService.RunOrchestration<string[], string>(
null,
"RecreateSubOrchestrationParent",
implementation: async (ctx, input) =>
{
string first = await ctx.CreateSubOrchestrationInstance<string>(
subOrchestrationName, string.Empty, subInstanceId, "first");
string second = await ctx.CreateSubOrchestrationInstance<string>(
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<string> 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<string> parentInstance = await this.testService.RunOrchestration<string, string>(
null,
"RunningSubOrchestrationParent",
implementation: (ctx, input) => ctx.CreateSubOrchestrationInstance<string>(
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<string> 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<string> parentInstance = await this.testService.RunOrchestration<string, string>(
"parent",
"ConcurrentReuseParent",
version: null,
parentInstanceId,
implementation: (ctx, input) => ctx.CreateSubOrchestrationInstance<string>(
subOrchestrationName, string.Empty, subInstanceId, input));
await WaitUntilPausedAsync(checkpointStarted);

// Meanwhile a client must not overwrite the checkpoint's new instance.
Task<OrchestrationInstance> createTask = this.testService.CreateOrchestrationInstanceAsync(
subOrchestrationName, string.Empty, subInstanceId, "client");
await Task.Delay(CheckpointPauseDelay);

await blockerTransaction.RollbackAsync();

// The checkpoint wins.
await Assert.ThrowsAsync<OrchestrationAlreadyExistsException>(() => 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);

/// <summary>Completes when the instance starts checkpointing.</summary>
Task WatchCheckpoint(string instanceId)
{
TaskCompletionSource<bool> started = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);

this.testService.OrchestrationServiceMock.Setup(
svc => svc.CompleteTaskOrchestrationWorkItemAsync(
It.IsAny<TaskOrchestrationWorkItem>(),
It.IsAny<OrchestrationRuntimeState>(),
It.IsAny<IList<TaskMessage>>(),
It.IsAny<IList<TaskMessage>>(),
It.IsAny<IList<TaskMessage>>(),
It.IsAny<TaskMessage>(),
It.IsAny<OrchestrationState>()))
.Callback<TaskOrchestrationWorkItem, OrchestrationRuntimeState, IList<TaskMessage>, IList<TaskMessage>, IList<TaskMessage>, 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);
}

/// <summary>Holds an uncommitted event for the instance, so purging it waits for the transaction.</summary>
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
Expand Down
5 changes: 5 additions & 0 deletions test/DurableTask.SqlServer.Tests/Utils/TestService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ public Task<OrchestrationState> GetOrchestrationStateAsync(string instanceId)
return this.client.GetOrchestrationStateAsync(new OrchestrationInstance { InstanceId = instanceId });
}

public Task<OrchestrationInstance> 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;
Expand Down