|
| 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) |
0 commit comments