diff --git a/CHANGELOG.md b/CHANGELOG.md index 8722b28..4938800 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 and never send the marker; listing `timeout_cleanup` without `cooperative_cancellation` raises `ValueError`. ([Server #1201](https://github.com/durable-workflow/server/issues/1201)) +- `ActivityHeartbeatUnavailable`, exported from `durable_workflow`. An + activity's `heartbeat()` or `heartbeat_sync()` raises it when a transient + outage, such as a Server failover (durable-workflow/cloud#752), outlasts the + client's transport retries. Before, this case raised a plain `ServerError`, + or the raw `httpx` connection or timeout error. The heartbeat is still not + retried further, because it runs inside activity code and a hidden retry + would block the activity. The activity can catch the error, keep working or + retry with backoff, and complete. The error subclasses `ServerError`, so + existing `except ServerError` handlers still catch it. It carries the + Server's `Retry-After` as `retry_after` (or `None`) and the underlying error + as `cause`. It is raised only for the failures the worker already treats as + transient (#383): connection and timeout errors, a 500, 502, 503 or 504 + without a reason or with `server_error`, a 503 `storage_unavailable` or + `backend_unavailable`, and a 5xx or 429 with `retryable: true`. Code that + caught `httpx.TransportError` from a heartbeat must catch + `ActivityHeartbeatUnavailable` instead. Cancellation, a lost lease or closed + attempt, 4xx refusals and 5xx errors with a typed reason keep their existing + errors. See "Activity heartbeats during a failover" in the worker reference. ## [2.23.1] - 2026-11-24 diff --git a/docs/reference/worker.md b/docs/reference/worker.md index 1ef5e6d..63afea3 100644 --- a/docs/reference/worker.md +++ b/docs/reference/worker.md @@ -230,6 +230,62 @@ exposes the parsed value as `retry_after` on the raised error. The client's own `TransportRetryPolicy` also honours the header between its quick attempts, capped at its `max_backoff_seconds`. +### Activity heartbeats during a failover + +`await activity.context().heartbeat(details)` and `heartbeat_sync(details)` +are not retried beyond the client's quick transport attempts. They run inside +your activity code, so a long hidden retry would block the activity. When a +transient failure from the list above outlasts those attempts, the call raises +`ActivityHeartbeatUnavailable`. Its `retry_after` is the Server's +`Retry-After` in seconds, or `None`, and its `cause` is the underlying error. +It subclasses `ServerError`, so existing `except ServerError` handlers still +catch it. + +The heartbeat was not confirmed, but the attempt still holds its claim. The +activity can keep working, or wait and heartbeat again: + +```python +import asyncio +import random + +from durable_workflow import ActivityHeartbeatUnavailable, activity + + +async def heartbeat_through_outage(details: dict, *, attempts: int = 6) -> None: + ctx = activity.context() + delay = 0.5 + for attempt in range(1, attempts + 1): + try: + await ctx.heartbeat(details) + return + except ActivityHeartbeatUnavailable as outage: + if attempt == attempts: + raise + wait = random.uniform(0, delay) + await asyncio.sleep(max(wait, outage.retry_after or 0.0)) + delay = min(delay * 2, 8.0) + + +@activity.defn(name="export_rows") +async def export_rows(batch: list[str]) -> int: + for index, row in enumerate(batch): + await write_row(row) # your application's work + await heartbeat_through_outage({"row": index}) + return len(batch) +``` + +Keep the total wait well inside the activity's heartbeat timeout. After that +the Server times out the attempt, and the activity's retry policy applies. The +example re-raises on its last attempt, which fails this attempt. Only +transient failures raise `ActivityHeartbeatUnavailable`. Cancellation still +raises `ActivityCancelled`, a lost lease or closed attempt still raises +`ActivityWorkerLost`, and other refusals, such as a 4xx or a 5xx with a typed +reason, raise their usual errors. Don't retry those. + +With cooperative cancellation enabled, a remote activity runs in a supervised +callback process. There a failed heartbeat abandons the claim instead, and the +error does not reach activity code. + ## Lifecycle and shutdown `Worker.run()` and `Worker.run_until()` register through the worker protocol diff --git a/docs/sdk-reference.md b/docs/sdk-reference.md index 0cf9ac0..99ccb90 100644 --- a/docs/sdk-reference.md +++ b/docs/sdk-reference.md @@ -1611,6 +1611,12 @@ original `.reason`, such as `activity_deadline_elapsed`, `attempt_closed` or The worker releases the slot after the callback exits and submits neither a result nor a failure for that refused attempt. +A transient outage that outlasts the client's transport retries, such as a +Server failover, raises `ActivityHeartbeatUnavailable` instead. That is not a +refusal: the attempt keeps its claim, and the activity can keep working or +retry the heartbeat after its `retry_after`. See [Activity heartbeats during a +failover](reference/worker.md#activity-heartbeats-during-a-failover). + Checks happen at the next heartbeat. Code that never heartbeats may continue until it returns, subject to separately negotiated lease/cancellation supervision. The SDK cannot forcibly stop a running native thread or undo its diff --git a/src/durable_workflow/__init__.py b/src/durable_workflow/__init__.py index 86ee21f..7399b32 100644 --- a/src/durable_workflow/__init__.py +++ b/src/durable_workflow/__init__.py @@ -74,6 +74,7 @@ ActivityCancelled, ActivityFailed, ActivityHeartbeatResumeUnavailable, + ActivityHeartbeatUnavailable, ChildWorkflowCancelled, ChildWorkflowFailed, ChildWorkflowTerminated, @@ -274,6 +275,7 @@ "ActivityRetryInfo", "ActivityHeartbeatCheckpoint", "ActivityHeartbeatResumeUnavailable", + "ActivityHeartbeatUnavailable", "ActivityInterceptorContext", "ActivityRetryPolicy", "BridgeAdapterOutcome", diff --git a/src/durable_workflow/activity.py b/src/durable_workflow/activity.py index 2aec47c..2644b50 100644 --- a/src/durable_workflow/activity.py +++ b/src/durable_workflow/activity.py @@ -10,7 +10,7 @@ from ._activity_checkpoint import ActivityHeartbeatCheckpoint, _HeartbeatResume, claim_resume from ._activity_lease import current_activity_authority -from .errors import ActivityCancelled, ActivityWorkerLost +from .errors import ActivityCancelled, ActivityHeartbeatUnavailable, ActivityWorkerLost if TYPE_CHECKING: from .client import Client @@ -160,6 +160,8 @@ def heartbeat_sync(self, details: dict[str, Any] | None = None) -> None: The request runs on the worker's event loop using the original attempt and client. Async handlers must use ``await heartbeat()`` instead. + It raises the same errors as :meth:`heartbeat`, including + :class:`~durable_workflow.errors.ActivityHeartbeatUnavailable`. """ loop = self._event_loop if loop is None or not loop.is_running(): @@ -193,6 +195,12 @@ async def heartbeat(self, details: dict[str, Any] | None = None) -> None: Raises :class:`~durable_workflow.errors.ActivityWorkerLost` with the original Server reason when the attempt cannot continue, including an elapsed deadline, closed attempt or closed run. + + Raises :class:`~durable_workflow.errors.ActivityHeartbeatUnavailable` + when a transient outage, such as a Server failover, outlasts the + client's transport retries. The heartbeat is not retried further, so + the activity can choose to keep working and heartbeat again later, + waiting at least its ``retry_after`` when set. """ self._raise_if_cannot_continue() if self._heartbeat_callback is not None: @@ -202,12 +210,22 @@ async def heartbeat(self, details: dict[str, Any] | None = None) -> None: self._cancel_requested = True raise return - resp = await self._client.heartbeat_activity_task( - task_id=self._info.task_id, - activity_attempt_id=self._info.activity_attempt_id, - lease_owner=self._info.worker_id, - details=details, - ) + try: + resp = await self._client.heartbeat_activity_task( + task_id=self._info.task_id, + activity_attempt_id=self._info.activity_attempt_id, + lease_owner=self._info.worker_id, + details=details, + ) + except Exception as error: + # The worker's classification; imported here because worker imports this module. + from .worker import _transient_runtime_error + + # Not retried here: the activity decides whether to keep working + # through an outage. Definitive refusals keep their own errors. + if _transient_runtime_error(error): + raise ActivityHeartbeatUnavailable(self._info.task_id, error) from error + raise if isinstance(resp, dict) and resp.get("cancel_requested"): self._cancel_requested = True raise ActivityCancelled() diff --git a/src/durable_workflow/errors.py b/src/durable_workflow/errors.py index 5acd665..7ccaf4f 100644 --- a/src/durable_workflow/errors.py +++ b/src/durable_workflow/errors.py @@ -364,6 +364,47 @@ def is_storage_admission_failure(self, poll_request_id: str | None = None) -> bo ) +class ActivityHeartbeatUnavailable(ServerError): + """An activity heartbeat could not reach the Server because of a transient outage. + + :meth:`~durable_workflow.ActivityContext.heartbeat` and + :meth:`~durable_workflow.ActivityContext.heartbeat_sync` raise this after + the client's own transport retries are used up, for example during a + Server or database failover. It is raised only for failures that may + succeed unchanged once the Server recovers: a refused, reset or timed-out + connection; a 500, 502, 503 or 504 without a protocol ``reason`` or with + the generic ``server_error`` reason; a 503 ``storage_unavailable`` or + ``backend_unavailable``; and a 5xx or 429 that says ``retryable: true``. + + The heartbeat was not confirmed, but the attempt has not lost its + authority. Activity code may keep working and heartbeat again later, + waiting at least ``retry_after`` when it is set. A cancellation or lost + attempt still raises :class:`~durable_workflow.errors.ActivityCancelled` + or :class:`~durable_workflow.errors.ActivityWorkerLost`, and other + refusals keep their own errors. + + It subclasses :class:`~durable_workflow.errors.ServerError`, so existing + ``except ServerError`` handlers still catch it. ``status`` and ``body`` + are those of the HTTP response, or ``0`` and ``None`` when no response + arrived. ``cause`` (also ``__cause__``) is the underlying error, and + ``retry_after`` is the Server's ``Retry-After`` in seconds, or ``None`` + when it sent none. + """ + + def __init__(self, task_id: str, cause: BaseException) -> None: + if isinstance(cause, ServerError): + status, body = cause.status, cause.body + else: + status, body = 0, None + super().__init__(status, body) + detail = f"server returned {status}: {body!r}" if status else f"{type(cause).__name__}: {cause}" + self.args = (f"activity task {task_id!r} heartbeat not delivered; the Server is unavailable ({detail})",) + self.task_id = task_id + self.cause = cause + retry_after = getattr(cause, "retry_after", None) + self.retry_after = float(retry_after) if isinstance(retry_after, (int, float)) else None + + WORKFLOW_TASK_COMPLETION_BYTES = "workflow_task_completion_bytes" diff --git a/tests/test_activity_checkpoint.py b/tests/test_activity_checkpoint.py index 77a3236..ffd1266 100644 --- a/tests/test_activity_checkpoint.py +++ b/tests/test_activity_checkpoint.py @@ -161,8 +161,10 @@ async def test_heartbeat_outcomes_never_advance_the_received_checkpoint(outcome: ctx = context(poll(details={"cursor": 1}, at=AT)) if outcome == "uncertain": ctx._client.heartbeat_activity_task.side_effect = httpx.ReadTimeout("response lost") # type: ignore[attr-defined] - with pytest.raises(httpx.ReadTimeout): + from durable_workflow.errors import ActivityHeartbeatUnavailable + with pytest.raises(ActivityHeartbeatUnavailable) as raised: await ctx.heartbeat({"cursor": 2}) + assert isinstance(raised.value.cause, httpx.ReadTimeout) else: ctx._client.heartbeat_activity_task.return_value = { # type: ignore[attr-defined] "can_continue": outcome == "success", "last_heartbeat_details": {"cursor": 2}, diff --git a/tests/test_activity_heartbeat_unavailable.py b/tests/test_activity_heartbeat_unavailable.py new file mode 100644 index 0000000..2b108d8 --- /dev/null +++ b/tests/test_activity_heartbeat_unavailable.py @@ -0,0 +1,297 @@ +"""A user-called activity heartbeat raises a typed, catchable outage error. + +During a Server failover (durable-workflow/cloud#752) the Server can answer +HTTP 500 ``server_error`` and then 503 for longer than the client's transport +retries. ``ActivityContext.heartbeat()`` does not retry further; it raises +``ActivityHeartbeatUnavailable`` so activity code decides whether to keep +going. Definitive refusals keep their own errors. Every test uses a scripted +fake Server and injected waits, so nothing depends on timing. +""" +from __future__ import annotations + +import asyncio +import logging +from typing import Any + +import httpx +import pytest + +import durable_workflow +from durable_workflow import Client, activity, serializer +from durable_workflow.activity import ActivityContext, ActivityInfo +from durable_workflow.errors import ( + ActivityCancelled, + ActivityHeartbeatUnavailable, + ActivityWorkerLost, + DurableWorkflowError, + ServerError, + Unauthorized, +) +from durable_workflow.retry_policy import TransportRetryPolicy + +from .test_worker_transient_5xx_retry import SERVER_ERROR, FailoverServer, failover_worker, lease + +HEARTBEAT_PATH = "/api/worker/activity-tasks/t1/heartbeat" +ACCEPTED = (200, {"can_continue": True, "cancel_requested": False}, {}) + + +class HeartbeatServer: + """Answers activity heartbeats from a script, then accepts them.""" + + def __init__(self, script: list[tuple[int, Any, dict[str, str]] | Exception]) -> None: + self.script = script + self.sends: list[httpx.Request] = [] + + def respond(self, request: httpx.Request) -> httpx.Response: + assert request.url.path == HEARTBEAT_PATH + self.sends.append(request) + step = self.script.pop(0) if self.script else ACCEPTED + if isinstance(step, Exception): + raise step + status, body, headers = step + return httpx.Response(status, json=body, headers=headers) + + +def heartbeat_context(server: HeartbeatServer, *, transport_attempts: int = 2) -> tuple[Client, ActivityContext]: + # A real Client, so the error is built by the real request path. The + # transport retries are kept but never wait (a Retry-After is capped at 0). + policy = TransportRetryPolicy( + max_attempts=transport_attempts, initial_backoff_seconds=0.0, max_backoff_seconds=0.0, jitter=False, + ) + client = Client("http://runtime.invalid", token="token", retry_policy=policy) + client._http = httpx.AsyncClient(base_url="http://runtime.invalid", transport=httpx.MockTransport(server.respond)) + info = ActivityInfo( + task_id="t1", activity_type="export", activity_attempt_id="aa1", attempt_number=1, + task_queue="q", worker_id="w1", + ) + return client, ActivityContext(info=info, client=client) + + +def test_is_exported_and_keeps_existing_server_error_handlers_working() -> None: + assert durable_workflow.ActivityHeartbeatUnavailable is ActivityHeartbeatUnavailable + assert "ActivityHeartbeatUnavailable" in durable_workflow.__all__ + assert issubclass(ActivityHeartbeatUnavailable, ServerError) + assert issubclass(ActivityHeartbeatUnavailable, DurableWorkflowError) + + +async def test_server_error_500_raises_the_typed_error_with_retry_after_and_cause() -> None: + status, body, _ = SERVER_ERROR + server = HeartbeatServer([(status, body, {"Retry-After": "7"}), (status, body, {"Retry-After": "7"})]) + client, ctx = heartbeat_context(server) + try: + with pytest.raises(ActivityHeartbeatUnavailable) as raised: + await ctx.heartbeat({"row": 3}) + finally: + await client.aclose() + + error = raised.value + assert error.status == 500 + assert error.body == body + assert error.reason() == "server_error" + assert error.retry_after == 7.0 + assert error.task_id == "t1" + assert type(error.cause) is ServerError + assert error.cause.status == 500 + assert error.__cause__ is error.cause + assert "heartbeat not delivered" in str(error) + # Both transport attempts were used; heartbeat() added no hidden retry. + assert len(server.sends) == 2 + # The outage is not lost authority: the next heartbeat may go through. + assert not ctx.is_cancelled + ctx._raise_if_cannot_continue() + + +async def test_server_error_500_without_retry_after_has_none() -> None: + status, body, _ = SERVER_ERROR + server = HeartbeatServer([(status, body, {})]) + client, ctx = heartbeat_context(server, transport_attempts=1) + try: + with pytest.raises(ActivityHeartbeatUnavailable) as raised: + await ctx.heartbeat() + finally: + await client.aclose() + assert raised.value.retry_after is None + assert len(server.sends) == 1 + + +async def test_catching_server_error_still_catches_it() -> None: + status, body, _ = SERVER_ERROR + server = HeartbeatServer([(status, body, {})]) + client, ctx = heartbeat_context(server, transport_attempts=1) + try: + with pytest.raises(ServerError) as raised: + await ctx.heartbeat() + finally: + await client.aclose() + assert isinstance(raised.value, ActivityHeartbeatUnavailable) + + +@pytest.mark.parametrize( + "step", + [ + (500, {"message": "Server Error"}, {}), + (502, "Bad Gateway", {}), + (504, {}, {}), + (503, {"reason": "storage_unavailable", "message": "storage is unavailable"}, {}), + (503, {"reason": "backend_unavailable", "message": "backend is unavailable"}, {}), + (500, {"reason": "server_error", "retryable": True}, {}), + ], + ids=["500-untyped", "502-text", "504-empty", "503-storage", "503-backend", "500-retryable"], +) +async def test_transient_http_failures_raise_the_typed_error(step: tuple[int, Any, dict[str, str]]) -> None: + server = HeartbeatServer([step]) + client, ctx = heartbeat_context(server, transport_attempts=1) + try: + with pytest.raises(ActivityHeartbeatUnavailable) as raised: + await ctx.heartbeat() + finally: + await client.aclose() + assert raised.value.status == step[0] + assert isinstance(raised.value.cause, ServerError) + + +@pytest.mark.parametrize( + "failure", + [httpx.ConnectError("connection refused"), httpx.ReadTimeout("read timed out")], + ids=["connect", "timeout"], +) +async def test_connection_and_timeout_failures_raise_the_typed_error(failure: httpx.TransportError) -> None: + server = HeartbeatServer([failure, failure]) + client, ctx = heartbeat_context(server) + try: + with pytest.raises(ActivityHeartbeatUnavailable) as raised: + await ctx.heartbeat() + finally: + await client.aclose() + error = raised.value + assert error.status == 0 + assert error.body is None + assert error.retry_after is None + assert isinstance(error.cause, type(failure)) + assert error.__cause__ is error.cause + assert type(failure).__name__ in str(error) + assert len(server.sends) == 2 + + +@pytest.mark.parametrize( + ("step", "expected"), + [ + ((500, {"reason": "invariant_violation"}, {}), ServerError), + ((503, {"reason": "server_error", "retryable": False}, {}), ServerError), + ((409, {"reason": "stale_attempt", "recorded": False}, {}), ServerError), + ((401, {"reason": "unauthorized", "message": "bad token"}, {}), Unauthorized), + ], + ids=["500-typed-reason", "503-retryable-false", "409-stale-attempt", "401"], +) +async def test_definitive_refusals_keep_their_existing_errors( + step: tuple[int, Any, dict[str, str]], expected: type[Exception], +) -> None: + server = HeartbeatServer([step, step]) + client, ctx = heartbeat_context(server) + try: + with pytest.raises(DurableWorkflowError) as raised: + await ctx.heartbeat() + finally: + await client.aclose() + assert type(raised.value) is expected + assert not isinstance(raised.value, ActivityHeartbeatUnavailable) + + +async def test_lost_lease_still_raises_activity_worker_lost() -> None: + server = HeartbeatServer([(200, {"can_continue": False, "reason": "lease_expired", "cancel_requested": False}, {})]) + client, ctx = heartbeat_context(server) + try: + with pytest.raises(ActivityWorkerLost) as raised: + await ctx.heartbeat() + finally: + await client.aclose() + assert raised.value.reason == "lease_expired" + + +async def test_cancellation_still_raises_activity_cancelled() -> None: + server = HeartbeatServer([(200, {"can_continue": True, "cancel_requested": True}, {})]) + client, ctx = heartbeat_context(server) + try: + with pytest.raises(ActivityCancelled): + await ctx.heartbeat() + finally: + await client.aclose() + assert ctx.is_cancelled + + +class FailoverHeartbeatServer(FailoverServer): + """The failover fake Server with a scripted activity heartbeat route.""" + + def __init__(self, heartbeats: list[tuple[int, Any, dict[str, str]]]) -> None: + super().__init__({"heartbeat": heartbeats}) + self.heartbeats: list[dict[str, Any]] = [] + + async def respond(self, request: httpx.Request) -> httpx.Response: + if request.url.path.endswith("/activity-tasks/task-1/heartbeat"): + self.heartbeats.append(httpx.Response(200, content=request.content).json()) + failure = self.scripted("heartbeat") + if failure is not None: + return failure + return httpx.Response(200, json={"can_continue": True, "cancel_requested": False}) + return await super().respond(request) + + @staticmethod + def activity_task() -> dict[str, Any]: + return { + "task_id": "task-1", "activity_attempt_id": "attempt-1", "attempt_number": 1, + "activity_type": "heartbeat.failover.export", "workflow_id": "wf-1", "run_id": "run-1", + "lease_owner": "worker-1", "task_queue": "q", "lease_expires_at": lease(300), + "arguments": serializer.envelope([3], codec="avro"), "payload_codec": "avro", + } + + +async def test_activity_catches_the_outage_retries_and_completes(caplog: pytest.LogCaptureFixture) -> None: + status, body, _ = SERVER_ERROR + server = FailoverHeartbeatServer([ + (status, body, {"Retry-After": "3"}), + (503, {"reason": "storage_unavailable"}, {}), + ]) + waits: list[float] = [] + + @activity.defn(name="heartbeat.failover.export") + async def export(rows: int) -> dict[str, int]: + ctx = activity.context() + outages = 0 + for row in range(rows): + delay = 1.0 + while True: + try: + await ctx.heartbeat({"row": row}) + break + except ActivityHeartbeatUnavailable as outage: + outages += 1 + waits.append(max(delay, outage.retry_after or 0.0)) + await asyncio.sleep(0) # stands in for asyncio.sleep(waits[-1]) + delay = min(delay * 2, 8.0) + return {"rows": rows, "outages": outages} + + client, worker, _ = failover_worker(server, workflows=[], activities=[export]) + running = asyncio.create_task(worker.run()) + try: + for _ in range(500): + if server.completions: + break + await asyncio.sleep(0.01) + assert not running.done(), running.exception() if running.done() else None + finally: + await worker.stop() + running.cancel() + await asyncio.gather(running, return_exceptions=True) + await client.aclose() + + # The activity waited the Server's Retry-After, then its own backoff step. + assert waits == [3.0, 2.0] + # Row 0 was sent three times (500, 503, accepted), then rows 1 and 2 once. + assert [beat.get("details") for beat in server.heartbeats] == [ + {"row": 0}, {"row": 0}, {"row": 0}, {"row": 1}, {"row": 2}, + ] + assert len(server.completions) == 1 + completion = server.completions[0] + assert completion["activity_attempt_id"] == "attempt-1" + assert serializer.decode_envelope(completion["result"], codec="avro") == {"rows": 3, "outages": 2} + assert not [record for record in caplog.records if record.levelno >= logging.ERROR]