|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import time |
| 5 | +from contextlib import suppress |
| 6 | +from datetime import datetime, timedelta, timezone |
| 7 | +from unittest.mock import AsyncMock |
| 8 | + |
| 9 | +import httpx |
| 10 | +import pytest |
| 11 | + |
| 12 | +from durable_workflow import activity, serializer |
| 13 | +from durable_workflow._activity_lease import ActivityLeaseAuthority, current_activity_authority |
| 14 | +from durable_workflow.activity import ActivityContext, ActivityInfo |
| 15 | +from durable_workflow.client import Client |
| 16 | +from durable_workflow.errors import ActivityLeaseAuthorityLost, NonRetryableError |
| 17 | +from durable_workflow.worker import Worker |
| 18 | + |
| 19 | +REASONS = ("activity_deadline_elapsed", "attempt_closed", "run_closed") |
| 20 | + |
| 21 | + |
| 22 | +def refusing_client(reason: str) -> AsyncMock: |
| 23 | + client = AsyncMock(spec=Client) |
| 24 | + client.heartbeat_activity_task.return_value = { |
| 25 | + "can_continue": False, "cancel_requested": False, "reason": reason, |
| 26 | + } |
| 27 | + return client |
| 28 | + |
| 29 | + |
| 30 | +@pytest.mark.asyncio |
| 31 | +@pytest.mark.parametrize("reason", REASONS) |
| 32 | +@pytest.mark.parametrize("synchronous", (False, True)) |
| 33 | +async def test_heartbeat_refusal_carries_original_reason(reason: str, synchronous: bool) -> None: |
| 34 | + ctx = ActivityContext(info=ActivityInfo( |
| 35 | + task_id="original-task", activity_type="heartbeat-refusal", activity_attempt_id="original-attempt", |
| 36 | + attempt_number=1, task_queue="original-queue", worker_id="original-worker", |
| 37 | + ), client=refusing_client(reason)) |
| 38 | + |
| 39 | + invocation = (asyncio.to_thread(ctx.heartbeat_sync, {"progress": 1}) if synchronous |
| 40 | + else ctx.heartbeat({"progress": 1})) |
| 41 | + with pytest.raises(ActivityLeaseAuthorityLost) as refusal: |
| 42 | + await invocation |
| 43 | + |
| 44 | + assert refusal.value.task_id == "original-task" |
| 45 | + assert refusal.value.reason == reason |
| 46 | + assert not ctx.is_cancelled |
| 47 | + |
| 48 | + |
| 49 | +@pytest.mark.asyncio |
| 50 | +@pytest.mark.parametrize("reason", REASONS) |
| 51 | +@pytest.mark.parametrize("synchronous", (False, True)) |
| 52 | +async def test_default_worker_does_not_publish_after_heartbeat_refusal( |
| 53 | + reason: str, synchronous: bool, |
| 54 | +) -> None: |
| 55 | + client = refusing_client(reason) |
| 56 | + continued: list[str] = [] |
| 57 | + |
| 58 | + def sync_handler() -> str: |
| 59 | + activity.context().heartbeat_sync() |
| 60 | + continued.append("after refusal") |
| 61 | + return "late result" |
| 62 | + |
| 63 | + async def async_handler() -> str: |
| 64 | + await activity.context().heartbeat() |
| 65 | + continued.append("after refusal") |
| 66 | + return "late result" |
| 67 | + |
| 68 | + handler = activity.defn(name="heartbeat-refusal")(sync_handler if synchronous else async_handler) |
| 69 | + worker = Worker(client, task_queue="original-queue", workflows=[], activities=[handler]) |
| 70 | + task = { |
| 71 | + "task_id": "original-task", "activity_attempt_id": "original-attempt", |
| 72 | + "activity_type": "heartbeat-refusal", "attempt_number": 1, |
| 73 | + "arguments": serializer.encode([], codec="avro"), "payload_codec": "avro", |
| 74 | + } |
| 75 | + |
| 76 | + assert await worker._run_activity_task(task) == "claim_aborted" |
| 77 | + assert continued == [] |
| 78 | + client.complete_activity_task.assert_not_called() |
| 79 | + client.fail_activity_task.assert_not_called() |
| 80 | + with pytest.raises(RuntimeError, match="outside of an activity"): |
| 81 | + activity.context() |
| 82 | + |
| 83 | + |
| 84 | +@pytest.mark.asyncio |
| 85 | +@pytest.mark.parametrize("same_original", (True, False)) |
| 86 | +async def test_refusal_fences_only_the_matching_original_client_authority(same_original: bool) -> None: |
| 87 | + paths: list[str] = [] |
| 88 | + |
| 89 | + async def respond(request: httpx.Request) -> httpx.Response: |
| 90 | + paths.append(request.url.path) |
| 91 | + assert request.url.path.endswith("/heartbeat") |
| 92 | + return httpx.Response(200, json={ |
| 93 | + "heartbeat_recorded": False, "can_continue": False, |
| 94 | + "cancel_requested": False, "reason": "attempt_closed", |
| 95 | + }) |
| 96 | + |
| 97 | + async with Client("http://heartbeat.invalid", worker_token="synthetic-worker-token") as client: |
| 98 | + await client._http.aclose() |
| 99 | + client._http = httpx.AsyncClient(base_url="http://heartbeat.invalid", transport=httpx.MockTransport(respond)) |
| 100 | + reference = datetime.now(timezone.utc) |
| 101 | + def timestamp(value: datetime) -> str: |
| 102 | + return value.isoformat(timespec="microseconds").replace("+00:00", "Z") |
| 103 | + |
| 104 | + authority = ActivityLeaseAuthority.delivery(client, client.namespace, { |
| 105 | + "task_id": "original-task" if same_original else "different-task", |
| 106 | + "workflow_id": "workflow-1", "run_id": "run-1", "activity_execution_id": "execution-1", |
| 107 | + "activity_attempt_id": "original-attempt", "lease_owner": "original-worker", |
| 108 | + "task_queue": "original-queue", "attempt_number": 1, |
| 109 | + "lease_expires_at": timestamp(reference + timedelta(seconds=30)), "deadlines": {}, |
| 110 | + }, owner="original-worker", task_queue="original-queue", server_time=timestamp(reference), |
| 111 | + request_started=time.monotonic()) |
| 112 | + token = current_activity_authority.set(authority) |
| 113 | + try: |
| 114 | + ctx = ActivityContext(info=ActivityInfo( |
| 115 | + task_id="original-task", activity_type="heartbeat-refusal", activity_attempt_id="original-attempt", |
| 116 | + attempt_number=1, task_queue="original-queue", worker_id="original-worker", |
| 117 | + ), client=client) |
| 118 | + with pytest.raises(ActivityLeaseAuthorityLost, match="attempt_closed"): |
| 119 | + await ctx.heartbeat() |
| 120 | + if same_original: |
| 121 | + with pytest.raises(ActivityLeaseAuthorityLost, match="attempt_closed"): |
| 122 | + await client.complete_activity_task( |
| 123 | + task_id="original-task", activity_attempt_id="original-attempt", |
| 124 | + lease_owner="original-worker", result="late result", |
| 125 | + ) |
| 126 | + assert paths == ["/api/worker/activity-tasks/original-task/heartbeat"] |
| 127 | + else: |
| 128 | + assert authority.remaining() > 0 |
| 129 | + finally: |
| 130 | + current_activity_authority.reset(token) |
| 131 | + |
| 132 | + |
| 133 | +@pytest.mark.asyncio |
| 134 | +@pytest.mark.parametrize("late_error", (None, ValueError, NonRetryableError)) |
| 135 | +async def test_swallowed_heartbeat_refusal_still_fences_worker_publication(late_error: type[Exception] | None) -> None: |
| 136 | + client = refusing_client("attempt_closed") |
| 137 | + |
| 138 | + @activity.defn(name="heartbeat-refusal-caught") |
| 139 | + async def handler() -> str: |
| 140 | + with suppress(Exception): |
| 141 | + await activity.context().heartbeat() |
| 142 | + if late_error is not None: |
| 143 | + raise late_error("application error after closed attempt") |
| 144 | + return "late result" |
| 145 | + |
| 146 | + worker = Worker(client, task_queue="original-queue", workflows=[], activities=[handler]) |
| 147 | + task = { |
| 148 | + "task_id": "original-task", "activity_attempt_id": "original-attempt", |
| 149 | + "activity_type": "heartbeat-refusal-caught", "attempt_number": 1, |
| 150 | + "arguments": serializer.encode([], codec="avro"), "payload_codec": "avro", |
| 151 | + } |
| 152 | + |
| 153 | + assert await worker._run_activity_task(task) == "claim_aborted" |
| 154 | + client.complete_activity_task.assert_not_called() |
| 155 | + client.fail_activity_task.assert_not_called() |
0 commit comments