Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
56 changes: 56 additions & 0 deletions docs/reference/worker.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions docs/sdk-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/durable_workflow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
ActivityCancelled,
ActivityFailed,
ActivityHeartbeatResumeUnavailable,
ActivityHeartbeatUnavailable,
ChildWorkflowCancelled,
ChildWorkflowFailed,
ChildWorkflowTerminated,
Expand Down Expand Up @@ -274,6 +275,7 @@
"ActivityRetryInfo",
"ActivityHeartbeatCheckpoint",
"ActivityHeartbeatResumeUnavailable",
"ActivityHeartbeatUnavailable",
"ActivityInterceptorContext",
"ActivityRetryPolicy",
"BridgeAdapterOutcome",
Expand Down
32 changes: 25 additions & 7 deletions src/durable_workflow/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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:
Expand All @@ -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()
Expand Down
41 changes: 41 additions & 0 deletions src/durable_workflow/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"


Expand Down
4 changes: 3 additions & 1 deletion tests/test_activity_checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down
Loading