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
10 changes: 10 additions & 0 deletions docs/providers/azure-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,16 @@ Checkpoints are written in this order to ensure that no data is lost if there is

Because the checkpoints aren't atomic, duplicates may occur. The replay model handles history duplicates gracefully. Message duplicates may result in activities being executed multiple times if an unexpected failure occurs.

### Entity-Started Orchestrations

With the default Azure Table tracking store, orchestrations started by entities are registered as `Pending`, including their scheduled start time, input, tags, and parent entity ID. They can be queried and terminated before their start messages become visible. Once a Pending termination has been processed, the matching delayed start is discarded without running orchestration code.

The start message is enqueued before its Pending row is registered, and registration completes before the sending entity's history checkpoint. Workers defer registered start messages while registration is in flight. Conditional inserts and ETag-checked replacements prevent a late registration from overwriting an execution that has already started or a newer execution. Retried prepared starts do not reset terminal instances or recreate purged rows. Reusing an instance ID after a terminal execution creates a new generation.

When an instance ID is reused, the previous execution's terminal history can remain while the new execution is Pending. An execution-independent termination is reconciled against the current Pending row with its ETag before the old terminal-history batch is discarded. A termination explicitly targeting the old execution does not cancel the newer Pending execution. The conditional update preserves execution identity, generation, input, and prior history; conflicting writes and storage failures are retried through the normal worker lifecycle rather than overwriting a replacement or recreating a deleted row.

Upgrade all workers sharing a task hub to obtain these guarantees. Older workers do not reconcile entity-generated starts with Pending registrations, and entity start messages produced by older workers without a generation retain their legacy behavior. This does not change the provider's at-least-once delivery model or make entity actions transactional with child execution.

## Scaling

### Horizontal Scaling
Expand Down
122 changes: 115 additions & 7 deletions src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1086,7 +1086,44 @@ async Task<string> IsExecutableInstanceAsync(
bool allowReplayingTerminalInstances,
CancellationToken cancellationToken)
{
if (runtimeState.ExecutionStartedEvent == null && !newMessages.Any(msg => msg.Event is ExecutionStartedEvent))
ExecutionStartedEvent startEvent = null;
ExecutionTerminatedEvent terminationEvent = null;
ExecutionTerminatedEvent independentTermination = null;
foreach (TaskMessage message in newMessages)
{
if (message.Event is ExecutionStartedEvent started)
{
startEvent ??= started;
}
else if (message.Event is ExecutionTerminatedEvent terminated)
{
terminationEvent = terminated;
if (message.OrchestrationInstance.ExecutionId == null)
{
independentTermination = terminated;
}
}
}

if (runtimeState.ExecutionStartedEvent == null &&
startEvent != null &&
startEvent.Generation.HasValue &&
startEvent.ParentInstance?.OrchestrationInstance?.InstanceId is string parentInstanceId &&
DurableTask.Core.Common.Entities.IsEntityInstance(parentInstanceId))
{
// Reconciliation can precede a Pending termination while this start waits for its session.
InstanceStatus status = await this.trackingStore.FetchInstanceStatusAsync(
startEvent.OrchestrationInstance.InstanceId,
cancellationToken);
if (status != null &&
status.State.OrchestrationStatus == OrchestrationStatus.Terminated &&
string.Equals(status.State.OrchestrationInstance.ExecutionId, startEvent.OrchestrationInstance.ExecutionId, StringComparison.OrdinalIgnoreCase))
{
return $"Instance is {OrchestrationStatus.Terminated}";
}
}

if (runtimeState.ExecutionStartedEvent == null && startEvent == null)
{
var instanceId = newMessages[0].OrchestrationInstance.InstanceId;

Expand All @@ -1096,13 +1133,12 @@ async Task<string> IsExecutableInstanceAsync(
}
else
{
TaskMessage executionTerminatedEventMessage = newMessages.LastOrDefault(msg => msg.Event is ExecutionTerminatedEvent);
if (executionTerminatedEventMessage is not null)
if (terminationEvent != null)
{
var executionTerminatedEvent = (ExecutionTerminatedEvent)executionTerminatedEventMessage.Event;
await this.trackingStore.UpdateStatusForTerminationAsync(
instanceId,
executionTerminatedEvent);
terminationEvent,
cancellationToken);
return $"Instance is {OrchestrationStatus.Terminated}";
}

Expand All @@ -1122,7 +1158,24 @@ await this.trackingStore.UpdateStatusForTerminationAsync(
runtimeState.OrchestrationStatus != OrchestrationStatus.Pending &&
runtimeState.OrchestrationStatus != OrchestrationStatus.Suspended)
{
InstanceStatus instanceStatus = await this.trackingStore.FetchInstanceStatusAsync(runtimeState.OrchestrationInstance.InstanceId);
InstanceStatus instanceStatus = await this.trackingStore.FetchInstanceStatusAsync(
runtimeState.OrchestrationInstance.InstanceId,
cancellationToken);
if (instanceStatus != null &&
instanceStatus.State.OrchestrationStatus == OrchestrationStatus.Pending &&
!string.Equals(instanceStatus.State.OrchestrationInstance.ExecutionId, runtimeState.OrchestrationInstance.ExecutionId, StringComparison.OrdinalIgnoreCase) &&
independentTermination != null &&
this.trackingStore is AzureTableTrackingStore tableTrackingStore)
{
// ID reuse can leave old terminal history while the latest execution is still Pending.
await tableTrackingStore.UpdateStatusForTerminationAsync(
runtimeState.OrchestrationInstance.InstanceId,
independentTermination,
instanceStatus.ETag,
cancellationToken);
return $"Instance is {OrchestrationStatus.Terminated}";
}

if (instanceStatus == null || (instanceStatus.State.OrchestrationInstance.ExecutionId == runtimeState.OrchestrationInstance.ExecutionId
&& instanceStatus.State.OrchestrationStatus != runtimeState.OrchestrationStatus))
{
Expand Down Expand Up @@ -1453,9 +1506,64 @@ async Task CommitOutboundQueueMessages(
}
}

// Custom instance stores need not support conditional Pending registration or start reconciliation.
await enqueueOperations.ParallelForEachAsync(
this.settings.MaxStorageOperationConcurrency,
op => op.Queue.AddMessageAsync(op.Message, session));
op => this.trackingStore is AzureTableTrackingStore &&
op.Message.Event is ExecutionStartedEvent &&
DurableTask.Core.Common.Entities.IsEntityInstance(session.Instance.InstanceId)
? this.SendEntityOrchestrationStartAsync(op.Queue, op.Message, session)
: op.Queue.AddMessageAsync(op.Message, session));
}

internal async Task SendEntityOrchestrationStartAsync(
TaskHubQueue queue,
TaskMessage message,
OrchestrationSession session)
{
var startEvent = (ExecutionStartedEvent)message.Event;
// Retrying a prepared message must not reset a progressed or purged instance.
bool registerPending = !startEvent.Generation.HasValue;
InstanceStatus existingInstance = null;
if (registerPending)
{
existingInstance = await this.trackingStore.FetchInstanceStatusAsync(message.OrchestrationInstance.InstanceId);
if (existingInstance != null &&
(string.Equals(existingInstance.State.OrchestrationInstance.ExecutionId, message.OrchestrationInstance.ExecutionId, StringComparison.OrdinalIgnoreCase) ||
existingInstance.State.OrchestrationStatus is OrchestrationStatus.Pending or OrchestrationStatus.Running or OrchestrationStatus.Suspended or OrchestrationStatus.ContinuedAsNew))
{
startEvent.Generation = existingInstance.State.Generation ?? 0;
registerPending = false;
}
else
{
startEvent.Generation = (existingInstance?.State.Generation ?? -1) + 1;
}
}

// As with client starts, enqueue before registering Pending and before checkpointing the sender.
MessageData queuedMessage = await queue.AddMessageAsync(message, session);
if (registerPending)
{
string inputPayloadOverride = queuedMessage.CompressedBlobName == null
? null
: this.messageManager.GetBlobUrl(queuedMessage.CompressedBlobName);
try
{
await this.trackingStore.SetNewExecutionAsync(startEvent, existingInstance?.ETag, inputPayloadOverride);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed against unchanged head a5435df6 using a real entity/worker plus owned local Azurite, in both instance-table ETag modes. A repeated termination changed only the same old historyless Terminated row's ETag. The source entity checkpointed/acked once, but its new start carried generation 8 while the stored row stayed at the old execution/generation 7. Driving the actual queued message through the unchanged reconciler produced real deliveries 2–10; it was deleted at 10 and child dispatches stayed zero. Only that owned message's visibility delays were shortened to bound the experiment; counts and production reconciliation were not fabricated.

This is a blocking start-loss regression. A false registration result cannot be treated as success merely because a different checkpoint or execution might have won: this case leaves the same prior terminal execution current. The minimum correction should refetch/conditionally reconcile that outcome or fail before the source checkpoint so the existing entity replay can recover. No new retry framework is needed. This review made no production-code changes, and this thread intentionally remains unresolved.

}
catch (DurableTaskStorageException e) when (
existingInstance != null &&
e.HttpStatusCode == (int)HttpStatusCode.NotFound &&
e.ErrorCode == "ResourceNotFound")
{
this.settings.Logger.GeneralWarning(
this.azureStorageClient.TableAccountName,
this.settings.TaskHubName,
"Skipped Pending registration because the previous instance was purged after its status was read.",
instanceId: message.OrchestrationInstance.InstanceId);
}
}
}

async Task DeleteMessageBatchAsync(OrchestrationSession session, IList<MessageData> messagesToDelete)
Expand Down
4 changes: 2 additions & 2 deletions src/DurableTask.AzureStorage/Messaging/TaskHubQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ public TaskHubQueue(
/// </summary>
/// <param name="message">Instance of <see cref="TaskMessage"/></param>
/// <param name="sourceSession">Instance of <see cref="SessionBase"/></param>
/// <returns></returns>
public Task AddMessageAsync(TaskMessage message, SessionBase sourceSession)
/// <returns>The queued message, including any large-message blob reference.</returns>
public Task<MessageData> AddMessageAsync(TaskMessage message, SessionBase sourceSession)
{
return this.AddMessageAsync(message, sourceSession.Instance, sourceSession);
}
Expand Down
20 changes: 14 additions & 6 deletions src/DurableTask.AzureStorage/OrchestrationSessionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -252,10 +252,12 @@ async Task<IEnumerable<MessageData>> DedupeExecutionStartedMessagesAsync(

foreach (MessageData message in messages)
{
// We do de-duplication when creating top-level orchestrations but not for sub-orchestrations.
// De-dupe protection for sub-orchestrations is not implemented and will require a bit more work.
// Registered entity starts use the same Pending-row reconciliation as client starts.
// Awaited sub-orchestrations and older entity starts do not have Pending registration.
if (message.TaskMessage.Event is ExecutionStartedEvent startEvent &&
startEvent.ParentInstance == null)
(startEvent.ParentInstance == null ||
(startEvent.Generation.HasValue &&
DurableTask.Core.Common.Entities.IsEntityInstance(startEvent.ParentInstance.OrchestrationInstance.InstanceId))))
{
executionStartedMessages ??= new List<MessageData>(messages.Count);
executionStartedMessages.Add(message);
Expand Down Expand Up @@ -289,9 +291,15 @@ async Task<IEnumerable<MessageData>> DedupeExecutionStartedMessagesAsync(
if (remoteOrchestrationsById.TryGetValue(localInstance.InstanceId, out InstanceStatus remoteInstance) &&
(remoteInstance.State.OrchestrationInstance.ExecutionId == null || string.Equals(localInstance.ExecutionId, remoteInstance.State.OrchestrationInstance.ExecutionId, StringComparison.OrdinalIgnoreCase)))
{
// Happy path: The message matches the table status. Alternatively, if the table doesn't have an ExecutionId field (older clients, pre-v1.8.5),
// then we have no way of knowing if it's a duplicate. Either way, allow it to run.
if (this.settings.UseInstanceTableEtag)
if (remoteInstance.State.OrchestrationStatus == OrchestrationStatus.Terminated &&
remoteInstance.State.OrchestrationInstance.ExecutionId != null)
{
// Pending termination has no history event. Reject its delayed start using the same status read.
messagesToDiscard ??= new List<MessageData>(executionStartedMessages.Count);
messagesToDiscard.Add(message);
}
// A missing execution ID is a legacy record that cannot be safely deduplicated.
else if (this.settings.UseInstanceTableEtag)
{
message.MessageMetadata = remoteInstance.ETag;
}
Expand Down
20 changes: 18 additions & 2 deletions src/DurableTask.AzureStorage/Tracking/AzureTableTrackingStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,13 @@ public override async Task<bool> SetNewExecutionAsync(
// It is possible that the queue message was small enough to be written directly to a queue message,
// not a blob, but is too large to be written to a table property.
await this.CompressLargeMessageAsync(entity, listOfBlobs: null, cancellationToken: cancellationToken);
// Pending rows expose large inputs as URLs, just like checkpointed instance rows.
this.SetInstancesTablePropertyFromHistoryProperty(
entity,
entity,
historyPropertyName: InputProperty,
instancePropertyName: InputProperty,
data: inputPayloadOverride ?? executionStartedEvent.Input);

Stopwatch stopwatch = Stopwatch.StartNew();
try
Expand Down Expand Up @@ -881,10 +888,19 @@ public override async Task UpdateStatusForRewindAsync(string instanceId, Cancell
}

/// <inheritdoc />
public override async Task UpdateStatusForTerminationAsync(
public override Task UpdateStatusForTerminationAsync(
string instanceId,
ExecutionTerminatedEvent executionTerminatedEvent,
CancellationToken cancellationToken = default)
{
return this.UpdateStatusForTerminationAsync(instanceId, executionTerminatedEvent, ETag.All, cancellationToken);
}

internal async Task UpdateStatusForTerminationAsync(
string instanceId,
ExecutionTerminatedEvent executionTerminatedEvent,
ETag ifMatch,
CancellationToken cancellationToken = default)
{
string sanitizedInstanceId = KeySanitation.EscapePartitionKey(instanceId);
TableEntity instanceEntity = new TableEntity(sanitizedInstanceId, "")
Expand All @@ -901,7 +917,7 @@ public override async Task UpdateStatusForTerminationAsync(
await this.CompressLargeMessageAsync(instanceEntity, listOfBlobs: null, cancellationToken: cancellationToken, addBlobPropertyName: false);

Stopwatch stopwatch = Stopwatch.StartNew();
await this.InstancesTable.MergeEntityAsync(instanceEntity, ETag.All, cancellationToken);
await this.InstancesTable.MergeEntityAsync(instanceEntity, ifMatch, cancellationToken);

this.settings.Logger.InstanceStatusUpdate(
this.storageAccountName,
Expand Down
4 changes: 2 additions & 2 deletions src/DurableTask.AzureStorage/Tracking/ITrackingStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,10 @@ interface ITrackingStore
AsyncPageable<OrchestrationState> GetStateAsync(OrchestrationInstanceStatusQueryCondition condition, CancellationToken cancellationToken = default);

/// <summary>
/// Used to set a state in the tracking store whenever a new execution is initiated from the client
/// Used to set a Pending state whenever a new execution is initiated by a client or entity.
/// </summary>
/// <param name="executionStartedEvent">The Execution Started Event being queued</param>
/// <param name="eTag">The eTag value to use for optimistic concurrency or <c>null</c> to overwrite any existing execution status.</param>
/// <param name="eTag">The eTag read before enqueueing the start, or <c>null</c> for a new instance.</param>
/// <param name="inputPayloadOverride">An override value to use for the Input column. If not specified, uses <see cref="ExecutionStartedEvent.Input"/>.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>Returns <c>true</c> if the record was created successfully; <c>false</c> otherwise.</returns>
Expand Down
Loading
Loading