From b1a3bef01738025af86f22874173160928a640b1 Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Wed, 9 Sep 2026 13:32:21 -0700 Subject: [PATCH 1/9] implemented the fix to retain external events --- .../AzureStorageOrchestrationService.cs | 35 ++-- .../AzureStorageScenarioTests.cs | 165 ++++++++++++++++++ 2 files changed, 186 insertions(+), 14 deletions(-) diff --git a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs index 74798cb45..5e8f7a7d3 100644 --- a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs +++ b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs @@ -830,7 +830,11 @@ async Task LockNextTaskOrchestrationWorkItemAsync(boo // If no messages have a matching execution ID, then delete all of them. This means all the // messages are external (external events, termination, etc.) and were sent to an instance that // doesn't exist or is no longer in a running state. - if (messagesToDiscard.Count == 0) + // This is only safe to do if the session's execution ID is itself null, otherwise the history + // could be missing due to trying to fetch a particular execution ID that no longer exists for + // example due to a continue-as-new. In that case we do not want to delete the external messages + // but rather retry them on the current execution + if (messagesToDiscard.Count == 0 && session.Instance.ExecutionId == null) { messagesToDiscard.AddRange(messagesToAbandon); messagesToAbandon.Clear(); @@ -841,21 +845,24 @@ async Task LockNextTaskOrchestrationWorkItemAsync(boo // the next time they are picked up. messagesToAbandon.ForEach(session.DeferMessage); - var eventListBuilder = new StringBuilder(orchestrationWorkItem.NewMessages.Count * 40); - foreach (MessageData msg in messagesToDiscard) + if (messagesToDiscard.Count > 0) { - eventListBuilder.Append(msg.TaskMessage.Event.EventType.ToString()).Append(','); - } + var eventListBuilder = new StringBuilder(orchestrationWorkItem.NewMessages.Count * 40); + foreach (MessageData msg in messagesToDiscard) + { + eventListBuilder.Append(msg.TaskMessage.Event.EventType.ToString()).Append(','); + } - this.settings.Logger.DiscardingWorkItem( - this.azureStorageClient.QueueAccountName, - this.settings.TaskHubName, - session.Instance.InstanceId, - session.Instance.ExecutionId, - orchestrationWorkItem.NewMessages.Count, - session.RuntimeState.Events.Count, - eventListBuilder.ToString(0, eventListBuilder.Length - 1) /* remove trailing comma */, - warningMessage); + this.settings.Logger.DiscardingWorkItem( + this.azureStorageClient.QueueAccountName, + this.settings.TaskHubName, + session.Instance.InstanceId, + session.Instance.ExecutionId, + orchestrationWorkItem.NewMessages.Count, + session.RuntimeState.Events.Count, + eventListBuilder.ToString(0, eventListBuilder.Length - 1) /* remove trailing comma */, + warningMessage); + } // The instance has already completed or never existed. Delete this message batch. await this.DeleteMessageBatchAsync(session, messagesToDiscard); diff --git a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs index a23720346..7fbe14417 100644 --- a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs +++ b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs @@ -3950,6 +3950,171 @@ await service.SendTaskOrchestrationMessageAsync( } } + [TestMethod] + public async Task WorkerDoesNotDiscardExternalEventBatchedWithMessageForMissingExecution() + { + AzureStorageOrchestrationService service = null; + AzureStorageOrchestrationService retryService = null; + bool serviceStarted = false; + bool retryServiceStarted = false; + + string instanceId = Guid.NewGuid().ToString(); + string currentExecutionId = Guid.NewGuid().ToString(); + string futureExecutionId = Guid.NewGuid().ToString(); + DateTime fireAt = DateTime.UtcNow; + + var settings = new AzureStorageOrchestrationServiceSettings + { + PartitionCount = 1, + StorageAccountClientProvider = new StorageAccountClientProvider(TestHelpers.GetTestStorageAccountConnectionString()), + TaskHubName = "MixedBatch" + Guid.NewGuid().ToString("N").Substring(0, 12), + ExtendedSessionsEnabled = false, + ControlQueueVisibilityTimeout = TimeSpan.FromSeconds(5), + UseAppLease = false, + }; + + try + { + service = new AzureStorageOrchestrationService(settings); + await service.CreateAsync(); + + OrchestrationHistory emptyHistory = await service.TrackingStore.GetHistoryEventsAsync( + instanceId, + currentExecutionId); + var currentRuntimeState = new OrchestrationRuntimeState(); + currentRuntimeState.AddEvent(new OrchestratorStartedEvent(-1)); + currentRuntimeState.AddEvent(new ExecutionStartedEvent(-1, string.Empty) + { + Name = "orchestration", + Version = string.Empty, + OrchestrationInstance = new OrchestrationInstance + { + InstanceId = instanceId, + ExecutionId = currentExecutionId, + }, + }); + currentRuntimeState.AddEvent(new OrchestratorCompletedEvent(-1)); + + await service.TrackingStore.UpdateStateAsync( + currentRuntimeState, + new OrchestrationRuntimeState(), + instanceId, + currentExecutionId, + new OrchestrationETags { HistoryETag = emptyHistory.ETag }, + emptyHistory.TrackingStoreContext); + + var controlQueue = service.AllControlQueues.Single(); + var sourceInstance = new OrchestrationInstance + { + InstanceId = "source", + ExecutionId = "source-execution", + }; + + await controlQueue.AddMessageAsync( + new TaskMessage + { + OrchestrationInstance = new OrchestrationInstance + { + InstanceId = instanceId, + ExecutionId = futureExecutionId, + }, + Event = new TimerFiredEvent(-1, fireAt) { TimerId = 0 }, + }, + sourceInstance); + await controlQueue.AddMessageAsync( + new TaskMessage + { + OrchestrationInstance = new OrchestrationInstance { InstanceId = instanceId }, + Event = new EventRaisedEvent(-1, string.Empty) { Name = "event" }, + }, + sourceInstance); + + await service.StartAsync(); + serviceStarted = true; + + using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30))) + { + TaskOrchestrationWorkItem workItem = await service.LockNextTaskOrchestrationWorkItemAsync( + TimeSpan.FromSeconds(30), + timeout.Token); + Assert.IsNull(workItem); + } + + Assert.AreEqual( + 2, + await controlQueue.InnerQueue.GetApproximateMessagesCountAsync(), + "The out-of-order timer and execution-independent event should both remain on the queue."); + + await service.StopAsync(isForced: true); + serviceStarted = false; + + OrchestrationHistory currentHistory = await service.TrackingStore.GetHistoryEventsAsync( + instanceId, + currentExecutionId); + var futureRuntimeState = new OrchestrationRuntimeState(); + futureRuntimeState.AddEvent(new OrchestratorStartedEvent(-1)); + futureRuntimeState.AddEvent(new ExecutionStartedEvent(-1, string.Empty) + { + Name = "orchestration", + Version = string.Empty, + OrchestrationInstance = new OrchestrationInstance + { + InstanceId = instanceId, + ExecutionId = futureExecutionId, + }, + }); + futureRuntimeState.AddEvent(new TimerCreatedEvent(0, fireAt)); + futureRuntimeState.AddEvent(new OrchestratorCompletedEvent(-1)); + + await service.TrackingStore.UpdateStateAsync( + futureRuntimeState, + new OrchestrationRuntimeState(currentHistory.Events), + instanceId, + futureExecutionId, + new OrchestrationETags { HistoryETag = currentHistory.ETag }, + currentHistory.TrackingStoreContext); + + await Task.Delay(settings.ControlQueueVisibilityTimeout + TimeSpan.FromSeconds(1)); + + retryService = new AzureStorageOrchestrationService(settings); + await retryService.StartAsync(); + retryServiceStarted = true; + + using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30))) + { + TaskOrchestrationWorkItem workItem = await retryService.LockNextTaskOrchestrationWorkItemAsync( + TimeSpan.FromSeconds(30), + timeout.Token); + + Assert.IsNotNull(workItem); + Assert.AreEqual(futureExecutionId, workItem.OrchestrationRuntimeState.OrchestrationInstance.ExecutionId); + Assert.AreEqual(2, workItem.NewMessages.Count); + Assert.IsTrue(workItem.NewMessages.Any(message => message.Event is TimerFiredEvent)); + Assert.IsTrue(workItem.NewMessages.Any(message => message.Event is EventRaisedEvent)); + } + } + finally + { + if (retryServiceStarted) + { + await retryService.StopAsync(isForced: true); + } + + if (serviceStarted) + { + await service.StopAsync(isForced: true); + } + + if (service != null) + { + await service.DeleteAsync(); + } + + retryService?.Dispose(); + service?.Dispose(); + } + } + [DataTestMethod] [DataRow(true, true)] [DataRow(false, true)] From 8f5ae7d11576c3a047a217d708dc460d9a9f5a81 Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Thu, 10 Sep 2026 11:43:07 -0700 Subject: [PATCH 2/9] added comments to the test --- .../AzureStorageScenarioTests.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs index 7fbe14417..110e76cc3 100644 --- a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs +++ b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs @@ -3978,6 +3978,7 @@ public async Task WorkerDoesNotDiscardExternalEventBatchedWithMessageForMissingE service = new AzureStorageOrchestrationService(settings); await service.CreateAsync(); + // First manually generate a history for a particular "old" execution ID OrchestrationHistory emptyHistory = await service.TrackingStore.GetHistoryEventsAsync( instanceId, currentExecutionId); @@ -4010,6 +4011,8 @@ await service.TrackingStore.UpdateStateAsync( ExecutionId = "source-execution", }; + // Next, enqueue two messages - one is a TimerFired targeting a "future" execution that has + // not been committed yet, and another is a generic EventRaisedEvent that is execution-independent await controlQueue.AddMessageAsync( new TaskMessage { @@ -4032,6 +4035,11 @@ await controlQueue.AddMessageAsync( await service.StartAsync(); serviceStarted = true; + // Now confirm that both messages remain on the queue, even though no history was fetched for the + // "future" execution ID attached to the TimerFired that has not yet been committed to the history table. + // Critically, we want to abandon both the TimerFired *and* the EventRaisedEvent even though the latter has + // targets no specific execution ID. + // No work item is generated since no history was fetched, but both messages will be retried again after the visibility timeout expires. using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30))) { TaskOrchestrationWorkItem workItem = await service.LockNextTaskOrchestrationWorkItemAsync( @@ -4048,6 +4056,7 @@ await controlQueue.InnerQueue.GetApproximateMessagesCountAsync(), await service.StopAsync(isForced: true); serviceStarted = false; + // Now manually update the history to have the "future" execution ID OrchestrationHistory currentHistory = await service.TrackingStore.GetHistoryEventsAsync( instanceId, currentExecutionId); @@ -4080,6 +4089,8 @@ await service.TrackingStore.UpdateStateAsync( await retryService.StartAsync(); retryServiceStarted = true; + // This time when the history is fetched for the execution ID attached to the TimerFired, there *is* + // a stored history, so both messages can be processed and attached to the work item using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30))) { TaskOrchestrationWorkItem workItem = await retryService.LockNextTaskOrchestrationWorkItemAsync( From 479051d5e7271860a94a8065ab6401d2b13548d4 Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Thu, 10 Sep 2026 11:44:28 -0700 Subject: [PATCH 3/9] fixing comment typos --- .../AzureStorageScenarioTests.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs index 110e76cc3..f02ec3423 100644 --- a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs +++ b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs @@ -4037,9 +4037,10 @@ await controlQueue.AddMessageAsync( // Now confirm that both messages remain on the queue, even though no history was fetched for the // "future" execution ID attached to the TimerFired that has not yet been committed to the history table. - // Critically, we want to abandon both the TimerFired *and* the EventRaisedEvent even though the latter has + // Critically, we want to abandon both the TimerFired *and* the EventRaisedEvent even though the latter // targets no specific execution ID. - // No work item is generated since no history was fetched, but both messages will be retried again after the visibility timeout expires. + // No work item is generated since no history was fetched, but both messages will be retried again after + // the visibility timeout expires. using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30))) { TaskOrchestrationWorkItem workItem = await service.LockNextTaskOrchestrationWorkItemAsync( From 2724a4bb39a713c8514dd8945ecca4ad3bad109f Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Thu, 10 Sep 2026 15:14:53 -0700 Subject: [PATCH 4/9] fixed the bug where external events were not deleted for terminal orchestrations --- .../AzureStorageOrchestrationService.cs | 31 +-- .../AzureStorageScenarioTests.cs | 188 +++++++++++++++++- 2 files changed, 195 insertions(+), 24 deletions(-) diff --git a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs index 5e8f7a7d3..c488b9e4e 100644 --- a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs +++ b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs @@ -802,7 +802,7 @@ async Task LockNextTaskOrchestrationWorkItemAsync(boo TraceContext = currentRequestTraceContext, }; - string warningMessage = await this.IsExecutableInstanceAsync( + (string warningMessage, bool isKnownTerminalInstance) = await this.IsExecutableInstanceAsync( session.RuntimeState, orchestrationWorkItem.NewMessages, settings.AllowReplayingTerminalInstances, @@ -829,12 +829,15 @@ async Task LockNextTaskOrchestrationWorkItemAsync(boo // If no messages have a matching execution ID, then delete all of them. This means all the // messages are external (external events, termination, etc.) and were sent to an instance that - // doesn't exist or is no longer in a running state. - // This is only safe to do if the session's execution ID is itself null, otherwise the history - // could be missing due to trying to fetch a particular execution ID that no longer exists for - // example due to a continue-as-new. In that case we do not want to delete the external messages - // but rather retry them on the current execution - if (messagesToDiscard.Count == 0 && session.Instance.ExecutionId == null) + // doesn't exist or is no longer in a running state: + // - If the session's ExecutionId is null, that means no history exists for this instance at all + // (since the session adopts whatever ExecutionId it finds in history, if it was not already set) + // - If the ExecutionId is non-null, then either there exists state for a terminal instance, or + // some of the messages in the batch had an execution ID with no matching history. In the first case, + // we want to delete the message, in the second case we want to abandon it. To distinguish between the two, + // IsExecutableInstanceAsync explicitly reports whether the instance is known to be terminal. + if (messagesToDiscard.Count == 0 && + (session.Instance.ExecutionId == null || isKnownTerminalInstance)) { messagesToDiscard.AddRange(messagesToAbandon); messagesToAbandon.Clear(); @@ -1070,7 +1073,7 @@ internal static void TraceMessageReceived(AzureStorageOrchestrationServiceSettin data.Episode.GetValueOrDefault(-1)); } - async Task IsExecutableInstanceAsync( + async Task<(string WarningMessage, bool IsKnownTerminalInstance)> IsExecutableInstanceAsync( OrchestrationRuntimeState runtimeState, IList newMessages, bool allowReplayingTerminalInstances, @@ -1082,7 +1085,7 @@ async Task IsExecutableInstanceAsync( if (DurableTask.Core.Common.Entities.AutoStart(instanceId, newMessages)) { - return null; + return (null, false); } else { @@ -1093,7 +1096,7 @@ async Task IsExecutableInstanceAsync( await this.trackingStore.UpdateStatusForTerminationAsync( instanceId, executionTerminatedEvent); - return $"Instance is {OrchestrationStatus.Terminated}"; + return ($"Instance is {OrchestrationStatus.Terminated}", true); } // A non-zero event count usually happens when an instance's history is overwritten by a @@ -1103,7 +1106,9 @@ await this.trackingStore.UpdateStatusForTerminationAsync( // the old history and we receive a message from the old instance (this happens frequently // with canceled durable timer messages) we'll end up loading just the history that hasn't // been fully overwritten. We know it's invalid because it's missing the ExecutionStartedEvent. - return runtimeState.Events.Count == 0 ? "No such instance" : "Invalid history (may have been overwritten by a newer instance)"; + return ( + runtimeState.Events.Count == 0 ? "No such instance" : "Invalid history (may have been overwritten by a newer instance)", + false); } } @@ -1125,11 +1130,11 @@ await this.trackingStore.UpdateInstanceStatusForCompletedOrchestrationAsync( } if (!allowReplayingTerminalInstances) { - return $"Instance is {runtimeState.OrchestrationStatus}"; + return ($"Instance is {runtimeState.OrchestrationStatus}", true); } } - return null; + return (null, false); } async Task AbandonAndReleaseSessionAsync(OrchestrationSession session) diff --git a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs index f02ec3423..a2b7957be 100644 --- a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs +++ b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs @@ -657,6 +657,13 @@ private async Task GetBlobCount(string containerName, string directoryName) return await containerClient.GetBlobsAsync(traits: BlobTraits.Metadata, states: BlobStates.None, prefix: directoryName, cancellationToken: default).CountAsync(); } + static async Task GetControlQueueMessageCountAsync(AzureStorageOrchestrationService service) + { + int[] messageCounts = await Task.WhenAll( + service.AllControlQueues.Select(queue => queue.InnerQueue.GetApproximateMessagesCountAsync())); + return messageCounts.Sum(); + } + [TestMethod] public async Task PurgeMultipleInstancesHistoryByTimePeriod_ScalabilityValidation() @@ -2947,6 +2954,13 @@ public async Task TestWorkerFailingDuringCompleteWorkItemCallCompletedOrchestrat Assert.AreEqual(OrchestrationStatus.Completed, status.OrchestrationStatus); Assert.AreEqual(input, JToken.Parse(status.Output).ToString()); Assert.AreEqual(input, JToken.Parse(status.Input).ToString()); + if (!terminate) + { + Assert.AreEqual( + 0, + await GetControlQueueMessageCountAsync(host.service), + "The external event sent to the completed orchestration should be deleted."); + } // Now simulate there being no instance entity (which can be the case for suborchestrations that complete in one execution), and try again await instanceTable.DeleteEntityAsync(entity, Azure.ETag.All); @@ -2972,6 +2986,13 @@ public async Task TestWorkerFailingDuringCompleteWorkItemCallCompletedOrchestrat Assert.IsTrue(status.Name.Contains(nameof(Orchestrations.Echo))); Assert.IsTrue(status.Tags.Contains(new KeyValuePair("key", "value"))); Assert.AreEqual(executionId, status.OrchestrationInstance.ExecutionId); + if (!terminate) + { + Assert.AreEqual( + 0, + await GetControlQueueMessageCountAsync(host.service), + "The external event sent after deleting the completed orchestration's instance row should be deleted."); + } await host.StopAsync(); } @@ -3806,9 +3827,13 @@ await service.CreateTaskOrchestrationAsync( } [DataTestMethod] - [DataRow(true)] - [DataRow(false)] - public async Task WorkerAttemptingToDequeueMessageForNonExistentInstance(bool extendedSessionsEnabled) + [DataRow(true, false)] + [DataRow(false, false)] + [DataRow(true, true)] + [DataRow(false, true)] + public async Task WorkerAttemptingToDequeueMessageForNonExistentInstance( + bool extendedSessionsEnabled, + bool sendExternalEvent) { AzureStorageOrchestrationService service = null; try @@ -3825,8 +3850,25 @@ public async Task WorkerAttemptingToDequeueMessageForNonExistentInstance(bool ex await service.CreateAsync(); await service.StartAsync(); - await service.SendTaskOrchestrationMessageAsync( - new TaskMessage + TaskMessage message; + if (sendExternalEvent) + { + message = new TaskMessage + { + OrchestrationInstance = new OrchestrationInstance + { + InstanceId = "instance_id", + ExecutionId = null, + }, + Event = new EventRaisedEvent(-1, string.Empty) + { + Name = "event", + }, + }; + } + else + { + message = new TaskMessage { OrchestrationInstance = new OrchestrationInstance { @@ -3836,10 +3878,17 @@ await service.SendTaskOrchestrationMessageAsync( Event = new TaskCompletedEvent(-1, 0, string.Empty) { Timestamp = DateTime.UtcNow - TimeSpan.FromMinutes(1), - } - }); + }, + }; + } + + await service.SendTaskOrchestrationMessageAsync( + message); - for (int i = 0; i < 6; i++) + // Task responses are given five benefit-of-the-doubt abandonments before deletion. External events are + // not out-of-order messages, so an event for a nonexistent instance should be deleted immediately. + int dequeueAttempts = sendExternalEvent ? 1 : 6; + for (int i = 0; i < dequeueAttempts; i++) { var workItem = await service.LockNextTaskOrchestrationWorkItemAsync( TimeSpan.FromMinutes(1), @@ -3847,9 +3896,10 @@ await service.SendTaskOrchestrationMessageAsync( Assert.IsNull(workItem); } - // On the last attempt, the message should have been deleted since we have exceeded the maximum abandonment count - // for a message to a nonexistent instance (5) - Assert.IsNull(await service.OwnedControlQueues.Single().InnerQueue.PeekMessageAsync()); + Assert.AreEqual( + 0, + await GetControlQueueMessageCountAsync(service), + "The message for the nonexistent orchestration should be deleted rather than abandoned."); } finally { @@ -4127,6 +4177,122 @@ await service.TrackingStore.UpdateStateAsync( } } + [TestMethod] + public async Task WorkerDiscardsExecutionIndependentMessagesWhenPendingInstanceIsTerminated() + { + AzureStorageOrchestrationService service = null; + bool serviceStarted = false; + + string instanceId = Guid.NewGuid().ToString(); + string executionId = Guid.NewGuid().ToString(); + + var settings = new AzureStorageOrchestrationServiceSettings + { + PartitionCount = 1, + StorageAccountClientProvider = new StorageAccountClientProvider(TestHelpers.GetTestStorageAccountConnectionString()), + TaskHubName = "PendingTermination" + Guid.NewGuid().ToString("N").Substring(0, 8), + ExtendedSessionsEnabled = false, + ControlQueueVisibilityTimeout = TimeSpan.FromSeconds(5), + UseAppLease = false, + }; + + try + { + service = new AzureStorageOrchestrationService(settings); + await service.CreateAsync(); + + var orchestrationInstance = new OrchestrationInstance + { + InstanceId = instanceId, + ExecutionId = executionId, + }; + var executionStartedEvent = new ExecutionStartedEvent(-1, string.Empty) + { + Name = "orchestration", + Version = string.Empty, + OrchestrationInstance = orchestrationInstance, + }; + + // Create only the pending instance row, without committing any history or enqueueing its start message. + Assert.IsTrue(await service.TrackingStore.SetNewExecutionAsync(executionStartedEvent, null, null)); + InstanceStatus status = await service.TrackingStore.FetchInstanceStatusAsync(instanceId); + Assert.AreEqual(OrchestrationStatus.Pending, status.State.OrchestrationStatus); + Assert.AreEqual( + 0, + (await service.TrackingStore.GetHistoryEventsAsync(instanceId, executionId)).Events.Count); + + var controlQueue = service.AllControlQueues.Single(); + var sourceInstance = new OrchestrationInstance + { + InstanceId = "source", + ExecutionId = "source-execution", + }; + + // Now terminate the pending orchestration + await controlQueue.AddMessageAsync( + new TaskMessage + { + OrchestrationInstance = new OrchestrationInstance { InstanceId = instanceId }, + Event = new ExecutionTerminatedEvent(-1, "terminate"), + }, + sourceInstance); + + await service.StartAsync(); + serviceStarted = true; + + using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30))) + { + TaskOrchestrationWorkItem workItem = await service.LockNextTaskOrchestrationWorkItemAsync( + TimeSpan.FromSeconds(30), + timeout.Token); + Assert.IsNull(workItem); + } + + status = await service.TrackingStore.FetchInstanceStatusAsync(instanceId); + Assert.AreEqual(OrchestrationStatus.Terminated, status.State.OrchestrationStatus); + Assert.AreEqual( + 0, + await controlQueue.InnerQueue.GetApproximateMessagesCountAsync(), + "The termination message should be deleted after terminating the pending instance."); + + // Now try to send an external event to the terminated pending instance. It should be deleted rather than abandoned. + await controlQueue.AddMessageAsync( + new TaskMessage + { + OrchestrationInstance = new OrchestrationInstance { InstanceId = instanceId }, + Event = new EventRaisedEvent(-1, string.Empty) { Name = "event" }, + }, + sourceInstance); + + using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30))) + { + TaskOrchestrationWorkItem workItem = await service.LockNextTaskOrchestrationWorkItemAsync( + TimeSpan.FromSeconds(30), + timeout.Token); + Assert.IsNull(workItem); + } + + Assert.AreEqual( + 0, + await controlQueue.InnerQueue.GetApproximateMessagesCountAsync(), + "The external event sent to the terminated pending instance should be deleted."); + } + finally + { + if (serviceStarted) + { + await service.StopAsync(isForced: true); + } + + if (service != null) + { + await service.DeleteAsync(); + } + + service?.Dispose(); + } + } + [DataTestMethod] [DataRow(true, true)] [DataRow(false, true)] From 6a81a59658473bbb2dc5a6f70304db1679803644 Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Thu, 10 Sep 2026 16:25:09 -0700 Subject: [PATCH 5/9] simplified the logic to only discard messages for an explicit terminal instance --- .../AzureStorageOrchestrationService.cs | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs index c488b9e4e..baadbcb52 100644 --- a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs +++ b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs @@ -827,17 +827,11 @@ async Task LockNextTaskOrchestrationWorkItemAsync(boo } } - // If no messages have a matching execution ID, then delete all of them. This means all the - // messages are external (external events, termination, etc.) and were sent to an instance that - // doesn't exist or is no longer in a running state: - // - If the session's ExecutionId is null, that means no history exists for this instance at all - // (since the session adopts whatever ExecutionId it finds in history, if it was not already set) - // - If the ExecutionId is non-null, then either there exists state for a terminal instance, or - // some of the messages in the batch had an execution ID with no matching history. In the first case, - // we want to delete the message, in the second case we want to abandon it. To distinguish between the two, - // IsExecutableInstanceAsync explicitly reports whether the instance is known to be terminal. - if (messagesToDiscard.Count == 0 && - (session.Instance.ExecutionId == null || isKnownTerminalInstance)) + // If the instance is known to be terminal, delete all messages. + // We don't necessarily want to do this for an instance with an empty history, because it + // could be that there is no history for the specific execution attached to session.Instance.ExecutionId. + // In this case, we would want to retry any external events that do not target a specific execution ID. + if (isKnownTerminalInstance) { messagesToDiscard.AddRange(messagesToAbandon); messagesToAbandon.Clear(); From 80796633ee47e80a353f77112ed953bfee8ecf23 Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Thu, 10 Sep 2026 16:35:09 -0700 Subject: [PATCH 6/9] added a more comprehensive test for terminal instances --- .../AzureStorageScenarioTests.cs | 139 ++++++++++++++++-- 1 file changed, 125 insertions(+), 14 deletions(-) diff --git a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs index a2b7957be..87335a64d 100644 --- a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs +++ b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs @@ -2954,13 +2954,6 @@ public async Task TestWorkerFailingDuringCompleteWorkItemCallCompletedOrchestrat Assert.AreEqual(OrchestrationStatus.Completed, status.OrchestrationStatus); Assert.AreEqual(input, JToken.Parse(status.Output).ToString()); Assert.AreEqual(input, JToken.Parse(status.Input).ToString()); - if (!terminate) - { - Assert.AreEqual( - 0, - await GetControlQueueMessageCountAsync(host.service), - "The external event sent to the completed orchestration should be deleted."); - } // Now simulate there being no instance entity (which can be the case for suborchestrations that complete in one execution), and try again await instanceTable.DeleteEntityAsync(entity, Azure.ETag.All); @@ -2986,13 +2979,6 @@ await GetControlQueueMessageCountAsync(host.service), Assert.IsTrue(status.Name.Contains(nameof(Orchestrations.Echo))); Assert.IsTrue(status.Tags.Contains(new KeyValuePair("key", "value"))); Assert.AreEqual(executionId, status.OrchestrationInstance.ExecutionId); - if (!terminate) - { - Assert.AreEqual( - 0, - await GetControlQueueMessageCountAsync(host.service), - "The external event sent after deleting the completed orchestration's instance row should be deleted."); - } await host.StopAsync(); } @@ -3184,6 +3170,131 @@ public async Task TestWorkerFailingDuringCompleteWorkItemCallTerminatedOrchestra } } + [DataTestMethod] + [DataRow(OrchestrationStatus.Completed, false)] + [DataRow(OrchestrationStatus.Failed, false)] + [DataRow(OrchestrationStatus.Terminated, false)] + [DataRow(OrchestrationStatus.Completed, true)] + [DataRow(OrchestrationStatus.Failed, true)] + [DataRow(OrchestrationStatus.Terminated, true)] + public async Task WorkerDeletesMessagesForTerminalOrchestration( + OrchestrationStatus terminalStatus, + bool includeExecutionSpecificMessage) + { + AzureStorageOrchestrationService service = null; + bool serviceStarted = false; + + string instanceId = Guid.NewGuid().ToString(); + string executionId = Guid.NewGuid().ToString(); + var orchestrationInstance = new OrchestrationInstance + { + InstanceId = instanceId, + ExecutionId = executionId, + }; + + var settings = new AzureStorageOrchestrationServiceSettings + { + PartitionCount = 1, + StorageAccountClientProvider = new StorageAccountClientProvider(TestHelpers.GetTestStorageAccountConnectionString()), + TaskHubName = "TerminalMessages" + Guid.NewGuid().ToString("N").Substring(0, 10), + ExtendedSessionsEnabled = false, + UseAppLease = false, + }; + + try + { + service = new AzureStorageOrchestrationService(settings); + await service.CreateAsync(); + + // Create a completed orchestration history with the specific terminal status + OrchestrationHistory emptyHistory = await service.TrackingStore.GetHistoryEventsAsync( + instanceId, + executionId); + var runtimeState = new OrchestrationRuntimeState(); + runtimeState.AddEvent(new OrchestratorStartedEvent(-1)); + runtimeState.AddEvent(new ExecutionStartedEvent(-1, string.Empty) + { + Name = "orchestration", + Version = string.Empty, + OrchestrationInstance = orchestrationInstance, + }); + if (includeExecutionSpecificMessage) + { + runtimeState.AddEvent(new TaskScheduledEvent(0)); + } + + runtimeState.AddEvent(new ExecutionCompletedEvent(1, "output", terminalStatus)); + runtimeState.AddEvent(new OrchestratorCompletedEvent(-1)); + + await service.TrackingStore.UpdateStateAsync( + runtimeState, + new OrchestrationRuntimeState(), + instanceId, + executionId, + new OrchestrationETags { HistoryETag = emptyHistory.ETag }, + emptyHistory.TrackingStoreContext); + + var controlQueue = service.AllControlQueues.Single(); + var sourceInstance = new OrchestrationInstance + { + InstanceId = "source", + ExecutionId = "source-execution", + }; + + // Enqueue an external event that targets no specific execution ID and potentially an + // event that does target the specific execution ID of the terminal orchestration + if (includeExecutionSpecificMessage) + { + await controlQueue.AddMessageAsync( + new TaskMessage + { + OrchestrationInstance = orchestrationInstance, + Event = new TaskCompletedEvent(-1, 0, "result"), + }, + sourceInstance); + } + + await controlQueue.AddMessageAsync( + new TaskMessage + { + OrchestrationInstance = new OrchestrationInstance { InstanceId = instanceId }, + Event = new EventRaisedEvent(-1, string.Empty) { Name = "event" }, + }, + sourceInstance); + + await service.StartAsync(); + serviceStarted = true; + + using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30))) + { + TaskOrchestrationWorkItem workItem = await service.LockNextTaskOrchestrationWorkItemAsync( + TimeSpan.FromSeconds(30), + timeout.Token); + Assert.IsNull(workItem); + } + + // Confirm both are deleted + Assert.AreEqual( + 0, + await GetControlQueueMessageCountAsync(service), + "All messages sent to the terminal orchestration should be deleted."); + } + finally + { + if (serviceStarted) + { + await service.StopAsync(isForced: true); + } + + if (service != null) + { + await service.DeleteAsync(); + } + + service?.Dispose(); + } + } + /// /// Same as but for an orchestration with large input /// and output, which will need to be stored in blob storage. From 9c876620c6effd0aafb7c3f05a2b50107a278568 Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Thu, 10 Sep 2026 22:37:12 -0700 Subject: [PATCH 7/9] switched to a much simpler and cleaner and consistent implementation --- .../AzureStorageOrchestrationService.cs | 31 ++- .../AzureStorageScenarioTests.cs | 260 +++++++++++++++++- 2 files changed, 271 insertions(+), 20 deletions(-) diff --git a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs index baadbcb52..d7b601bec 100644 --- a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs +++ b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs @@ -802,7 +802,7 @@ async Task LockNextTaskOrchestrationWorkItemAsync(boo TraceContext = currentRequestTraceContext, }; - (string warningMessage, bool isKnownTerminalInstance) = await this.IsExecutableInstanceAsync( + string warningMessage = await this.IsExecutableInstanceAsync( session.RuntimeState, orchestrationWorkItem.NewMessages, settings.AllowReplayingTerminalInstances, @@ -827,11 +827,16 @@ async Task LockNextTaskOrchestrationWorkItemAsync(boo } } - // If the instance is known to be terminal, delete all messages. - // We don't necessarily want to do this for an instance with an empty history, because it - // could be that there is no history for the specific execution attached to session.Instance.ExecutionId. - // In this case, we would want to retry any external events that do not target a specific execution ID. - if (isKnownTerminalInstance) + bool matchingExecutionMessageWasAbandoned = outOfOrderMessages?.Any( + msg => msg.TaskMessage.OrchestrationInstance.ExecutionId == session.Instance.ExecutionId) == true; + + // If no remaining or abandoned message targeted the session's execution, then no message + // pinned the history lookup to a specific execution and the latest history was fetched, so it + // is safe to discard all remaining messages. + // Otherwise, preserve execution-independent messages because there may be a valid history for + // another execution ID committed. + if (messagesToDiscard.Count == 0 && + !matchingExecutionMessageWasAbandoned) { messagesToDiscard.AddRange(messagesToAbandon); messagesToAbandon.Clear(); @@ -1067,7 +1072,7 @@ internal static void TraceMessageReceived(AzureStorageOrchestrationServiceSettin data.Episode.GetValueOrDefault(-1)); } - async Task<(string WarningMessage, bool IsKnownTerminalInstance)> IsExecutableInstanceAsync( + async Task IsExecutableInstanceAsync( OrchestrationRuntimeState runtimeState, IList newMessages, bool allowReplayingTerminalInstances, @@ -1079,7 +1084,7 @@ internal static void TraceMessageReceived(AzureStorageOrchestrationServiceSettin if (DurableTask.Core.Common.Entities.AutoStart(instanceId, newMessages)) { - return (null, false); + return null; } else { @@ -1090,7 +1095,7 @@ internal static void TraceMessageReceived(AzureStorageOrchestrationServiceSettin await this.trackingStore.UpdateStatusForTerminationAsync( instanceId, executionTerminatedEvent); - return ($"Instance is {OrchestrationStatus.Terminated}", true); + return $"Instance is {OrchestrationStatus.Terminated}"; } // A non-zero event count usually happens when an instance's history is overwritten by a @@ -1100,9 +1105,7 @@ await this.trackingStore.UpdateStatusForTerminationAsync( // the old history and we receive a message from the old instance (this happens frequently // with canceled durable timer messages) we'll end up loading just the history that hasn't // been fully overwritten. We know it's invalid because it's missing the ExecutionStartedEvent. - return ( - runtimeState.Events.Count == 0 ? "No such instance" : "Invalid history (may have been overwritten by a newer instance)", - false); + return runtimeState.Events.Count == 0 ? "No such instance" : "Invalid history (may have been overwritten by a newer instance)"; } } @@ -1124,11 +1127,11 @@ await this.trackingStore.UpdateInstanceStatusForCompletedOrchestrationAsync( } if (!allowReplayingTerminalInstances) { - return ($"Instance is {runtimeState.OrchestrationStatus}", true); + return $"Instance is {runtimeState.OrchestrationStatus}"; } } - return (null, false); + return null; } async Task AbandonAndReleaseSessionAsync(OrchestrationSession session) diff --git a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs index 87335a64d..d07babea9 100644 --- a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs +++ b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs @@ -33,6 +33,7 @@ namespace DurableTask.AzureStorage.Tests using System.IO; using System.Linq; using System.Net; + using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Threading; @@ -3265,15 +3266,19 @@ await controlQueue.AddMessageAsync( await service.StartAsync(); serviceStarted = true; - using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30))) + int dequeueAttempts = includeExecutionSpecificMessage ? 2 : 1; + for (int i = 0; i < dequeueAttempts; i++) { - TaskOrchestrationWorkItem workItem = await service.LockNextTaskOrchestrationWorkItemAsync( - TimeSpan.FromSeconds(30), - timeout.Token); - Assert.IsNull(workItem); + using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30))) + { + TaskOrchestrationWorkItem workItem = await service.LockNextTaskOrchestrationWorkItemAsync( + TimeSpan.FromSeconds(30), + timeout.Token); + Assert.IsNull(workItem); + } } - // Confirm both are deleted + // Confirm all messages are deleted. Assert.AreEqual( 0, await GetControlQueueMessageCountAsync(service), @@ -3295,6 +3300,249 @@ await GetControlQueueMessageCountAsync(service), } } + [DataTestMethod] + [DataRow(true)] + [DataRow(false)] + public async Task WorkerDoesNotDiscardExternalEventBatchedWithStaleTerminalMessageDuringInstanceReuse( + bool includeTaskScheduledEvent) + { + AzureStorageOrchestrationService service = null; + bool serviceStarted = false; + + string instanceId = Guid.NewGuid().ToString(); + string oldExecutionId = Guid.NewGuid().ToString(); + string newExecutionId = Guid.NewGuid().ToString(); + + var settings = new AzureStorageOrchestrationServiceSettings + { + PartitionCount = 1, + StorageAccountClientProvider = new StorageAccountClientProvider(TestHelpers.GetTestStorageAccountConnectionString()), + TaskHubName = "ReusedInstance" + Guid.NewGuid().ToString("N").Substring(0, 10), + ExtendedSessionsEnabled = false, + UseAppLease = false, + }; + + try + { + service = new AzureStorageOrchestrationService(settings); + await service.CreateAsync(); + + var oldInstance = new OrchestrationInstance + { + InstanceId = instanceId, + ExecutionId = oldExecutionId, + }; + + // First create a terminal orchestration with the old execution ID + OrchestrationHistory emptyHistory = await service.TrackingStore.GetHistoryEventsAsync( + instanceId, + oldExecutionId); + var oldRuntimeState = new OrchestrationRuntimeState(); + oldRuntimeState.AddEvent(new OrchestratorStartedEvent(-1)); + oldRuntimeState.AddEvent(new ExecutionStartedEvent(-1, string.Empty) + { + Name = "orchestration", + Version = string.Empty, + OrchestrationInstance = oldInstance, + }); + if (includeTaskScheduledEvent) + { + oldRuntimeState.AddEvent(new TaskScheduledEvent(0)); + } + + oldRuntimeState.AddEvent(new ExecutionCompletedEvent(1, "output", OrchestrationStatus.Completed)); + oldRuntimeState.AddEvent(new OrchestratorCompletedEvent(-1)); + + await service.TrackingStore.UpdateStateAsync( + oldRuntimeState, + new OrchestrationRuntimeState(), + instanceId, + oldExecutionId, + new OrchestrationETags { HistoryETag = emptyHistory.ETag }, + emptyHistory.TrackingStoreContext); + + var newInstance = new OrchestrationInstance + { + InstanceId = instanceId, + ExecutionId = newExecutionId, + }; + var newExecutionStartedEvent = new ExecutionStartedEvent(-1, string.Empty) + { + Name = "orchestration", + Version = string.Empty, + OrchestrationInstance = newInstance, + Generation = 1, + }; + + InstanceStatus oldInstanceStatus = await service.TrackingStore.FetchInstanceStatusAsync(instanceId); + Assert.IsNotNull(oldInstanceStatus); + Assert.IsTrue(await service.TrackingStore.SetNewExecutionAsync( + newExecutionStartedEvent, + oldInstanceStatus.ETag, + inputPayloadOverride: null)); + + InstanceStatus pendingInstance = await service.TrackingStore.FetchInstanceStatusAsync(instanceId); + Assert.IsNotNull(pendingInstance); + Assert.AreEqual(newExecutionId, pendingInstance.State.OrchestrationInstance.ExecutionId); + Assert.AreEqual(OrchestrationStatus.Pending, pendingInstance.State.OrchestrationStatus); + + var controlQueue = service.AllControlQueues.Single(); + var sourceInstance = new OrchestrationInstance + { + InstanceId = "source", + ExecutionId = "source-execution", + }; + + // A delayed message for the old execution can arrive after the new ExecutionStarted message. + // The execution-independent event then joins the newer message batch targeting the old execution + // rather than the message batch containing the ExecutionStarted event for the new execution. + await controlQueue.AddMessageAsync( + new TaskMessage + { + OrchestrationInstance = oldInstance, + Event = new TaskCompletedEvent(-1, 0, "result"), + }, + sourceInstance); + await controlQueue.AddMessageAsync( + new TaskMessage + { + OrchestrationInstance = new OrchestrationInstance { InstanceId = instanceId }, + Event = new EventRaisedEvent(-1, string.Empty) { Name = "event" }, + }, + sourceInstance); + await controlQueue.AddMessageAsync( + new TaskMessage + { + OrchestrationInstance = newInstance, + Event = newExecutionStartedEvent, + }, + sourceInstance); + + // Fetch the messages directly so their pending-batch assignment is deterministic. The new + // ExecutionStarted message was enqueued after the stale messages and must form its own batch, + // while the external event joins the batch created by the stale TaskCompleted message. + var queuedMessages = new List(); + using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30))) + { + while (queuedMessages.Count < 3) + { + queuedMessages.AddRange(await controlQueue.GetMessagesAsync(timeout.Token)); + } + } + + Assert.AreEqual(3, queuedMessages.Count); + MessageData executionStartedMessage = queuedMessages.Single( + message => message.TaskMessage.Event is ExecutionStartedEvent); + MessageData staleTaskCompletedMessage = queuedMessages.Single( + message => message.TaskMessage.Event is TaskCompletedEvent); + MessageData externalEventMessage = queuedMessages.Single( + message => message.TaskMessage.Event is EventRaisedEvent); + + // Initialize the service lifecycle without allowing its queue listener to compete with + // the messages that this test assigns to pending batches explicitly. + settings.ControlQueueBufferThreshold = 0; + await service.StartAsync(); + serviceStarted = true; + + var sessionManagerField = typeof(AzureStorageOrchestrationService).GetField( + "orchestrationSessionManager", + BindingFlags.Instance | BindingFlags.NonPublic); + Assert.IsNotNull(sessionManagerField); + var sessionManager = (OrchestrationSessionManager)sessionManagerField.GetValue(service); + + Guid traceActivityId = Guid.NewGuid(); + sessionManager.AddMessageToPendingOrchestration( + controlQueue, + new[] { staleTaskCompletedMessage, externalEventMessage }, + traceActivityId, + CancellationToken.None); + sessionManager.AddMessageToPendingOrchestration( + controlQueue, + new[] { executionStartedMessage }, + traceActivityId, + CancellationToken.None); + + bool externalEventDelivered = false; + bool staleTerminalBatchProcessed = false; + for (int attempt = 0; attempt < 3 && !externalEventDelivered; attempt++) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + TaskOrchestrationWorkItem workItem = await service.LockNextTaskOrchestrationWorkItemAsync( + TimeSpan.FromSeconds(30), + timeout.Token); + + // The stale terminal batch does not produce a work item. The TaskCompleted event is either + // discarded or removed as out of order, and the EventRaised event is abandoned and retried. + if (workItem == null) + { + staleTerminalBatchProcessed = true; + continue; + } + + if (workItem.NewMessages.Any(message => message.Event is EventRaisedEvent)) + { + // Either the ExecutionStartedEvent batch was committed first, in which case the execution ID is + // already part of the orchestration runtime state and this EventRaisedEvent is retried by itself + // after the work item with the stale TaskCompletedEvent is abandoned. + // Or the ExecutionStartedEvent batch was dequeued second, in which case the EventRaisedEvent has + // already been abandoned and is retried with the ExecutionStartedEvent as part of the new messages too + string executionId = workItem.OrchestrationRuntimeState.OrchestrationInstance?.ExecutionId ?? + workItem.NewMessages.Single(message => message.Event is ExecutionStartedEvent) + .OrchestrationInstance.ExecutionId; + + Assert.AreEqual(newExecutionId, executionId); + Assert.IsFalse(workItem.NewMessages.Any(message => message.Event is TaskCompletedEvent)); + externalEventDelivered = true; + await service.AbandonTaskOrchestrationWorkItemAsync(workItem); + await service.ReleaseTaskOrchestrationWorkItemAsync(workItem); + break; + } + + // If the new ExecutionStarted batch is dequeued first, commit it so that the deferred + // external event can subsequently be loaded against the new execution's history. + Assert.AreEqual(1, workItem.NewMessages.Count); + Assert.IsInstanceOfType(workItem.NewMessages.Single().Event, typeof(ExecutionStartedEvent)); + Assert.AreEqual(newExecutionId, workItem.NewMessages.Single().OrchestrationInstance.ExecutionId); + + OrchestrationRuntimeState newRuntimeState = workItem.OrchestrationRuntimeState; + newRuntimeState.AddEvent(new OrchestratorStartedEvent(-1)); + newRuntimeState.AddEvent(newExecutionStartedEvent); + newRuntimeState.AddEvent(new OrchestratorCompletedEvent(-1)); + + await service.CompleteTaskOrchestrationWorkItemAsync( + workItem, + newRuntimeState, + new List(), + new List(), + new List(), + null, + null); + await service.ReleaseTaskOrchestrationWorkItemAsync(workItem); + } + + Assert.IsTrue( + staleTerminalBatchProcessed, + "The stale execution-specific message should be processed against the old terminal history."); + Assert.IsTrue( + externalEventDelivered, + "The execution-independent event should be delivered to the recreated execution."); + } + finally + { + if (serviceStarted) + { + await service.StopAsync(isForced: true); + } + + if (service != null) + { + await service.DeleteAsync(); + } + + service?.Dispose(); + } + } + /// /// Same as but for an orchestration with large input /// and output, which will need to be stored in blob storage. From 8ccc2f05a9cbb9cede94a1fdf88a6db3fb679535 Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Thu, 10 Sep 2026 22:40:51 -0700 Subject: [PATCH 8/9] slight comment update --- .../AzureStorageOrchestrationService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs index d7b601bec..3cdedc9e1 100644 --- a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs +++ b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs @@ -832,9 +832,9 @@ async Task LockNextTaskOrchestrationWorkItemAsync(boo // If no remaining or abandoned message targeted the session's execution, then no message // pinned the history lookup to a specific execution and the latest history was fetched, so it - // is safe to discard all remaining messages. + // is safe to discard all remaining messages if the instance is not deemed executable. // Otherwise, preserve execution-independent messages because there may be a valid history for - // another execution ID committed. + // another execution ID stored. if (messagesToDiscard.Count == 0 && !matchingExecutionMessageWasAbandoned) { From a35fa25ee5ab8e85143fdc1eacfa5b163834a8d2 Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Thu, 10 Sep 2026 22:41:16 -0700 Subject: [PATCH 9/9] style update --- .../AzureStorageOrchestrationService.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs index 3cdedc9e1..f676e71a3 100644 --- a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs +++ b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs @@ -835,8 +835,7 @@ async Task LockNextTaskOrchestrationWorkItemAsync(boo // is safe to discard all remaining messages if the instance is not deemed executable. // Otherwise, preserve execution-independent messages because there may be a valid history for // another execution ID stored. - if (messagesToDiscard.Count == 0 && - !matchingExecutionMessageWasAbandoned) + if (messagesToDiscard.Count == 0 && !matchingExecutionMessageWasAbandoned) { messagesToDiscard.AddRange(messagesToAbandon); messagesToAbandon.Clear();