From 192bb1cd30c64c59b45381415aa5602dc394f070 Mon Sep 17 00:00:00 2001 From: Saurav Gupta Date: Thu, 15 Oct 2026 13:00:25 +0530 Subject: [PATCH 1/3] Fix unbounded memory growth when the orchestration state prefetch fails permanently When OrchestrationSessionManager.ScheduleOrchestrationStatePrefetch cannot load the history of a pending batch, the catch block logs the failure, waits 5 s, and then awaits a recursive call of the same method. Because the catch block contains an await, the compiler keeps the caught exception in the state machine until the method completes. The awaited recursive call completes only when a later attempt succeeds. If the failure is permanent (for example, a missing large-message blob that a History row refers to), every failed attempt, its exception, and the storage response stay in memory. Memory then increases by one attempt every 5 s until the process stops. The awaited recursion came from #633, which replaced the re-enqueue into a DispatchQueue with `await Task.Run(...)`. Before #633, the retry put a new work item in the queue and returned. Changes: - Do not await the re-scheduled prefetch. Each failed attempt now completes after it schedules the next attempt, as before #633. At most one failed attempt stays in memory for each pending batch. - Give the cancellation token to the retry delay, so that the retries stop at shutdown also when the tracking store ignores the token. - Add an internal PrefetchRetryDelay property (default 5 s) so that tests can use a short delay. - Add OrchestrationStatePrefetchTests. Three of the five tests fail without this change. --- .../OrchestrationStatePrefetchTests.cs | 390 ++++++++++++++++++ .../OrchestrationSessionManager.cs | 11 +- 2 files changed, 399 insertions(+), 2 deletions(-) create mode 100644 Test/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs diff --git a/Test/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs b/Test/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs new file mode 100644 index 00000000..87e610ef --- /dev/null +++ b/Test/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs @@ -0,0 +1,390 @@ +// ---------------------------------------------------------------------------------- +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +namespace DurableTask.AzureStorage.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Runtime.CompilerServices; + using System.Threading; + using System.Threading.Tasks; + using Azure; + using Azure.Storage.Queues.Models; + using DurableTask.AzureStorage.Messaging; + using DurableTask.AzureStorage.Monitoring; + using DurableTask.AzureStorage.Storage; + using DurableTask.AzureStorage.Tracking; + using DurableTask.Core; + using DurableTask.Core.History; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + /// + /// Tests for the retries of the orchestration state prefetch in . + /// The tests use an in-memory tracking store. They do not send requests to Azure Storage. + /// + [TestClass] + public class OrchestrationStatePrefetchTests + { + const string InstanceId = "prefetch-instance"; + const string ExecutionId = "prefetch-execution"; + static readonly TimeSpan WaitTimeout = TimeSpan.FromSeconds(30); + + AzureStorageOrchestrationServiceSettings settings; + ControlQueue controlQueue; + + [TestInitialize] + public void Initialize() + { + this.settings = new AzureStorageOrchestrationServiceSettings + { + // The storage clients are necessary to create a control queue, but the tests do not use them. + StorageAccountClientProvider = new StorageAccountClientProvider("UseDevelopmentStorage=true"), + }; + + var azureStorageClient = new AzureStorageClient(this.settings); + var messageManager = new MessageManager(this.settings, azureStorageClient, "prefetch-largemessages"); + this.controlQueue = new ControlQueue(azureStorageClient, "prefetch-control-00", messageManager); + } + + [TestCleanup] + public void Cleanup() + { + this.controlQueue?.Dispose(); + } + + /// + /// A history load that fails each time must not cause the failed attempts to stay in memory. + /// Each retry must release the previous attempt and its exception, also when no attempt completes. + /// + [TestMethod] + public async Task PrefetchRetry_PermanentFailure_DoesNotKeepFailedAttemptsInMemory() + { + const int FailedAttempts = 20; + var exceptions = new WeakReference[FailedAttempts]; + var pendingLoad = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var trackingStore = new FakeTrackingStore + { + OnGetHistory = attempt => + { + if (attempt > FailedAttempts) + { + // This attempt does not complete. Thus the retries are active, as they are in production. + return pendingLoad.Task; + } + + var exception = new SimulatedStorageException(attempt); + exceptions[attempt - 1] = new WeakReference(exception); + throw exception; + }, + }; + + using var manager = this.CreateManager(trackingStore); + using var shutdown = new CancellationTokenSource(); + manager.AddMessageToPendingOrchestration(this.controlQueue, new[] { this.CreateMessage() }, Guid.NewGuid(), shutdown.Token); + + await TestHelpers.WaitFor(() => trackingStore.HistoryCalls > FailedAttempts, WaitTimeout); + + bool[] live = GetLiveStatesAfterFullCollection(exceptions); + + shutdown.Cancel(); + pendingLoad.TrySetCanceled(); + + // In a build without optimization, the compiler can keep the exception of the latest failed attempt + // in the state machine until the next failure. The exceptions of the earlier attempts must not stay in memory. + int liveEarlierExceptions = live.Take(FailedAttempts - 1).Count(isLive => isLive); + Assert.AreEqual( + 0, + liveEarlierExceptions, + $"{liveEarlierExceptions} of {FailedAttempts - 1} exceptions from earlier failed history loads are still in memory. " + + $"Total live exceptions: {live.Count(isLive => isLive)} of {FailedAttempts}."); + } + + /// + /// When the history load succeeds after some failures, the batch becomes ready one time, with the loaded state. + /// + [TestMethod] + public async Task PrefetchRetry_SuccessAfterFailures_BatchIsReadyOneTimeWithState() + { + const int FailedAttempts = 3; + OrchestrationHistory history = CreateHistory(); + var trackingStore = new FakeTrackingStore + { + OnGetHistory = attempt => attempt <= FailedAttempts + ? throw new SimulatedStorageException(attempt) + : Task.FromResult(history), + }; + + using var manager = this.CreateManager(trackingStore); + manager.AddMessageToPendingOrchestration(this.controlQueue, new[] { this.CreateMessage() }, Guid.NewGuid(), CancellationToken.None); + + OrchestrationSession session; + using (var timeout = new CancellationTokenSource(WaitTimeout)) + { + session = await manager.GetNextSessionAsync(entitiesOnly: false, timeout.Token); + } + + Assert.IsNotNull(session); + Assert.AreEqual(FailedAttempts + 1, trackingStore.HistoryCalls); + Assert.AreEqual(InstanceId, session.Instance.InstanceId); + Assert.AreEqual(ExecutionId, session.Instance.ExecutionId); + Assert.AreSame(history.Events[0], session.RuntimeState.ExecutionStartedEvent); + Assert.AreEqual(history.ETag, session.ETags.HistoryETag); + Assert.AreEqual(1, session.CurrentMessageBatch.Count); + + // The batch must not become ready a second time. + using (var timeout = new CancellationTokenSource(TimeSpan.FromMilliseconds(500))) + { + try + { + OrchestrationSession secondSession = await manager.GetNextSessionAsync(entitiesOnly: false, timeout.Token); + Assert.IsNull(secondSession, "The batch became ready for processing more than one time."); + } + catch (OperationCanceledException) + { + // Expected: no other batch is ready. + } + } + + Assert.AreEqual(FailedAttempts + 1, trackingStore.HistoryCalls); + } + + /// + /// When the shutdown token is cancelled while the prefetch waits to try again, the prefetch stops without a new attempt. + /// + [TestMethod] + public async Task PrefetchRetry_CancelledDuringRetryDelay_StopsRetrying() + { + TimeSpan retryDelay = TimeSpan.FromMilliseconds(200); + var trackingStore = new FakeTrackingStore + { + OnGetHistory = attempt => throw new SimulatedStorageException(attempt), + }; + + using var manager = this.CreateManager(trackingStore, retryDelay); + using var shutdown = new CancellationTokenSource(); + manager.AddMessageToPendingOrchestration(this.controlQueue, new[] { this.CreateMessage() }, Guid.NewGuid(), shutdown.Token); + + await TestHelpers.WaitFor(() => trackingStore.HistoryCalls == 1, WaitTimeout); + await Task.Delay(TimeSpan.FromMilliseconds(50)); + shutdown.Cancel(); + + // Wait much longer than the retry delay. A retry that ignores the token would load the history again. + await Task.Delay(retryDelay + TimeSpan.FromSeconds(1)); + + Assert.AreEqual(1, trackingStore.HistoryCalls, "The prefetch tried to load the history again after cancellation."); + } + + /// + /// When the shutdown token is already cancelled, the prefetch stops after the first failure. + /// This must also occur when the store does not monitor the token. + /// + [TestMethod] + public async Task PrefetchRetry_TokenAlreadyCancelled_StopsAfterFirstFailure() + { + var trackingStore = new FakeTrackingStore + { + IgnoreCancellation = true, + OnGetHistory = attempt => throw new SimulatedStorageException(attempt), + }; + + using var manager = this.CreateManager(trackingStore); + using var shutdown = new CancellationTokenSource(); + shutdown.Cancel(); + + try + { + manager.AddMessageToPendingOrchestration(this.controlQueue, new[] { this.CreateMessage() }, Guid.NewGuid(), shutdown.Token); + await TestHelpers.WaitFor(() => trackingStore.HistoryCalls >= 1, WaitTimeout); + + // The retry delay is 1 ms. A retry that does not monitor the token would load the history many times in this time. + await Task.Delay(TimeSpan.FromMilliseconds(500)); + + Assert.AreEqual(1, trackingStore.HistoryCalls, "The prefetch tried to load the history again after cancellation."); + } + finally + { + // Make sure that a retry that continues stops at the next load. + trackingStore.IgnoreCancellation = false; + } + } + + /// + /// When the history is already loaded and a later step fails, the retry must not load the history again. + /// + [TestMethod] + public async Task PrefetchRetry_HistoryAlreadyLoaded_DoesNotLoadHistoryAgain() + { + // The instance ETag is loaded after the history. Make the first instance ETag load fail. + this.settings.UseInstanceTableEtag = true; + OrchestrationHistory history = CreateHistory(); + var trackingStore = new FakeTrackingStore + { + OnGetHistory = attempt => Task.FromResult(history), + OnFetchInstanceStatus = attempt => attempt == 1 + ? throw new SimulatedStorageException(attempt) + : Task.FromResult(null), + }; + + using var manager = this.CreateManager(trackingStore); + manager.AddMessageToPendingOrchestration(this.controlQueue, new[] { this.CreateMessage() }, Guid.NewGuid(), CancellationToken.None); + + OrchestrationSession session; + using (var timeout = new CancellationTokenSource(WaitTimeout)) + { + session = await manager.GetNextSessionAsync(entitiesOnly: false, timeout.Token); + } + + Assert.IsNotNull(session); + Assert.IsTrue(trackingStore.InstanceStatusCalls >= 1, "The instance ETag load did not run."); + Assert.AreEqual(1, trackingStore.HistoryCalls, "The retry loaded the history again."); + Assert.AreSame(history.Events[0], session.RuntimeState.ExecutionStartedEvent); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static bool[] GetLiveStatesAfterFullCollection(WeakReference[] references) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + return references.Select(reference => reference != null && reference.IsAlive).ToArray(); + } + + static OrchestrationHistory CreateHistory() + { + var executionStarted = new ExecutionStartedEvent(-1, null) + { + Name = "TestOrchestration", + Version = string.Empty, + OrchestrationInstance = new OrchestrationInstance { InstanceId = InstanceId, ExecutionId = ExecutionId }, + }; + + return new OrchestrationHistory(new List { executionStarted }, DateTime.UtcNow, new ETag("history-etag")); + } + + OrchestrationSessionManager CreateManager(FakeTrackingStore trackingStore, TimeSpan? retryDelay = null) + { + return new OrchestrationSessionManager("testaccount", this.settings, new AzureStorageOrchestrationServiceStats(), trackingStore) + { + PrefetchRetryDelay = retryDelay ?? TimeSpan.FromMilliseconds(1), + }; + } + + MessageData CreateMessage() + { + var taskMessage = new TaskMessage + { + OrchestrationInstance = new OrchestrationInstance { InstanceId = InstanceId, ExecutionId = ExecutionId }, + Event = new EventRaisedEvent(-1, null) { Name = "TestEvent" }, + }; + + return new MessageData(taskMessage, Guid.NewGuid(), this.controlQueue.Name, orchestrationEpisode: null, sender: new OrchestrationInstance()) + { + OriginalQueueMessage = QueuesModelFactory.QueueMessage( + messageId: Guid.NewGuid().ToString(), + popReceipt: "pop-receipt", + messageText: string.Empty, + dequeueCount: 1), + }; + } + + sealed class SimulatedStorageException : Exception + { + public SimulatedStorageException(int attempt) + : base($"Simulated storage failure {attempt}.") + { + // About 32 KB, as a large storage error response can be. + this.Payload = new string('x', 16 * 1024); + } + + public string Payload { get; } + } + + sealed class FakeTrackingStore : ITrackingStore + { + int historyCalls; + int instanceStatusCalls; + + public Func> OnGetHistory { get; set; } + + public Func> OnFetchInstanceStatus { get; set; } + + // Set to true to simulate a store that does not monitor the cancellation token. + public bool IgnoreCancellation { get; set; } + + public int HistoryCalls => Volatile.Read(ref this.historyCalls); + + public int InstanceStatusCalls => Volatile.Read(ref this.instanceStatusCalls); + + async Task ITrackingStore.GetHistoryEventsAsync(string instanceId, string expectedExecutionId, CancellationToken cancellationToken) + { + int attempt = Interlocked.Increment(ref this.historyCalls); + if (!this.IgnoreCancellation) + { + cancellationToken.ThrowIfCancellationRequested(); + } + + // Complete asynchronously, as a storage request does. + await Task.Yield(); + return await this.OnGetHistory(attempt); + } + + async Task ITrackingStore.FetchInstanceStatusAsync(string instanceId, CancellationToken cancellationToken) + { + int attempt = Interlocked.Increment(ref this.instanceStatusCalls); + cancellationToken.ThrowIfCancellationRequested(); + await Task.Yield(); + return await this.OnFetchInstanceStatus(attempt); + } + + Task ITrackingStore.CreateAsync(CancellationToken cancellationToken) => throw new NotSupportedException(); + + Task ITrackingStore.DeleteAsync(CancellationToken cancellationToken) => throw new NotSupportedException(); + + Task ITrackingStore.ExistsAsync(CancellationToken cancellationToken) => throw new NotSupportedException(); + + Task ITrackingStore.StartAsync(CancellationToken cancellationToken) => throw new NotSupportedException(); + + IAsyncEnumerable ITrackingStore.RewindHistoryAsync(string instanceId, CancellationToken cancellationToken) => throw new NotSupportedException(); + + Task ITrackingStore.UpdateStateAsync(OrchestrationRuntimeState newRuntimeState, OrchestrationRuntimeState oldRuntimeState, string instanceId, string executionId, OrchestrationETags eTags, object trackingStoreContext, CancellationToken cancellationToken) => throw new NotSupportedException(); + + IAsyncEnumerable ITrackingStore.GetStateAsync(string instanceId, bool allExecutions, bool fetchInput, CancellationToken cancellationToken) => throw new NotSupportedException(); + + Task ITrackingStore.GetStateAsync(string instanceId, string executionId, bool fetchInput, CancellationToken cancellationToken) => throw new NotSupportedException(); + + Task ITrackingStore.UpdateInstanceStatusForCompletedOrchestrationAsync(string instanceId, string executionId, OrchestrationRuntimeState runtimeState, bool instanceEntityExists, CancellationToken cancellationToken) => throw new NotSupportedException(); + + IAsyncEnumerable ITrackingStore.GetStateAsync(CancellationToken cancellationToken) => throw new NotSupportedException(); + + IAsyncEnumerable ITrackingStore.FetchInstanceStatusAsync(IEnumerable instanceIds, CancellationToken cancellationToken) => throw new NotSupportedException(); + + AsyncPageable ITrackingStore.GetStateAsync(DateTime createdTimeFrom, DateTime? createdTimeTo, IEnumerable runtimeStatus, CancellationToken cancellationToken) => throw new NotSupportedException(); + + AsyncPageable ITrackingStore.GetStateAsync(OrchestrationInstanceStatusQueryCondition condition, CancellationToken cancellationToken) => throw new NotSupportedException(); + + Task ITrackingStore.SetNewExecutionAsync(ExecutionStartedEvent executionStartedEvent, ETag? eTag, string inputPayloadOverride, CancellationToken cancellationToken) => throw new NotSupportedException(); + + Task ITrackingStore.UpdateStatusForRewindAsync(string instanceId, CancellationToken cancellationToken) => throw new NotSupportedException(); + + Task ITrackingStore.UpdateStatusForTerminationAsync(string instanceId, ExecutionTerminatedEvent executionTerminatedEvent, CancellationToken cancellationToken) => throw new NotSupportedException(); + + Task ITrackingStore.PurgeHistoryAsync(DateTime thresholdDateTimeUtc, OrchestrationStateTimeRangeFilterType timeRangeFilterType, CancellationToken cancellationToken) => throw new NotSupportedException(); + + Task ITrackingStore.PurgeInstanceHistoryAsync(string instanceId, CancellationToken cancellationToken) => throw new NotSupportedException(); + + Task ITrackingStore.PurgeInstanceHistoryAsync(DateTime createdTimeFrom, DateTime? createdTimeTo, IEnumerable runtimeStatus, CancellationToken cancellationToken) => throw new NotSupportedException(); + } + } +} diff --git a/src/DurableTask.AzureStorage/OrchestrationSessionManager.cs b/src/DurableTask.AzureStorage/OrchestrationSessionManager.cs index fafd0e4d..135d0d34 100644 --- a/src/DurableTask.AzureStorage/OrchestrationSessionManager.cs +++ b/src/DurableTask.AzureStorage/OrchestrationSessionManager.cs @@ -61,6 +61,9 @@ public OrchestrationSessionManager( internal IEnumerable Queues => this.ownedControlQueues.Values; + // The time to wait before a failed orchestration state prefetch is tried again. Tests can set a shorter time. + internal TimeSpan PrefetchRetryDelay { get; set; } = TimeSpan.FromSeconds(5); + public void AddQueue(string partitionId, ControlQueue controlQueue, CancellationToken cancellationToken) { this.shutdownToken = cancellationToken; @@ -575,11 +578,15 @@ async Task ScheduleOrchestrationStatePrefetch( e.ToString()); // Sleep briefly to avoid a tight failure loop. - await Task.Delay(TimeSpan.FromSeconds(5)); + // If the token is cancelled during the delay (shutdown), this background task stops here. + await Task.Delay(this.PrefetchRetryDelay, cancellationToken); // This is a background operation so failure is not an option. All exceptions must be handled. // To avoid starvation, we need to re-enqueue this async operation instead of retrying in a loop. - await Task.Run(() => this.ScheduleOrchestrationStatePrefetch(node, traceActivityId, cancellationToken)); + // Do not await the new operation. This method keeps the caught exception until the method completes. + // If it waits for the next attempt, each failed attempt stays in memory until an attempt is successful. + // If the failure is permanent, memory then increases without a limit. + _ = Task.Run(() => this.ScheduleOrchestrationStatePrefetch(node, traceActivityId, cancellationToken)); } } From 2cc6569410646c3fb69252aff6b2ecaa969b39aa Mon Sep 17 00:00:00 2001 From: Saurav Gupta Date: Fri, 16 Oct 2026 10:17:37 +0530 Subject: [PATCH 2/3] Move OrchestrationStatePrefetchTests to the test directory The test project is in test/DurableTask.AzureStorage.Tests (lowercase). On a case-sensitive file system, a file in Test/ (uppercase) is not part of the project, so the tests do not compile. --- .../OrchestrationStatePrefetchTests.cs | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Test => test}/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs (100%) diff --git a/Test/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs b/test/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs similarity index 100% rename from Test/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs rename to test/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs From 11d6b9b87821cd58539674856319c1cb7d2c97a9 Mon Sep 17 00:00:00 2001 From: Saurav Gupta Date: Tue, 20 Oct 2026 04:51:16 +0530 Subject: [PATCH 3/3] Load the instance ETag again when a prefetch retry finds the history loaded The instance ETag load was inside the history check of the prefetch. If the history loaded but the instance ETag load failed, the retry skipped the instance ETag load, and the batch continued without an instance ETag. With UseInstanceTableEtag, the checkpoint then used InsertEntityAsync for an instance row that already exists. That failed with 409 (SplitBrainDetected) and aborted the work item. Move the instance ETag load out of the history check. A retry now loads the instance ETag again if it is still missing, and it does not load the history again. The test asserts exactly two instance ETag loads and checks that the session has the ETag from the retry. --- .../OrchestrationSessionManager.cs | 22 ++++++++++--------- .../OrchestrationStatePrefetchTests.cs | 9 +++++--- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/DurableTask.AzureStorage/OrchestrationSessionManager.cs b/src/DurableTask.AzureStorage/OrchestrationSessionManager.cs index 135d0d34..9f010535 100644 --- a/src/DurableTask.AzureStorage/OrchestrationSessionManager.cs +++ b/src/DurableTask.AzureStorage/OrchestrationSessionManager.cs @@ -541,17 +541,19 @@ async Task ScheduleOrchestrationStatePrefetch( batch.ETags.HistoryETag = history.ETag; batch.LastCheckpointTime = history.LastCheckpointTime; batch.TrackingStoreContext = history.TrackingStoreContext; + } - // Try to get the instance ETag from the tracking store if it wasn't already provided - if (this.settings.UseInstanceTableEtag && batch.ETags.InstanceETag == null) - { - InstanceStatus? instanceStatus = await this.trackingStore.FetchInstanceStatusAsync( - batch.OrchestrationInstanceId, - cancellationToken); - // The instance could not exist in the case that these messages are for the first execution of a suborchestration, - // or an entity-started orchestration, for example - batch.ETags.InstanceETag = instanceStatus?.ETag; - } + // Try to get the instance ETag from the tracking store if it wasn't already provided. + // This is not in the history check above, so that a retry loads the instance ETag again + // when an earlier attempt loaded the history but failed to load the instance ETag. + if (this.settings.UseInstanceTableEtag && batch.ETags.InstanceETag == null) + { + InstanceStatus? instanceStatus = await this.trackingStore.FetchInstanceStatusAsync( + batch.OrchestrationInstanceId, + cancellationToken); + // The instance could not exist in the case that these messages are for the first execution of a suborchestration, + // or an entity-started orchestration, for example + batch.ETags.InstanceETag = instanceStatus?.ETag; } if (this.settings.UseSeparateQueueForEntityWorkItems diff --git a/test/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs b/test/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs index 87e610ef..dbe582b8 100644 --- a/test/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs +++ b/test/DurableTask.AzureStorage.Tests/OrchestrationStatePrefetchTests.cs @@ -221,7 +221,8 @@ public async Task PrefetchRetry_TokenAlreadyCancelled_StopsAfterFirstFailure() } /// - /// When the history is already loaded and a later step fails, the retry must not load the history again. + /// When the history is loaded but the instance ETag load fails, the retry loads the instance ETag again. + /// The retry must not load the history again. /// [TestMethod] public async Task PrefetchRetry_HistoryAlreadyLoaded_DoesNotLoadHistoryAgain() @@ -229,12 +230,13 @@ public async Task PrefetchRetry_HistoryAlreadyLoaded_DoesNotLoadHistoryAgain() // The instance ETag is loaded after the history. Make the first instance ETag load fail. this.settings.UseInstanceTableEtag = true; OrchestrationHistory history = CreateHistory(); + var instanceETag = new ETag("instance-etag"); var trackingStore = new FakeTrackingStore { OnGetHistory = attempt => Task.FromResult(history), OnFetchInstanceStatus = attempt => attempt == 1 ? throw new SimulatedStorageException(attempt) - : Task.FromResult(null), + : Task.FromResult(new InstanceStatus(new OrchestrationState(), instanceETag)), }; using var manager = this.CreateManager(trackingStore); @@ -247,7 +249,8 @@ public async Task PrefetchRetry_HistoryAlreadyLoaded_DoesNotLoadHistoryAgain() } Assert.IsNotNull(session); - Assert.IsTrue(trackingStore.InstanceStatusCalls >= 1, "The instance ETag load did not run."); + Assert.AreEqual(2, trackingStore.InstanceStatusCalls, "The instance ETag load did not run."); + Assert.AreEqual(instanceETag, session.ETags.InstanceETag, "The session does not have the instance ETag from the retry."); Assert.AreEqual(1, trackingStore.HistoryCalls, "The retry loaded the history again."); Assert.AreSame(history.Events[0], session.RuntimeState.ExecutionStartedEvent); }