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
16 changes: 16 additions & 0 deletions docs/sdk-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1129,6 +1129,22 @@ libraries.
- **Worker interceptors**: Typed hooks around workflow tasks, activity calls, and query tasks for tracing, logging, and custom metrics
- **Metrics hooks**: Pluggable counters and histograms, with an optional Prometheus adapter

## Continue on the promoted build

A continue-as-new successor inherits its predecessor's build by default.
To move a long-lived chain to the promoted build at the next run boundary,
return or yield the targeted command inside the workflow.

```python
return ctx.continue_as_new(next_cursor, target_build="promoted")
```

The promoted build must serve the successor's workflow type on its task queue
and accept the arguments you pass. The Server records the build selection in
both runs. An unavailable promotion leaves the run open and the task follows
its normal retry path. When the worker's current registration lacks support,
the SDK raises `ContinueAsNewTargetUnsupported` at the authoring call.

## Workflow time and durable waits

`ctx.now()` returns the run's persisted start time and stays fixed for that
Expand Down
4 changes: 4 additions & 0 deletions src/durable_workflow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from . import activity, sync, testing, workflow
from ._activity_checkpoint import ActivityHeartbeatCheckpoint
from ._continue_as_new import ContinueAsNewTargetBuild
from .activity import ActivityContext, ActivityInfo, ActivityRetryInfo
from .auth_composition import (
AUTH_COMPOSITION_CONTRACT_SCHEMA,
Expand Down Expand Up @@ -76,6 +77,7 @@
ChildWorkflowCancelled,
ChildWorkflowFailed,
ChildWorkflowTerminated,
ContinueAsNewTargetUnsupported,
DuplicateRegistrationError,
DurableOperationCancelled,
DurableWorkflowError,
Expand Down Expand Up @@ -287,6 +289,8 @@
"ChildWorkflowTerminated",
"Client",
"ContinueAsNew",
"ContinueAsNewTargetBuild",
"ContinueAsNewTargetUnsupported",
"DurableOperationCancelled",
"DurableOperationHandle",
"MessageStream",
Expand Down
35 changes: 35 additions & 0 deletions src/durable_workflow/_continue_as_new.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""Worker protocol contract for targeted continue-as-new."""

from __future__ import annotations

import re
from collections.abc import Mapping
from typing import Literal, TypeAlias, TypeGuard

ContinueAsNewTargetBuild: TypeAlias = Literal["inherited", "promoted"]

CAPABILITY = "continue_as_new_target_build"
WORKER_PROTOCOL = "1.21"
PROMOTED_BUILD_UNAVAILABLE = "promoted_build_unavailable"


def valid_target(value: object) -> TypeGuard[ContinueAsNewTargetBuild]:
return isinstance(value, str) and value in ("inherited", "promoted")


def registration_supports_target(ack: object, worker_id: str, namespace: str | None, task_queue: str) -> bool:
if (
not isinstance(ack, Mapping)
or namespace is None
or ack.get("registered") is not True
or ack.get("worker_id") != worker_id
or ack.get("namespace") != namespace
or ack.get("task_queue") != task_queue
):
return False
capabilities = ack.get("server_capabilities")
if not isinstance(capabilities, Mapping) or capabilities.get(CAPABILITY) is not True:
return False
protocol = ack.get("protocol_version")
match = re.fullmatch(r"1\.([0-9]{1,4})", protocol) if isinstance(protocol, str) else None

Check warning on line 34 in src/durable_workflow/_continue_as_new.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use concise character class syntax '\d' instead of '[0-9]'.

See more on https://sonarcloud.io/project/issues?id=durable-workflow_sdk-python&issues=AaIJHDBWn2VTrPuIeJW4&open=AaIJHDBWn2VTrPuIeJW4&pullRequest=373
return match is not None and int(match[1]) >= 21
38 changes: 35 additions & 3 deletions src/durable_workflow/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@

import httpx

from . import serializer
from . import _continue_as_new, serializer
from ._activity_checkpoint import capture_poll as _capture_activity_checkpoint
from ._activity_lease import ActivityLeaseAuthority, current_activity_authority
from ._cancellation_scope import CancellationScopeOpenReceipt, scope_identity
Expand Down Expand Up @@ -73,6 +73,7 @@
from .errors import (
REQUEST_ID_AMBIGUOUS,
REQUEST_ID_CONFLICT,
ContinueAsNewTargetUnsupported,
ExternalPayloadIntegrityMismatch,
ExternalPayloadOversized,
ExternalPayloadUnavailable,
Expand Down Expand Up @@ -2005,6 +2006,7 @@
self._cluster_info: dict[str, Any] | None = None
self._cluster_info_lock = asyncio.Lock()
self._capabilities_digest = ServerCapabilitiesDigest()
self._continue_as_new_target_workers: set[tuple[str, str]] = set()
self._runtime_external_payload_transport_cache: (
_RuntimeExternalPayloadTransport | None
) = None
Expand All @@ -2023,6 +2025,7 @@
Safe to call multiple times.
"""
self._workflow_payload_observers.clear()
self._continue_as_new_target_workers.clear()
await self._http.aclose()

async def __aenter__(self) -> Client:
Expand Down Expand Up @@ -2208,6 +2211,7 @@
context: str = "",
retry: bool = True,
raise_for_status: Callable[..., None] = _raise_for_status,
worker_protocol_version: str | None = None,
) -> Any:
if worker and discovery:
raise ValueError("a request cannot be both worker-plane and cluster discovery")
Expand Down Expand Up @@ -2269,6 +2273,8 @@
if worker and activity_authority is not None and activity_authority.governs(self, self.namespace, path):
request_timeout = min(request_timeout, activity_authority.remaining())
headers = self._discovery_headers() if discovery else self._headers(worker=worker)
if worker and worker_protocol_version is not None:
headers["X-Durable-Workflow-Protocol-Version"] = worker_protocol_version
if capabilities_digest is not None:
headers[CAPABILITIES_DIGEST_HEADER] = ServerCapabilitiesDigest.header(capabilities_digest)
if progress_poll:
Expand Down Expand Up @@ -4101,6 +4107,7 @@

async def deregister_worker(self, worker_id: str) -> dict[str, Any]:
"""Remove a stale or retired worker from the server roster."""
self._continue_as_new_target_workers.discard((self.namespace, worker_id))
data = await self._request("DELETE", f"/workers/{quote(worker_id, safe='')}", context=worker_id)
if not isinstance(data, dict):
raise ServerError(
Expand Down Expand Up @@ -6177,7 +6184,12 @@
body["process_metrics"] = process_metrics
if heartbeat_interval_seconds is not None:
body["heartbeat_interval_seconds"] = heartbeat_interval_seconds
return await self._request("POST", "/worker/register", worker=True, json=body)
session = (self.namespace, worker_id)
self._continue_as_new_target_workers.discard(session)
ack = await self._request("POST", "/worker/register", worker=True, json=body)
if _continue_as_new.registration_supports_target(ack, worker_id, self.namespace, task_queue):
self._continue_as_new_target_workers.add(session)
return ack

async def create_worker_session(
self, worker_id: str, options: WorkerSessionOptions
Expand Down Expand Up @@ -6228,6 +6240,7 @@
not isinstance(registration_token, str) or re.fullmatch(r"[a-f0-9]{32}", registration_token) is None
):
raise ValueError("registration_token must contain exactly 32 lowercase hexadecimal characters")
self._continue_as_new_target_workers.discard((self.namespace, worker_id))
fenced = registration_token is not None
try:
data = await self._request(
Expand Down Expand Up @@ -6412,7 +6425,7 @@

return data.get("task")

async def complete_workflow_task(

Check failure on line 6428 in src/durable_workflow/client.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 26 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=durable-workflow_sdk-python&issues=AaIJHDLsn2VTrPuIeJW6&open=AaIJHDLsn2VTrPuIeJW6&pullRequest=373
self,
*,
task_id: str,
Expand Down Expand Up @@ -6444,6 +6457,18 @@
failure_type="WorkflowTaskWaitingForHistory",
)

supports_target = (self.namespace, lease_owner) in self._continue_as_new_target_workers
continuation_protocol = None
for command in commands:
is_continuation = command.get("type") == "continue_as_new"
if "target_build" in command:
if not is_continuation or not _continue_as_new.valid_target(command["target_build"]):
raise ValueError("invalid_target_build: use the exact inherited or promoted continuation target")
if not supports_target:
raise ContinueAsNewTargetUnsupported()
if is_continuation and supports_target:
continuation_protocol = _continue_as_new.WORKER_PROTOCOL

body: dict[str, Any] = {
"lease_owner": lease_owner,
"workflow_task_attempt": workflow_task_attempt,
Expand All @@ -6462,6 +6487,7 @@
return await self._request(
"POST", f"/worker/workflow-tasks/{task_id}/complete", worker=True, json=body,
context="task_completion",
worker_protocol_version=continuation_protocol,
)

async def fail_workflow_task(
Expand All @@ -6482,6 +6508,11 @@
The runtime may block incompatible replay until compatible code and
a supported repair are available instead of automatically retrying it.
"""
continuation_protocol = None
if failure_reason == _continue_as_new.PROMOTED_BUILD_UNAVAILABLE:
if (self.namespace, lease_owner) not in self._continue_as_new_target_workers:
raise ContinueAsNewTargetUnsupported()
continuation_protocol = _continue_as_new.WORKER_PROTOCOL
failure: dict[str, Any] = {"message": message}
if failure_type is not None:
failure["type"] = failure_type
Expand All @@ -6495,7 +6526,8 @@
"failure": failure,
}
return await self._request(
"POST", f"/worker/workflow-tasks/{task_id}/fail", worker=True, json=body
"POST", f"/worker/workflow-tasks/{task_id}/fail", worker=True, json=body,
worker_protocol_version=continuation_protocol,
)

async def heartbeat_workflow_task(
Expand Down
9 changes: 9 additions & 0 deletions src/durable_workflow/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ class DurableWorkflowError(Exception):
"""Base class for every exception raised by the SDK."""


class ContinueAsNewTargetUnsupported(DurableWorkflowError):
"""The current worker registration cannot send a continue-as-new target."""

reason = "unsupported_target_build"

def __init__(self) -> None:
super().__init__(f"{self.reason}: the Server did not advertise build selection for this worker session")


class ActivityHeartbeatResumeUnavailable(DurableWorkflowError):
"""This claim did not supply the supported heartbeat-resume contract."""

Expand Down
48 changes: 44 additions & 4 deletions src/durable_workflow/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@

import httpx

from . import serializer
from . import _continue_as_new, serializer
from ._activity_lease import (
ACTIVITY_LEASE_RENEWAL_EXHAUSTED,
ActivityLeaseAuthority,
Expand Down Expand Up @@ -84,6 +84,7 @@
ActivityFailed,
ActivityWorkerLost,
AvroNotInstalledError,
ContinueAsNewTargetUnsupported,
DuplicateRegistrationError,
DurableWorkflowError,
ExternalPayloadError,
Expand Down Expand Up @@ -1465,6 +1466,7 @@ def __init__(
self._poller_tasks: set[asyncio.Task[Any]] = set()
self._registered = False
self._deregistration_fenced = False
self._continue_as_new_target_build_supported = False
self._sticky_history_suffix_supported = False
self._registration_token: str | None = None
self._registration_worker_id: str | None = None
Expand Down Expand Up @@ -1763,6 +1765,7 @@ async def _register(self) -> None:
"supported": True, "minimum_protocol_version": "1.18", "version": 1,
}

self._continue_as_new_target_build_supported = False
ack = await self.client.register_worker(
worker_id=self.worker_id,
task_queue=self.task_queue,
Expand All @@ -1777,6 +1780,9 @@ async def _register(self) -> None:
capabilities=capabilities,
capability_manifest={
**affinity_manifest,
_continue_as_new.CAPABILITY: {
"supported": True, "minimum_protocol_version": _continue_as_new.WORKER_PROTOCOL,
},
**({"nexus_cooperative_cancellation": {
"supported": True, "minimum_protocol_version": "1.20",
"implementation": "owned_workflow_run_canonical_delivery",
Expand All @@ -1798,6 +1804,9 @@ async def _register(self) -> None:
task_slots=self._current_task_slots(),
process_metrics=self._current_process_metrics(),
)
self._continue_as_new_target_build_supported = _continue_as_new.registration_supports_target(
ack, self.worker_id, getattr(self.client, "namespace", None), self.task_queue,
)
if self._deregistration_fenced:
token = ack.get("registration_token") if isinstance(ack, dict) else None
if (
Expand Down Expand Up @@ -2148,6 +2157,7 @@ async def _replay_workflow_claim(
allow_cancellation_scope_authoring=self._allow_cancellation_scope_authoring,
allow_cancellation_scope_delivery=self._allow_cancellation_scope_delivery,
record_parallel_failure_order=self.record_parallel_failure_order,
allow_continue_as_new_target_build=self._continue_as_new_target_build_supported,
)
if outcome.cancellation_scope_delivery is not None:
if outcome.commands:
Expand Down Expand Up @@ -3146,6 +3156,9 @@ def execute_local(command: RecordLocalActivity) -> Any:
except _WorkflowClaimDeferred:
log.info("workflow task %s released for durable successor work", task_id)
return None
except ContinueAsNewTargetUnsupported as error:
log.info("workflow task %s left on its original claim: %s", task_id, error)
return None
except LocalActivityExecutionAborted as e:
log.warning("abandoning workflow task %s before local activity commit: %s", task_id, e)
return None
Expand Down Expand Up @@ -3316,7 +3329,27 @@ def serialize_commands(source: list[Command]) -> list[dict[str, Any]]:
message_stream_waits=outcome.message_stream_waits,
sticky_cache=self._sticky_cache_claim(task, history, commands),
)
except ContinueAsNewTargetUnsupported as error:
log.info("workflow task %s left on its original claim: %s", task_id, error)
return None
except Exception as e:
if (
isinstance(e, ServerError)
and e.status == 409
and e.reason() == _continue_as_new.PROMOTED_BUILD_UNAVAILABLE
and isinstance(e.body, dict)
and e.body.get("retryable") is True
and e.body.get("request_admitted") is False
and any(
command.get("type") == "continue_as_new" and command.get("target_build") == "promoted"
for command in commands
)
):
log.info("workflow task %s will retry after promoted build admission was refused", task_id)
await self._report_workflow_task_after_completion_error(
task_id, attempt, e, failure_reason=_continue_as_new.PROMOTED_BUILD_UNAVAILABLE,
)
return None
log.warning("failed to complete workflow task %s: %s", task_id, e)
if _is_storage_admission_error(e) or isinstance(e, WorkflowTaskCompletionTooLarge):
return None
Expand Down Expand Up @@ -3453,15 +3486,22 @@ async def _report_workflow_task_after_completion_error(
task_id: str,
attempt: int,
error: Exception,
*,
failure_reason: str | None = None,
) -> None:
promoted_unavailable = failure_reason == _continue_as_new.PROMOTED_BUILD_UNAVAILABLE
try:
await self.client.fail_workflow_task(
task_id=task_id,
lease_owner=self.worker_id,
workflow_task_attempt=attempt,
message=f"workflow task completion failed after commands were produced: {error}",
failure_type=type(error).__name__,
stack_trace=traceback.format_exc(),
message=(
"The promoted build is unavailable for the successor workflow." if promoted_unavailable
else f"workflow task completion failed after commands were produced: {error}"
),
failure_type="PromotedBuildUnavailable" if promoted_unavailable else type(error).__name__,
stack_trace=None if promoted_unavailable else traceback.format_exc(),
failure_reason=failure_reason,
)
except Exception as fail_error:
log.warning(
Expand Down
Loading