Skip to content

Commit 150c6f6

Browse files
authored
Merge pull request #165: Correct duplicate-start contract for Python 2.6.1
Correct duplicate-start contract and publish Python 2.6.1
2 parents 0ed44b8 + e1eb1d9 commit 150c6f6

7 files changed

Lines changed: 196 additions & 20 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1414
`deprecate_patch` for the same change ID, while validating each call's range
1515
and preserving retained duplicate-marker sequences.
1616

17+
## [2.6.1] - 2026-10-19
18+
19+
### Fixed
20+
21+
- Raise `WorkflowAlreadyStarted` for the current Server's
22+
`instance_already_started` duplicate-start reason, retaining support for the
23+
historical `duplicate_not_allowed` reason.
24+
- Correct start-policy documentation to `fail` and `use-existing`, including
25+
active versus closed instances and preservation of original input/deadlines.
26+
Start admission and workflow lifecycle behavior are unchanged.
27+
1728
## [2.6.0] - 2026-10-18
1829

1930
### Added

‎docs/sdk-reference.md‎

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -84,14 +84,42 @@ own `/api` routes. For example, use `http://server:8080`, not
8484
`http://server:8080/api`. Managed-runtime paths such as
8585
`https://cloud.example/api/runtime/v1/namespaces/acme` are valid as written.
8686

87-
A workflow ID is the durable identity of an instance, not a per-attempt request
88-
ID. Starting the same ID again with the default `reject` duplicate policy raises
89-
the typed `WorkflowAlreadyStarted` exception. Generate a unique ID for each new
90-
instance, as the quickstart does. For an intentionally idempotent start, catch
91-
`WorkflowAlreadyStarted` and reconnect with
92-
`client.get_workflow_handle(workflow_id)`; choose `allow` or
93-
`terminate_existing` only when creating another run or replacing the current
94-
instance is the intended behavior.
87+
### Duplicate workflow IDs
88+
89+
A workflow ID is the durable identity of an instance. The PHP Server start
90+
contract accepts these policies:
91+
92+
| `duplicate_policy` | ID not yet used | Existing pending, running or waiting run | Closed instance |
93+
| --- | --- | --- | --- |
94+
| Omitted, `None`, or `"fail"` | Start a new instance | Raise `WorkflowAlreadyStarted` | Raise `WorkflowAlreadyStarted` |
95+
| `"use-existing"` | Start a new instance | Return a handle to the original run | Raise `WorkflowAlreadyStarted` |
96+
97+
An active duplicate keeps its original input, run and deadlines. It does not
98+
apply the new request's arguments. Duplicate requests can append start-accepted
99+
or start-rejected audit events without creating another business execution.
100+
101+
```python
102+
handle = await client.start_workflow(
103+
workflow_type="greeter",
104+
workflow_id="greet-customer-42",
105+
task_queue="python-workers",
106+
input=["world"],
107+
duplicate_policy="use-existing",
108+
)
109+
```
110+
111+
Use a unique workflow ID for each independent execution, as the quickstart does.
112+
To inspect an existing instance, including a closed one, use
113+
`client.get_workflow_handle(workflow_id)` and its describe/result methods instead
114+
of starting it again. `"use-existing"` does not restart or replace a closed run.
115+
The SDK forwards the policy unchanged. `"reject"`, `"allow"` and
116+
`"terminate_existing"` are invalid values and the PHP Server rejects them with
117+
HTTP 422 (`InvalidArgument`).
118+
119+
A resource-keyed ID can coordinate admission to one durable instance. It is not
120+
a physical global mutex: cancellation or termination cannot revoke a request
121+
already sent to an external system. Protect those effects with downstream
122+
idempotency and, where required, resource-enforced fencing.
95123

96124
For a fuller deployable example, see
97125
[`examples/order_processing`](https://github.com/durable-workflow/sdk-python/tree/main/examples/order_processing), which runs a

‎pyproject.toml‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "durable-workflow"
7-
version = "2.6.0"
7+
version = "2.6.1"
88
description = "Python client and worker SDK for Durable Workflow Cloud and self-hosted Server"
99
readme = "README.md"
1010
requires-python = ">=3.10"
@@ -71,8 +71,8 @@ durable-workflow-replay-conformance = "durable_workflow.replay_conformance:main"
7171
durable-workflow-workflow-updates-conformance = "durable_workflow.workflow_updates_conformance:main"
7272

7373
[tool.durable-workflow]
74-
product-train = "2.6.0"
75-
registry-version = "2.6.0"
74+
product-train = "2.6.1"
75+
registry-version = "2.6.1"
7676
supported-server-versions = "2.8.0"
7777
worker-protocol-version = "1.20"
7878
control-plane-version = "2"

‎src/durable_workflow/client.py‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3527,9 +3527,18 @@ async def start_workflow(
35273527
``workflow_type`` is the language-neutral type key registered via
35283528
:func:`durable_workflow.workflow.defn`. ``task_queue`` selects which
35293529
worker pool picks up the workflow. ``workflow_id`` is the
3530-
caller-supplied instance id — if it collides with an existing
3531-
workflow, behavior depends on ``duplicate_policy``
3532-
(``reject`` | ``allow`` | ``terminate_existing``).
3530+
caller-supplied instance ID. The PHP Server start contract accepts
3531+
``duplicate_policy="fail"`` (also the default when omitted) or
3532+
``"use-existing"``. ``fail`` raises :class:`WorkflowAlreadyStarted`
3533+
if the ID already exists. ``use-existing`` returns the original run
3534+
only while it is pending, running or waiting. Both policies reject
3535+
a closed instance. Neither replaces a run or changes its input or
3536+
deadlines. Use a new workflow ID for a new independent execution.
3537+
3538+
The SDK forwards the policy unchanged. ``reject``, ``allow`` and
3539+
``terminate_existing`` are not supported wire values. A resource-keyed
3540+
workflow ID coordinates start admission; it does not revoke work
3541+
already running in an external system.
35333542
35343543
``input`` is a list of positional arguments passed to the workflow's
35353544
``run`` method; the SDK encodes the list with the default payload

‎src/durable_workflow/errors.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -312,8 +312,10 @@ def __init__(self, workflow_id: str) -> None:
312312
class WorkflowAlreadyStarted(DurableWorkflowError):
313313
"""A start request collided with an existing instance id.
314314
315-
Raised when duplicate-start policy is ``reject`` (the default) and the
316-
caller-supplied ``workflow_id`` is already in use.
315+
The PHP Server raises this for an existing ``workflow_id`` when the
316+
duplicate policy is ``fail`` (the default), or when ``use-existing``
317+
addresses a closed instance. ``use-existing`` returns a handle only
318+
while the original run is pending, running or waiting.
317319
"""
318320

319321
def __init__(self, workflow_id: str) -> None:
@@ -874,7 +876,7 @@ def update_validation_failed(default: str) -> UpdateValidationFailed:
874876
if status == 409:
875877
if reason == "schedule_already_exists":
876878
raise ScheduleAlreadyExists(context)
877-
if reason == "duplicate_not_allowed":
879+
if reason in ("duplicate_not_allowed", "instance_already_started"):
878880
raise WorkflowAlreadyStarted(context)
879881
if reason == "run_not_active":
880882
if operation == "signal":
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
"""Qualify start policies against real admission, audit history and completion."""
2+
3+
from __future__ import annotations
4+
5+
import json
6+
from typing import Any
7+
from uuid import uuid4
8+
9+
import httpx
10+
import pytest
11+
12+
from durable_workflow import Client, Worker, workflow
13+
from durable_workflow.errors import InvalidArgument, WorkflowAlreadyStarted, WorkflowNotFound
14+
15+
16+
@workflow.defn(name="tests.duplicate-policy.echo")
17+
class PolicyWorkflow:
18+
def run(self, ctx: Any, value: Any) -> Any:
19+
yield from ()
20+
return value
21+
22+
23+
@pytest.mark.asyncio
24+
@pytest.mark.parametrize("initial_policy", [None, "fail", "use-existing"])
25+
async def test_duplicate_policies_preserve_active_and_completed_original(
26+
server_url: str, server_token: str, initial_policy: str | None,
27+
) -> None:
28+
suffix = uuid4().hex
29+
queue = f"policy-{suffix}"
30+
workflow_id = f"policy-{suffix}"
31+
value = {"integer": 9223372036854775807, "null": None, "text": "original 雪"}
32+
async with Client(server_url, token=server_token, namespace="default") as client:
33+
starts: list[tuple[dict[str, Any], int]] = []
34+
35+
async def observe(response: httpx.Response) -> None:
36+
request = response.request
37+
if request.method == "POST" and request.url.path.endswith("/workflows"):
38+
starts.append((json.loads(request.content), response.status_code))
39+
40+
client._http.event_hooks["response"].append(observe)
41+
42+
async def start(policy: str | None, *, original: bool = False) -> Any:
43+
return await client.start_workflow(
44+
workflow_type="tests.duplicate-policy.echo", task_queue=queue,
45+
workflow_id=workflow_id, input=[value if original else "replacement"],
46+
execution_timeout_seconds=120 if original else 600,
47+
run_timeout_seconds=60 if original else 300, duplicate_policy=policy,
48+
)
49+
50+
handle = await start(initial_policy, original=True)
51+
assert starts[-1][1] == 201
52+
assert starts[-1][0].get("duplicate_policy") == initial_policy
53+
assert ("duplicate_policy" in starts[-1][0]) is (initial_policy is not None)
54+
55+
for completed in (False, True):
56+
if completed:
57+
worker = Worker(
58+
client, task_queue=queue, workflows=[PolicyWorkflow], activities=[],
59+
poll_timeout=0.5, shutdown_timeout=10,
60+
)
61+
await worker.run_until(workflow_id=workflow_id, timeout=30, poll_interval=0.1)
62+
assert await handle.result(timeout=30) == value
63+
64+
before = await handle.describe_run()
65+
assert (before.status.lower() == "completed") is completed
66+
assert before.input is not None
67+
assert before.execution_deadline_at
68+
assert before.run_deadline_at
69+
history = (await handle.get_history())["events"]
70+
71+
for policy in (None, "fail", "use-existing"):
72+
returned = policy == "use-existing" and not completed
73+
if returned:
74+
existing = await start(policy)
75+
assert (existing.workflow_id, existing.run_id) == (handle.workflow_id, handle.run_id)
76+
else:
77+
with pytest.raises(WorkflowAlreadyStarted) as duplicate:
78+
await start(policy)
79+
assert duplicate.value.workflow_id == workflow_id
80+
request, status = starts[-1]
81+
assert request.get("duplicate_policy") == policy
82+
assert ("duplicate_policy" in request) is (policy is not None)
83+
assert status == (200 if returned else 409)
84+
after_history = (await handle.get_history())["events"]
85+
assert after_history[:len(history)] == history
86+
# Canonical duplicate starts append an admission audit event,
87+
# while retaining the original business execution.
88+
assert [event["event_type"] for event in after_history[len(history):]] == [
89+
"StartAccepted" if returned else "StartRejected",
90+
]
91+
history = after_history
92+
93+
for obsolete in ("reject", "allow", "terminate_existing"):
94+
with pytest.raises(InvalidArgument):
95+
await start(obsolete)
96+
assert starts[-1][0]["duplicate_policy"] == obsolete
97+
assert starts[-1][1] == 422
98+
assert (await handle.get_history())["events"] == history
99+
100+
after = await handle.describe_run()
101+
for field in ("run_id", "input", "status", "execution_deadline_at", "run_deadline_at", "output"):
102+
assert getattr(after, field) == getattr(before, field), field
103+
runs = await handle.list_runs()
104+
assert len(runs.runs) == 1
105+
assert runs.runs[0].run_id == handle.run_id
106+
assert sum(event["event_type"] == "WorkflowCompleted" for event in history) == int(completed)
107+
print(json.dumps({"initial_policy": initial_policy, "workflow_id": workflow_id,
108+
"run_id": handle.run_id, "start_statuses": [status for _, status in starts]}))
109+
110+
111+
@pytest.mark.asyncio
112+
@pytest.mark.parametrize("obsolete", ["reject", "allow", "terminate_existing"])
113+
async def test_invalid_policy_does_not_admit_a_fresh_workflow(
114+
server_url: str, server_token: str, obsolete: str,
115+
) -> None:
116+
workflow_id = f"invalid-policy-{uuid4().hex}"
117+
async with Client(server_url, token=server_token, namespace="default") as client:
118+
with pytest.raises(InvalidArgument):
119+
await client.start_workflow(
120+
workflow_type="tests.duplicate-policy.echo", task_queue="invalid-policy",
121+
workflow_id=workflow_id, input=[], duplicate_policy=obsolete,
122+
)
123+
with pytest.raises(WorkflowNotFound):
124+
await client.describe_workflow(workflow_id)

‎tests/test_errors.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,11 @@ def test_404_generic(self) -> None:
5757
with pytest.raises(ServerError):
5858
_raise_for_status(404, {"reason": "other"})
5959

60-
def test_409_duplicate(self) -> None:
61-
with pytest.raises(WorkflowAlreadyStarted):
62-
_raise_for_status(409, {"reason": "duplicate_not_allowed"}, context="wf-1")
60+
@pytest.mark.parametrize("reason", ["duplicate_not_allowed", "instance_already_started"])
61+
def test_409_duplicate(self, reason: str) -> None:
62+
with pytest.raises(WorkflowAlreadyStarted) as duplicate:
63+
_raise_for_status(409, {"reason": reason}, context="resource-017")
64+
assert duplicate.value.workflow_id == "resource-017"
6365

6466
def test_409_query_rejected(self) -> None:
6567
with pytest.raises(QueryFailed):

0 commit comments

Comments
 (0)