Skip to content

Commit bdf5b45

Browse files
authored
Add samples and docs for orchestration versioning (#60)
* Add versioning samples/docs * Add sub-orchestration documentation * Lint fix * Phrasing * Messaging around links to Functions docs * Add settings guide and examples
1 parent 7098172 commit bdf5b45

File tree

4 files changed

+167
-6
lines changed

4 files changed

+167
-6
lines changed

docs/features.md

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,37 @@ The following features are currently supported:
44

55
### Orchestrations
66

7-
Orchestrations are implemented using ordinary Python functions that take an `OrchestrationContext` as their first parameter. The `OrchestrationContext` provides APIs for starting child orchestrations, scheduling activities, and waiting for external events, among other things. Orchestrations are fault-tolerant and durable, meaning that they can automatically recover from failures and rebuild their local execution state. Orchestrator functions must be deterministic, meaning that they must always produce the same output given the same input.
7+
Orchestrators are implemented using ordinary Python functions that take an `OrchestrationContext` as their first parameter. The `OrchestrationContext` provides APIs for starting child orchestrations, scheduling activities, and waiting for external events, among other things. Orchestrations are fault-tolerant and durable, meaning that they can automatically recover from failures and rebuild their local execution state. Orchestrator functions must be deterministic, meaning that they must always produce the same output given the same input.
8+
9+
#### Orchestration versioning
10+
11+
Orchestrations may be assigned a version when they are first created. If an orchestration is given a version, it will continually be checked during its lifecycle to ensure that it remains compatible with the underlying orchestrator code. If the orchestrator code is updated while an orchestration is running, rules can be set that will define the behavior - whether the orchestration should fail, abandon for reprocessing at a later time, or attempt to run anyway. For more information, see [The provided examples](./supported-patterns.md). For more information about versioning in the context of Durable Functions, see [Orchestration versioning in Durable Functions](https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-orchestration-versioning) (Note that concepts specific to Azure Functions, such as host.json settings, do not apply to this SDK).
12+
13+
##### Orchestration versioning options
14+
15+
Both the Durable worker and durable client have versioning configuration available. Because versioning checks are handled by the worker, the only information the client needs is a default_version, taken in its constructor, to use as the version for new orchestrations unless otherwise specified. The worker takes a VersioningOptions object with a `default_version` for new sub-orchestrations, a `version` used by the worker for orchestration version comparisons, and two more options giving control over versioning behavior in case of match failures, a `VersionMatchStrategy` and `VersionFailureStrategy`.
16+
17+
**VersionMatchStrategy**
18+
19+
| VersionMatchStrategy.NONE | VersionMatchStrategy.STRICT | VersionMatchStrategy.CURRENT_OR_OLDER |
20+
|-|-|-|
21+
| Do not compare orchestration versions | Only allow orchestrations with the same version as the worker | Allow orchestrations with the same or older version as the worker |
22+
23+
**VersionFailureStrategy**
24+
25+
| VersionFailureStrategy.REJECT | VersionFailureStrategy.FAIL |
26+
|-|-|
27+
| Abandon execution of the orchestrator, but allow it to be reprocessed later | Fail the orchestration |
28+
29+
**Strategy examples**
30+
31+
Scenario 1: You are implementing versioning for the first time in your worker. You want to have a default version for new orchestrations, but do not care about comparing versions with currently running ones. Choose VersionMatchStrategy.NONE, and VersionFailureStrategy does not matter.
32+
33+
Scenario 2: You are updating an orchestrator's code, and you do not want old orchestrations to continue to be processed on the new code. Bump the default version and the worker version, set VersionMatchStrategy.STRICT and VersionFailureStrategy.FAIL.
34+
35+
Scenario 3: You are updating an orchestrator's code, and you have ensured the code is version-aware so that it remains backward-compatible with existing orchestrations. Bump the default version and the worker version, and set VersionMatchStrategy.CURRENT_OR_OLDER and VersionFailureStrategy.FAIL.
36+
37+
Scenario 4: You are performing a high-availability deployment, and your orchestrator code contains breaking changes making it not backward-compatible. Bump the default version and the worker version, and set VersionFailureStrategy.REJECT and VersionMatchStrategy.STRICT. Ensure that at least a few of the previous version of workers remain available to continue processing the older orchestrations - eventually, all older orchestrations _should_ land on the correct workers for processing. Once all remaining old orchestrations have been processed, shut down the remaining old workers.
838

939
### Activities
1040

@@ -16,7 +46,7 @@ Orchestrations can schedule durable timers using the `create_timer` API. These t
1646

1747
### Sub-orchestrations
1848

19-
Orchestrations can start child orchestrations using the `call_sub_orchestrator` API. Child orchestrations are useful for encapsulating complex logic and for breaking up large orchestrations into smaller, more manageable pieces.
49+
Orchestrations can start child orchestrations using the `call_sub_orchestrator` API. Child orchestrations are useful for encapsulating complex logic and for breaking up large orchestrations into smaller, more manageable pieces. Sub-orchestrations can also be versioned in a similar manner to their parent orchestrations, however, they do not inherit the parent orchestrator's version. Instead, they will use the default_version defined in the current worker's VersioningOptions unless otherwise specified during `call_sub_orchestrator`.
2050

2151
### External events
2252

docs/supported-patterns.md

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def sequence(ctx: task.OrchestrationContext, _):
2020
return [result1, result2, result3]
2121
```
2222

23-
You can find the full sample [here](../examples/activity_sequence.py).
23+
See the full [function chaining example](../examples/activity_sequence.py).
2424

2525
### Fan-out/fan-in
2626

@@ -48,7 +48,7 @@ def orchestrator(ctx: task.OrchestrationContext, _):
4848
return {'work_items': work_items, 'results': results, 'total': sum(results)}
4949
```
5050

51-
You can find the full sample [here](../examples/fanout_fanin.py).
51+
See the full [fan-out sample](../examples/fanout_fanin.py).
5252

5353
### Human interaction and durable timers
5454

@@ -79,4 +79,43 @@ def purchase_order_workflow(ctx: task.OrchestrationContext, order: Order):
7979

8080
As an aside, you'll also notice that the example orchestration above works with custom business objects. Support for custom business objects includes support for custom classes, custom data classes, and named tuples. Serialization and deserialization of these objects is handled automatically by the SDK.
8181

82-
You can find the full sample [here](../examples/human_interaction.py).
82+
See the full [human interaction sample](../examples/human_interaction.py).
83+
84+
### Version-aware orchestrator
85+
86+
When utilizing orchestration versioning, it is possible for an orchestrator to remain backwards-compatible with orchestrations created using the previously defined version. For instance, consider an orchestration defined with the following signature:
87+
88+
```python
89+
def my_orchestrator(ctx: task.OrchestrationContext, order: Order):
90+
"""Dummy orchestrator function illustrating old logic"""
91+
yield ctx.call_activity(activity_one)
92+
yield ctx.call_activity(activity_two)
93+
return "Success"
94+
```
95+
96+
Assume that any orchestrations created using this orchestrator were versioned 1.0.0. If the signature of this method needs to be updated to call activity_three between the calls to activity_one and activity_two, ordinarily this would break any running orchestrations at the time of deployment. However, the following orchestrator will be able to process both orchestraions versioned 1.0.0 and 2.0.0 after the change:
97+
98+
```python
99+
def my_orchestrator(ctx: task.OrchestrationContext, order: Order):
100+
"""Version-aware dummy orchestrator capable of processing both old and new orchestrations"""
101+
yield ctx.call_activity(activity_one)
102+
if ctx.version > '1.0.0':
103+
yield ctx.call_activity(activity_three)
104+
yield ctx.call_activity(activity_two)
105+
```
106+
107+
Alternatively, if the orchestrator changes completely, the following syntax might be preferred:
108+
109+
```python
110+
def my_orchestrator(ctx: task.OrchestrationContext, order: Order):
111+
if ctx.version == '1.0.0':
112+
yield ctx.call_activity(activity_one)
113+
yield ctx.call_activity(activity_two)
114+
return "Success
115+
yield ctx.call_activity(activity_one)
116+
yield ctx.call_activity(activity_three)
117+
yield ctx.call_activity(activity_two)
118+
return "Success"
119+
```
120+
121+
See the full [version-aware orchestrator sample](../examples/version_aware_orchestrator.py)

durabletask/worker.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def __init__(self, version: Optional[str] = None,
111111
112112
Args:
113113
version: The version of orchestrations that the worker can work on.
114-
default_version: The default version that will be used for starting new orchestrations.
114+
default_version: The default version that will be used for starting new sub-orchestrations.
115115
match_strategy: The versioning strategy for the Durable Task worker.
116116
failure_strategy: The versioning failure strategy for the Durable Task worker.
117117
"""
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
"""End-to-end sample that demonstrates how to configure an orchestrator
2+
that a dynamic number activity functions in parallel, waits for them all
3+
to complete, and prints an aggregate summary of the outputs."""
4+
import os
5+
6+
from azure.identity import DefaultAzureCredential
7+
8+
from durabletask import client, task, worker
9+
from durabletask.azuremanaged.client import DurableTaskSchedulerClient
10+
from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker
11+
12+
13+
def activity_v1(ctx: task.ActivityContext, input: str) -> str:
14+
"""Activity function that returns a result for a given work item"""
15+
print("processing input:", input)
16+
return "Success from activity v1"
17+
18+
19+
def activity_v2(ctx: task.ActivityContext, input: str) -> str:
20+
"""Activity function that returns a result for a given work item"""
21+
print("processing input:", input)
22+
return "Success from activity v2"
23+
24+
25+
def orchestrator(ctx: task.OrchestrationContext, _):
26+
"""Orchestrator function that checks the orchestration version and has version-aware behavior
27+
Use case: Updating an orchestrator with new logic while maintaining compatibility with previously
28+
started orchestrations"""
29+
if ctx.version == "1.0.0":
30+
# For version 1.0.0, we use the original logic
31+
result: int = yield ctx.call_activity(activity_v1, input="input for v1")
32+
elif ctx.version == "2.0.0":
33+
# For version 2.0.0, we use the updated logic
34+
result: int = yield ctx.call_activity(activity_v2, input="input for v2")
35+
else:
36+
raise ValueError(f"Unsupported version: {ctx.version}")
37+
return {
38+
'result': result,
39+
}
40+
41+
42+
# Use environment variables if provided, otherwise use default emulator values
43+
taskhub_name = os.getenv("TASKHUB", "default")
44+
endpoint = os.getenv("ENDPOINT", "http://localhost:8080")
45+
46+
print(f"Using taskhub: {taskhub_name}")
47+
print(f"Using endpoint: {endpoint}")
48+
49+
# Set credential to None for emulator, or DefaultAzureCredential for Azure
50+
credential = None if endpoint == "http://localhost:8080" else DefaultAzureCredential()
51+
52+
# configure and start the worker - use secure_channel=False for emulator
53+
secure_channel = endpoint != "http://localhost:8080"
54+
with DurableTaskSchedulerWorker(host_address=endpoint, secure_channel=secure_channel,
55+
taskhub=taskhub_name, token_credential=credential) as w:
56+
# This worker is versioned for v2, as the orchestrator code has already been updated
57+
# CURRENT_OR_OLDER allows this worker to process orchestrations versioned below 2.0.0 - e.g. 1.0.0
58+
w.use_versioning(worker.VersioningOptions(
59+
version="2.0.0",
60+
default_version="2.0.0",
61+
match_strategy=worker.VersionMatchStrategy.CURRENT_OR_OLDER,
62+
failure_strategy=worker.VersionFailureStrategy.FAIL
63+
))
64+
w.add_orchestrator(orchestrator)
65+
w.add_activity(activity_v1)
66+
w.add_activity(activity_v2)
67+
w.start()
68+
69+
# create a client, start an orchestration, and wait for it to finish
70+
# The client's version matches the worker's version
71+
c = DurableTaskSchedulerClient(host_address=endpoint, secure_channel=secure_channel,
72+
taskhub=taskhub_name, token_credential=credential,
73+
default_version="2.0.0")
74+
# Schedule a new orchestration manually versioned to 1.0.0
75+
# Normally, this would have been scheduled before the worker started from a worker also versioned v1.0.0,
76+
# Here we are doing it manually to avoid creating two workers
77+
instance_id_v1 = c.schedule_new_orchestration(orchestrator, version="1.0.0")
78+
state_v1 = c.wait_for_orchestration_completion(instance_id_v1, timeout=30)
79+
if state_v1 and state_v1.runtime_status == client.OrchestrationStatus.COMPLETED:
80+
print(f'Orchestration v1 completed! Result: {state_v1.serialized_output}')
81+
elif state_v1:
82+
print(f'Orchestration v1 failed: {state_v1.failure_details}')
83+
84+
# Also check that the orchestrator can be run with the current version
85+
instance_id = c.schedule_new_orchestration(orchestrator)
86+
state = c.wait_for_orchestration_completion(instance_id, timeout=30)
87+
if state and state.runtime_status == client.OrchestrationStatus.COMPLETED:
88+
print(f'Orchestration completed! Result: {state.serialized_output}')
89+
elif state:
90+
print(f'Orchestration failed: {state.failure_details}')
91+
92+
exit()

0 commit comments

Comments
 (0)