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
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
compares it with the original timer or the competing child terminal. Ordered
authoring stays disabled until every Server process sharing the database
supports marked waits. (durable-workflow/.github#230)
- The worker now rides out a Server or database failover that answers HTTP 500
and then 503 (found in a Cloud HA run, durable-workflow/cloud#752). Before,
the PHP SDK worker exited there. Python's pollers and heartbeats already kept
running, but three gaps remained:
- **Plain HTTP 500:** a 500 without a protocol `reason` (for example
`{"message": "Server Error"}`), or with the Server's generic
`server_error` reason that a database failover returns, now counts as
transient, like an upstream
502, 503 or 504. Before, an activity completion or failure report hit by
one was dropped after the client's three quick attempts, and registration
hit by one stopped `Worker.run()`. A 5xx with a typed `reason`, a
`retryable: false` answer and every 4xx refusal keep their handling.
- **Workflow-task completions:** a completion that fails transiently is now
resent with the shared backoff while the task's `lease_expires_at` covers
the next wait (60 seconds when the lease is unknown). Before, it was given
up after about a second and the task waited for its lease to expire. Each
resend has the same task ID, lease owner, attempt and commands, so lease
fencing is unchanged. When the lease runs out the worker logs an error and
the Server delivers the task again.
- **`Retry-After`:** the worker now honours a `Retry-After` header, both the
delta-seconds and the HTTP-date form, capped at 60 seconds. It applies to
polls, registration, activity outcomes and workflow-task completions.
Errors raised for HTTP responses expose the parsed value as `retry_after`.
`TransportRetryPolicy` honours the header between its own attempts, capped
at `max_backoff_seconds`.

## [2.23.0] - 2026-11-23

Expand Down
42 changes: 40 additions & 2 deletions docs/reference/worker.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ including HTTP errors, rejected credentials and unreachable runtimes. The wait
before the *n*-th consecutive retry is `uniform(0, min(10, 0.25 * 2**(n - 1)))`
seconds. That is the shared full-jitter schedule with a 10-second cap, so a
poller recovers quickly once the runtime is back, and workers do not retry in
lockstep. A bounded retry delay advertised by the Server is still honoured. Any
lockstep. A bounded retry delay advertised by the Server is still honoured,
including an HTTP `Retry-After` header (see
[Server failover and `Retry-After`](#server-failover-and-retry-after)). Any
successful poll, including an empty response, resets the schedule. Shutdown
interrupts the wait.

Expand Down Expand Up @@ -135,7 +137,9 @@ up or briefly unavailable while they register. Cluster discovery and
registration are repeated whole after a transient failure:

- a refused, reset or timed-out connection
- an upstream 502, 503 or 504 without a protocol body
- an HTTP 500, 502, 503 or 504 without a protocol `reason`, or with the
Server's generic reason `server_error`, from an upstream proxy or a Server
error such as a database failover
- a 503 whose reason is `storage_unavailable` or `backend_unavailable`
(native Server answers every storage failure with this body)
- any 5xx or 429 that says `retryable: true`
Expand All @@ -156,6 +160,7 @@ not read cluster info again, so a later cluster-info outage cannot stop it.
Some failures are never retried:

- `retryable: false`
- a 5xx with any other typed `reason`
- HTTP 401 or 403
- any other 4xx protocol refusal
- an incompatible Server
Expand Down Expand Up @@ -192,6 +197,39 @@ closed. It is reported as such and never treated as success. After
registration, pollers keep the poll-failure backoff described above. Worker
heartbeats log a failure and try again at the next interval.

### Workflow-task completions through transient failures

A workflow-task completion that hits one of the transient failures listed
above is sent again with the same backoff while the task's `lease_expires_at`
still covers the next wait, or for up to 60 seconds when the task carries no
lease. Every resend is the same request: the same task ID, lease owner,
`workflow_task_attempt` and commands, so the Server fences it exactly like the
first send. A lease or attempt refusal of a resend (`task_not_leased`,
`lease_expired`, `workflow_task_attempt_mismatch` and the like) is never
reported as a workflow-task failure, so resending a completion that a
transient hid cannot turn it into a failure.

When the lease cannot cover another wait, the worker logs `workflow task <id>
completion not delivered after N transient failures ...: its lease ran out`
at error level and stops resending. The Server delivers the task again when
the lease expires. Other retryable completion failures, such as a 5xx with a
typed reason, keep the short budget of three attempts. Definitive 4xx refusals
are never resent.

### Server failover and `Retry-After`

During a database failover a Server can answer HTTP 500 with reason
`server_error` (or without a reason), then HTTP 503, before it recovers. `Worker.run()` keeps running
through that sequence. Polls, registration, activity outcomes and
workflow-task completions all retry it as described above.

When a failed response carries a `Retry-After` header, in either the
delta-seconds form (`Retry-After: 5`) or the HTTP-date form, the worker waits
at least that long before the next attempt, capped at 60 seconds. The client
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`.

## Lifecycle and shutdown

`Worker.run()` and `Worker.run_until()` register through the worker protocol
Expand Down
25 changes: 16 additions & 9 deletions src/durable_workflow/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
REQUEST_ID_AMBIGUOUS,
REQUEST_ID_CONFLICT,
ContinueAsNewTargetUnsupported,
DurableWorkflowError,
ExternalPayloadIntegrityMismatch,
ExternalPayloadOversized,
ExternalPayloadUnavailable,
Expand Down Expand Up @@ -104,7 +105,7 @@
)
from .metrics import CLIENT_REQUEST_DURATION_SECONDS, CLIENT_REQUESTS, NOOP_METRICS, MetricsRecorder
from .nexus import NexusOperationResult, nexus_request_payload
from .retry_policy import TransportRetryPolicy
from .retry_policy import TransportRetryPolicy, response_retry_after
from .telemetry import ExecutionTelemetry, current_execution_telemetry
from .telemetry_carrier import supported as observability_supported
from .worker_session import WorkerSessionOptions
Expand Down Expand Up @@ -2324,14 +2325,20 @@ async def _answer() -> httpx.Response:
# The HTTP error is the answer; an unusable digest in it
# never replaces it. Ask for full capabilities next time.
self._capabilities_digest.forget()
# The typed completion-size refusal carries the limit; the
# size is the encoded request body this client sent.
if raise_for_status is _raise_for_status:
raise_for_status(
exc.response.status_code, body, context=context,
request_bytes=_request_body_bytes(exc.request),
)
raise_for_status(exc.response.status_code, body, context=context)
retry_after = response_retry_after(exc)
try:
# The typed completion-size refusal carries the limit; the
# size is the encoded request body this client sent.
if raise_for_status is _raise_for_status:
raise_for_status(
exc.response.status_code, body, context=context,
request_bytes=_request_body_bytes(exc.request),
)
raise_for_status(exc.response.status_code, body, context=context)
except DurableWorkflowError as typed:
if retry_after is not None:
typed.retry_after = retry_after
raise
raise # unreachable, but keeps type checker happy

try:
Expand Down
5 changes: 5 additions & 0 deletions src/durable_workflow/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ class explicitly (``except (ActivityCancelled, ...):``). This mirrors the way
class DurableWorkflowError(Exception):
"""Base class for every exception raised by the SDK."""

#: Seconds the Server asked the client to wait before retrying, parsed
#: from the ``Retry-After`` header of the HTTP response this error was
#: raised for (delta-seconds or HTTP-date). ``None`` when there was none.
retry_after: float | None = None


class ContinueAsNewTargetUnsupported(DurableWorkflowError):
"""The current worker registration cannot send a continue-as-new target."""
Expand Down
43 changes: 42 additions & 1 deletion src/durable_workflow/retry_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,13 @@
import contextvars
import json
import logging
import math
import random
import re
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from typing import TypeVar

import httpx
Expand All @@ -36,6 +39,38 @@
)


def parse_retry_after(value: str | None, *, now: datetime | None = None) -> float | None:
"""Seconds to wait from an HTTP ``Retry-After`` value, or ``None``.

Both forms of RFC 9110 are accepted: delta-seconds (``"5"``) and an
HTTP-date (``"Wed, 25 Nov 2026 22:40:41 GMT"``). A date in the past waits
zero seconds. Anything else is ignored. Callers apply their own cap.
"""
if value is None:
return None
value = value.strip()
if value.isascii() and value.isdigit():
# Callers cap the wait; an absurdly long value must not raise.
if len(value) > 10:
return float(10**10)
return float(int(value))
try:
when = parsedate_to_datetime(value)
except (TypeError, ValueError, IndexError, OverflowError):
return None
if when.tzinfo is None:
when = when.replace(tzinfo=timezone.utc)
seconds = (when - (now or datetime.now(timezone.utc))).total_seconds()
return max(0.0, seconds) if math.isfinite(seconds) else None


def response_retry_after(exc: BaseException) -> float | None:
"""The ``Retry-After`` delay of a failed HTTP response, or ``None``."""
if not isinstance(exc, httpx.HTTPStatusError):
return None
return parse_retry_after(exc.response.headers.get("retry-after"))


def _query_timeout_refusal(exc: httpx.HTTPStatusError) -> bool:
request = exc.request
if (exc.response.status_code != 504 or request.method != "POST"
Expand Down Expand Up @@ -220,7 +255,9 @@ class TransportRetryPolicy:
child workflow retries with
:class:`durable_workflow.workflow.ChildWorkflowRetryPolicy`.

Uses exponential backoff with jitter to avoid thundering herd.
Uses exponential backoff with jitter to avoid thundering herd. A
``Retry-After`` header on a retried response (delta-seconds or HTTP-date)
lengthens that wait, capped at ``max_backoff_seconds``.
Canonical query timeouts end the original query and are surfaced without
another query admission; unrelated transient HTTP failures still retry.
"""
Expand Down Expand Up @@ -320,6 +357,10 @@ async def execute(self, fn: Callable[[], Awaitable[T]]) -> T:

if attempt + 1 < self.max_attempts:
backoff = self.backoff_seconds(attempt)
retry_after = response_retry_after(exc)
if retry_after is not None:
# Honour the Server's Retry-After, capped by this policy's ceiling.
backoff = max(backoff, min(retry_after, self.max_backoff_seconds))
await asyncio.sleep(backoff)

attempt += 1
Expand Down
Loading