diff --git a/docs/sdk-reference.md b/docs/sdk-reference.md index 020574e..7dd67b4 100644 --- a/docs/sdk-reference.md +++ b/docs/sdk-reference.md @@ -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 diff --git a/src/durable_workflow/__init__.py b/src/durable_workflow/__init__.py index 53632f2..86ee21f 100644 --- a/src/durable_workflow/__init__.py +++ b/src/durable_workflow/__init__.py @@ -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, @@ -76,6 +77,7 @@ ChildWorkflowCancelled, ChildWorkflowFailed, ChildWorkflowTerminated, + ContinueAsNewTargetUnsupported, DuplicateRegistrationError, DurableOperationCancelled, DurableWorkflowError, @@ -287,6 +289,8 @@ "ChildWorkflowTerminated", "Client", "ContinueAsNew", + "ContinueAsNewTargetBuild", + "ContinueAsNewTargetUnsupported", "DurableOperationCancelled", "DurableOperationHandle", "MessageStream", diff --git a/src/durable_workflow/_continue_as_new.py b/src/durable_workflow/_continue_as_new.py new file mode 100644 index 0000000..95bd9f1 --- /dev/null +++ b/src/durable_workflow/_continue_as_new.py @@ -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 + return match is not None and int(match[1]) >= 21 diff --git a/src/durable_workflow/client.py b/src/durable_workflow/client.py index eaacf8b..d2b1a38 100644 --- a/src/durable_workflow/client.py +++ b/src/durable_workflow/client.py @@ -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 @@ -73,6 +73,7 @@ from .errors import ( REQUEST_ID_AMBIGUOUS, REQUEST_ID_CONFLICT, + ContinueAsNewTargetUnsupported, ExternalPayloadIntegrityMismatch, ExternalPayloadOversized, ExternalPayloadUnavailable, @@ -2005,6 +2006,7 @@ def __init__( 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 @@ -2023,6 +2025,7 @@ async def aclose(self) -> None: 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: @@ -2208,6 +2211,7 @@ async def _request( 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") @@ -2269,6 +2273,8 @@ async def _do_request() -> httpx.Response: 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: @@ -4101,6 +4107,7 @@ async def describe_worker(self, worker_id: str) -> WorkerDescription: 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( @@ -6177,7 +6184,12 @@ async def register_worker( 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 @@ -6228,6 +6240,7 @@ async def deregister_worker_registration( 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( @@ -6444,6 +6457,18 @@ async def complete_workflow_task( 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, @@ -6462,6 +6487,7 @@ async def complete_workflow_task( 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( @@ -6482,6 +6508,11 @@ async def fail_workflow_task( 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 @@ -6495,7 +6526,8 @@ async def fail_workflow_task( "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( diff --git a/src/durable_workflow/errors.py b/src/durable_workflow/errors.py index 870c901..e4dd263 100644 --- a/src/durable_workflow/errors.py +++ b/src/durable_workflow/errors.py @@ -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.""" diff --git a/src/durable_workflow/worker.py b/src/durable_workflow/worker.py index 89779c7..52458a1 100644 --- a/src/durable_workflow/worker.py +++ b/src/durable_workflow/worker.py @@ -41,7 +41,7 @@ import httpx -from . import serializer +from . import _continue_as_new, serializer from ._activity_lease import ( ACTIVITY_LEASE_RENEWAL_EXHAUSTED, ActivityLeaseAuthority, @@ -84,6 +84,7 @@ ActivityFailed, ActivityWorkerLost, AvroNotInstalledError, + ContinueAsNewTargetUnsupported, DuplicateRegistrationError, DurableWorkflowError, ExternalPayloadError, @@ -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 @@ -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, @@ -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", @@ -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 ( @@ -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: @@ -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 @@ -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 @@ -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( diff --git a/src/durable_workflow/workflow.py b/src/durable_workflow/workflow.py index 2e5ab4b..fc73ae1 100644 --- a/src/durable_workflow/workflow.py +++ b/src/durable_workflow/workflow.py @@ -45,6 +45,8 @@ ) from ._condition_fingerprint import fingerprint as _stable_condition_fingerprint from ._condition_fingerprint import fingerprint_verdict, is_legacy +from ._continue_as_new import ContinueAsNewTargetBuild +from ._continue_as_new import valid_target as _valid_continue_as_new_target from ._cooperative_cancellation import CancellationDelivery, read_cancellation_history from ._failure_reporting import exception_message from ._typed_values import decode_payload_value, to_payload_value, to_payload_values, validate_annotation @@ -63,6 +65,7 @@ ChildWorkflowCancelled, ChildWorkflowFailed, ChildWorkflowTerminated, + ContinueAsNewTargetUnsupported, DuplicateRegistrationError, DurableOperationCancelled, InvalidWorkflowDefinition, @@ -1146,6 +1149,14 @@ class ContinueAsNew: workflow_type: str | None = None arguments: list[Any] = field(default_factory=list) task_queue: str | None = None + target_build: ContinueAsNewTargetBuild | None = None + + def __post_init__(self) -> None: + if self.target_build is not None and not _valid_continue_as_new_target(self.target_build): + raise ValueError("invalid_target_build: use the exact inherited or promoted target") + context = _ACTIVE_WORKFLOW_REPLAY.get() + if self.target_build is not None and context is not None and not context._allow_continue_as_new_target_build: + raise ContinueAsNewTargetUnsupported() def to_server_command( self, @@ -1158,6 +1169,8 @@ def to_server_command( external_storage_threshold_bytes: int | None = None, ) -> dict[str, Any]: cmd: dict[str, Any] = {"type": "continue_as_new"} + if self.target_build is not None: + cmd["target_build"] = self.target_build if self.workflow_type is not None: cmd["workflow_type"] = self.workflow_type cmd["arguments"] = _payload_envelope( @@ -2097,6 +2110,8 @@ def commands_to_server_commands( if isinstance(command, ContinueAsNew): queue = command.task_queue or task_queue server_command = {"type": "continue_as_new", "queue": queue} + if command.target_build is not None: + server_command["target_build"] = command.target_build if command.workflow_type is not None: server_command["workflow_type"] = command.workflow_type server_commands.append(server_command) @@ -2451,6 +2466,7 @@ def __init__( cancel_requested: bool = False, allow_cancellation_scope_authoring: bool = False, _allow_wall_clock: bool = True, + allow_continue_as_new_target_build: bool = False, ) -> None: self._workflow_id = workflow_id self._run_id = run_id @@ -2471,6 +2487,7 @@ def __init__( self._cancellation_replay_time_available = False self._cancellation_shield_depth = 0 self._allow_cancellation_scope_authoring = allow_cancellation_scope_authoring + self._allow_continue_as_new_target_build = allow_continue_as_new_target_build self._cancellation_scope_id = "root" seed = int(hashlib.sha256(run_id.encode()).hexdigest()[:16], 16) self._rng = random.Random(seed) @@ -3147,8 +3164,16 @@ def continue_as_new( *args: Any, workflow_type: str | None = None, task_queue: str | None = None, + target_build: ContinueAsNewTargetBuild | None = None, ) -> ContinueAsNew: - return ContinueAsNew(workflow_type=workflow_type, arguments=list(args), task_queue=task_queue) + """Start the successor on the inherited build or opt into the promotion.""" + if target_build is not None and not _valid_continue_as_new_target(target_build): + raise ValueError("invalid_target_build: use the exact inherited or promoted target") + if target_build is not None and not self._allow_continue_as_new_target_build: + raise ContinueAsNewTargetUnsupported() + return ContinueAsNew( + workflow_type=workflow_type, arguments=list(args), task_queue=task_queue, target_build=target_build, + ) def now(self) -> datetime: """Return the persisted workflow-start time, fixed during replay.""" @@ -3777,6 +3802,7 @@ def replay( allow_cancellation_scope_authoring: bool = False, allow_cancellation_scope_delivery: bool = False, record_parallel_failure_order: bool = False, + allow_continue_as_new_target_build: bool = False, ) -> ReplayOutcome: """Replay ``history_events`` and return the next commands. @@ -3805,6 +3831,7 @@ def replay( allow_cancellation_scope_authoring=allow_cancellation_scope_authoring, allow_cancellation_scope_delivery=allow_cancellation_scope_delivery, record_parallel_failure_order=record_parallel_failure_order, + allow_continue_as_new_target_build=allow_continue_as_new_target_build, ).outcome @@ -4284,6 +4311,41 @@ def _history_event_type(event: Mapping[str, Any]) -> str | None: return value if isinstance(value, str) and value else None +def _recorded_continuation( + events: Iterable[dict[str, Any]], +) -> tuple[ContinueAsNewTargetBuild | None, bool]: + target: ContinueAsNewTargetBuild | None = None + recorded = False + for event in events: + if _history_event_type(event) != "WorkflowContinuedAsNew": + continue + if target is not None: + raise NonDeterministicReplayError( + 0, "one terminal continuation", ["WorkflowContinuedAsNew"], + detail="invalid_continue_as_new_transition: history records multiple continuations", + ) + target = "inherited" + payload = event.get("payload") + if not isinstance(payload, Mapping) or "build_transition" not in payload: + continue + transition = payload["build_transition"] + resolution = transition.get("resolution") if isinstance(transition, Mapping) else None + if ( + not isinstance(transition, Mapping) + or not _valid_continue_as_new_target(resolution) + or any( + key not in transition or (transition[key] is not None and not isinstance(transition[key], str)) + for key in ("from_compatibility", "to_compatibility") + ) + ): + raise NonDeterministicReplayError( + 0, "recorded build transition", ["WorkflowContinuedAsNew"], + detail="invalid_continue_as_new_transition: history lacks a complete build transition", + ) + target, recorded = resolution, True + return target, recorded + + # ``cancellation_reason`` of an ActivityCancelled that the run's own close # recorded (Workflow 2.28.0, workflow#1117 and server#1193). Completing, # failing or continuing as new cancels each activity the workflow never @@ -5310,6 +5372,7 @@ def _replay_state( allow_cancellation_scope_delivery: bool = False, parallel_group_policies: tuple[str, ...] = (), record_parallel_failure_order: bool = False, + allow_continue_as_new_target_build: bool = False, ) -> _ReplayState: _validate_workflow_entrypoint(workflow_cls) _workflow_handler_registries(workflow_cls) @@ -5332,6 +5395,10 @@ def _replay_state( # Retained metadata still requires a qualified consumer when its event is # excluded from semantic outcomes, including run-close settlements. retained_events = list(history_events) + recorded_continuation, recorded_build_transition = _recorded_continuation(retained_events) + can_author_target = ( + allow_continue_as_new_target_build or recorded_continuation is not None or reconstruction_only + ) recorded_group_policies = _read_parallel_group_policies(retained_events, parallel_group_policies) # A run-close cancellation never resolves a select() member, never fails # an all() group and never supplies replay time: the workflow had closed @@ -5640,6 +5707,7 @@ def _replay_state( cancel_requested=cancel_requested, allow_cancellation_scope_authoring=allow_cancellation_scope_authoring, _allow_wall_clock=not events, + allow_continue_as_new_target_build=can_author_target, ) ctx._replay_clock_error = replay_clock_error if workflow_start_time is None else None ctx._schedule_origin = _schedule_origin(events) @@ -6712,6 +6780,36 @@ def _refresh_replay_logging() -> None: except TypeError: raise WorkflowEntryArgumentsMismatchError(workflow_type, "argument_binding_failed") from None + def _terminal_continuation(command: ContinueAsNew, pending_commands: list[Command]) -> list[Command]: + _assert_no_unconsumed_history("continue as new") + target = command.target_build + if target is not None and not _valid_continue_as_new_target(target): + raise ValueError("invalid_target_build: use the exact inherited or promoted target") + if target is not None and not can_author_target: + raise ContinueAsNewTargetUnsupported() + if recorded_continuation is None: + return pending_commands + [command] + if (target or "inherited") != recorded_continuation: + raise NonDeterministicReplayError( + 0, recorded_continuation, ["WorkflowContinuedAsNew"], + detail="continue_as_new_target_changed: workflow chose a different build target on replay", + ) + if recorded_build_transition or target is not None: + if pending_commands: + raise NonDeterministicReplayError( + 0, "recorded continuation", ["WorkflowContinuedAsNew"], + detail="continue_as_new_target_changed: recorded continuation follows new commands", + ) + return [] + return pending_commands + [command] + + def _assert_continuation_replayed() -> None: + if recorded_continuation is not None: + raise NonDeterministicReplayError( + 0, "recorded continuation", ["WorkflowContinuedAsNew"], + detail="continue_as_new_target_changed: workflow finished without its recorded continuation", + ) + # Binding happens outside the application-error path. A TypeError raised # by a successfully bound body is still an actual workflow failure. try: @@ -6720,7 +6818,7 @@ def _refresh_replay_logging() -> None: gen = entry(ctx, *start_input) except NonDeterministicReplayError: raise - except LocalActivityExecutionAborted: + except (LocalActivityExecutionAborted, ContinueAsNewTargetUnsupported): raise except WorkflowCancelled as exc: return _state([_fail_workflow_from_exception(exc)]) @@ -6729,9 +6827,9 @@ def _refresh_replay_logging() -> None: if not hasattr(gen, "__next__"): _validate_workflow_result(gen, workflow_cls) if isinstance(gen, ContinueAsNew): - _assert_no_unconsumed_history("continue as new") - return _state([gen]) + return _state(_terminal_continuation(gen, [])) _assert_no_unconsumed_history("complete workflow") + _assert_continuation_replayed() return _state([CompleteWorkflow(result=gen)]) lifetime.generator = gen @@ -7702,9 +7800,9 @@ def _terminal_state(value: Any, *, include_pending: bool) -> _ReplayState: _consume_terminal_condition_reopens() commands = list(pending) if include_pending else [] if isinstance(value, ContinueAsNew): - _assert_no_unconsumed_history("continue as new") - return _state(commands + [value]) + return _state(_terminal_continuation(value, commands)) _assert_no_unconsumed_history("complete workflow") + _assert_continuation_replayed() return _state(commands + [CompleteWorkflow(result=value)]) def _consume_cancellation(command: Any, boundary: CancellationDelivery) -> _ReplayState | None: @@ -8859,7 +8957,9 @@ def _advance_selection_clock(base: int, size: int, failure: BaseException | None try: return _terminal_state(stop.value, include_pending=True) except Exception as exc: - if isinstance(exc, (NonDeterministicReplayError, InvalidWorkflowDefinition)): + if isinstance(exc, ( + NonDeterministicReplayError, InvalidWorkflowDefinition, ContinueAsNewTargetUnsupported, + )): raise return _state(pending + [_fail_workflow_from_exception(exc)]) except NonDeterministicReplayError as exc: @@ -8868,7 +8968,7 @@ def _advance_selection_clock(base: int, size: int, failure: BaseException | None raise except InvalidWorkflowDefinition: raise - except LocalActivityExecutionAborted: + except (LocalActivityExecutionAborted, ContinueAsNewTargetUnsupported): raise except WorkflowCancelled as exc: return _state(pending + [_fail_workflow_from_exception(exc)]) diff --git a/tests/fixtures/replay_regressions/continue-as-new-promoted-cold-replay.json b/tests/fixtures/replay_regressions/continue-as-new-promoted-cold-replay.json new file mode 100644 index 0000000..d26f56a --- /dev/null +++ b/tests/fixtures/replay_regressions/continue-as-new-promoted-cold-replay.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "continue-as-new-promoted-cold-replay", + "protocol_version": "1.21", + "bindings": ["python"], + "workflow": { + "type": "sdk.promoted-continue-replay", + "workflow_id": "chain", + "run_id": "original-run", + "input": ["cursor"], + "payload_codec": "avro" + }, + "history": [ + { + "event_type": "WorkflowStarted", + "sequence": 1, + "payload": {"workflow_run_id": "original-run", "workflow_type": "sdk.promoted-continue-replay"} + }, + { + "event_type": "WorkflowContinuedAsNew", + "sequence": 2, + "payload": { + "sequence": 1, + "continued_to_run_id": "successor-run", + "continued_to_run_number": 2, + "closed_reason": "continued", + "build_transition": { + "from_compatibility": "build-a", + "to_compatibility": "build-b", + "resolution": "promoted" + } + } + } + ], + "expected": {"command_sequence": []} +} diff --git a/tests/test_continue_as_new_target.py b/tests/test_continue_as_new_target.py new file mode 100644 index 0000000..fccbc8a --- /dev/null +++ b/tests/test_continue_as_new_target.py @@ -0,0 +1,174 @@ +from __future__ import annotations + +import json +from typing import Any + +import httpx +import pytest + +from durable_workflow import Client, ContinueAsNewTargetUnsupported, Worker, serializer, workflow +from durable_workflow.errors import NonDeterministicReplayError +from durable_workflow.workflow import ContinueAsNew, WorkflowContext, commands_to_server_commands, replay +from tests.test_worker import compatible_cluster_info + + +@workflow.defn(name="promoted-continuation") +class PromotedContinuation: + def run(self, ctx: WorkflowContext, state: str) -> ContinueAsNew | str: + if state == "before": + return ctx.continue_as_new("after", target_build="promoted") + return state + + +@workflow.defn(name="inherited-continuation") +class InheritedContinuation: + def run(self, ctx: WorkflowContext) -> ContinueAsNew: + return ctx.continue_as_new("after") + + +def test_replay_respects_the_recorded_target_and_legacy_history() -> None: + recorded = { + "event_type": "WorkflowContinuedAsNew", + "payload": { + "sequence": 1, + "build_transition": { + "from_compatibility": None, "to_compatibility": "build-b", "resolution": "promoted", + }, + }, + } + assert replay(PromotedContinuation, [recorded], ["before"]).commands == [] + with pytest.raises(NonDeterministicReplayError, match="continue_as_new_target_changed"): + replay(InheritedContinuation, [recorded], []) + legacy = {"event_type": "WorkflowContinuedAsNew", "payload": {"sequence": 1}} + assert replay(InheritedContinuation, [legacy], []).commands == [ContinueAsNew(arguments=["after"])] + + successor = {"event_type": "WorkflowStarted", "payload": recorded["payload"]} + assert replay(PromotedContinuation, [successor], ["after"]).commands[0].to_server_command("queue")["type"] == ( + "complete_workflow" + ) + with pytest.raises(ContinueAsNewTargetUnsupported, match="unsupported_target_build"): + replay(PromotedContinuation, [successor], ["before"]) + + +def test_direct_and_batch_serialization_use_the_same_target() -> None: + result = replay(PromotedContinuation, [], ["before"], allow_continue_as_new_target_build=True) + assert result.commands[0].to_server_command("queue")["target_build"] == "promoted" + assert commands_to_server_commands(result.commands, "queue")[0]["target_build"] == "promoted" + assert "target_build" not in ContinueAsNew().to_server_command("queue") + assert "target_build" not in commands_to_server_commands([ContinueAsNew()], "queue")[0] + + +@pytest.mark.parametrize("supported", [True, False]) +async def test_worker_reports_the_refusal_on_the_current_attempt_and_can_retry(supported: bool) -> None: + writes: list[tuple[str, str, dict[str, Any]]] = [] + + def request(req: httpx.Request) -> httpx.Response: + path = req.url.path + if path == "/api/cluster/info": + return httpx.Response(200, json=compatible_cluster_info()) + if path == "/api/worker/register": + assert req.headers["x-durable-workflow-protocol-version"] == "1.20" + assert json.loads(req.content)["capability_manifest"]["continue_as_new_target_build"] == { + "supported": True, "minimum_protocol_version": "1.21", + } + return httpx.Response(201, json={ + "registered": True, "worker_id": "worker", "namespace": "default", "task_queue": "queue", + "protocol_version": "1.21" if supported else "1.20", + "server_capabilities": {"continue_as_new_target_build": supported}, + }) + if path.endswith(("/complete", "/fail")): + body = json.loads(req.content) + writes.append((path, req.headers["x-durable-workflow-protocol-version"], body)) + if path.endswith("/first/complete"): + return httpx.Response(409, json={ + "reason": "promoted_build_unavailable", "retryable": True, "request_admitted": False, + }) + return httpx.Response(200, json={"recorded": True}) + raise AssertionError(f"unexpected request {req.method} {path}") + + async with Client("http://fixture.invalid") as client: + await client._http.aclose() + client._http = httpx.AsyncClient(base_url="http://fixture.invalid", transport=httpx.MockTransport(request)) + worker = Worker(client, task_queue="queue", worker_id="worker", workflows=[PromotedContinuation]) + await worker._register() + task = { + "task_id": "first", "workflow_id": "workflow", "run_id": "run", + "workflow_type": "promoted-continuation", "workflow_task_attempt": 1, "lease_owner": "worker", + "payload_codec": "avro", "arguments": serializer.envelope(["before"]), + "history_events": [{"event_type": "WorkflowStarted"}], + } + assert await worker._run_workflow_task(task) is None + if not supported: + assert writes == [] + return + result = await worker._run_workflow_task({**task, "task_id": "second", "workflow_task_attempt": 2}) + assert result is not None and result[0]["target_build"] == "promoted" + + assert [path.rsplit("/", 2)[-2:] for path, _, _ in writes] == [ + ["first", "complete"], ["first", "fail"], ["second", "complete"], + ] + assert [version for _, version, _ in writes] == ["1.21"] * 3 + assert writes[1][2]["failure"]["reason"] == "promoted_build_unavailable" + assert writes[1][2]["failure"]["message"] == "The promoted build is unavailable for the successor workflow." + assert "stack_trace" not in writes[1][2]["failure"] + assert [(body["lease_owner"], body["workflow_task_attempt"]) for _, _, body in writes] == [ + ("worker", 1), ("worker", 1), ("worker", 2), + ] + + +async def test_client_requires_exact_value_and_current_registration() -> None: + registrations = iter([ + ("1.20", True, "default", "queue"), + ("1.21", "true", "default", "queue"), + ("1.21", True, "different-namespace", "queue"), + ("1.21", True, "default", "different-queue"), + ("1.21", True, "default", "queue"), + ("1.21", False, "default", "queue"), + ]) + completions = [] + + def request(req: httpx.Request) -> httpx.Response: + if req.url.path == "/api/worker/register": + version, flag, namespace, queue = next(registrations) + return httpx.Response(201, json={ + "registered": True, "worker_id": "worker", "namespace": namespace, "task_queue": queue, + "protocol_version": version, + "server_capabilities": {"continue_as_new_target_build": flag}, + }) + if req.url.path == "/api/cluster/info": + return httpx.Response(200, json=compatible_cluster_info()) + completions.append((req.headers["x-durable-workflow-protocol-version"], json.loads(req.content))) + return httpx.Response(200, json={"recorded": True}) + + async with Client("http://fixture.invalid") as client: + await client._http.aclose() + client._http = httpx.AsyncClient(base_url="http://fixture.invalid", transport=httpx.MockTransport(request)) + + async def complete(command: dict[str, Any], *, owner: str = "worker") -> None: + await client.complete_workflow_task( + task_id="task", lease_owner=owner, workflow_task_attempt=1, commands=[command], + ) + + explicit = {"type": "continue_as_new", "target_build": "inherited"} + for _ in range(4): + await client.register_worker(worker_id="worker", task_queue="queue", capability_manifest={}) + with pytest.raises(ContinueAsNewTargetUnsupported): + await complete(explicit) + await client.register_worker(worker_id="worker", task_queue="queue", capability_manifest={}) + with pytest.raises(ContinueAsNewTargetUnsupported): + await complete(explicit, owner="unregistered") + for invalid in (None, False, [], 1, "Promoted", "promoted "): + with pytest.raises(ValueError, match="invalid_target_build"): + await complete({"type": "continue_as_new", "target_build": invalid}) + assert completions == [] + + await complete(explicit) + await complete({"type": "continue_as_new"}) + await complete({"type": "complete_workflow"}) + await client.register_worker(worker_id="worker", task_queue="queue", capability_manifest={}) + with pytest.raises(ContinueAsNewTargetUnsupported): + await complete(explicit) + + assert [protocol for protocol, _ in completions] == ["1.21", "1.21", "1.20"] + assert completions[0][1]["commands"][0]["target_build"] == "inherited" + assert "target_build" not in completions[1][1]["commands"][0] diff --git a/tests/test_replay_regression_corpus.py b/tests/test_replay_regression_corpus.py index ef94b0b..6b7c901 100644 --- a/tests/test_replay_regression_corpus.py +++ b/tests/test_replay_regression_corpus.py @@ -24,6 +24,7 @@ from durable_workflow.retry_policy import TransportRetryPolicy from durable_workflow.worker import RECORD_PARALLEL_FAILURE_ORDER_ENV from durable_workflow.workflow import ( + ContinueAsNew, LocalActivityExecutionAborted, WorkflowContext, commands_to_server_commands, @@ -101,6 +102,12 @@ FIXTURE_DIR = Path(__file__).parent / "fixtures" / "replay_regressions" +@workflow.defn(name="sdk.promoted-continue-replay") +class PromotedContinueReplay: + def run(self, ctx: WorkflowContext, cursor: str) -> ContinueAsNew: + return ctx.continue_as_new(cursor, target_build="promoted") + + @workflow.defn(name="sdk.query-task-dispatch") class QueryAuthorityWorkflow: calls = 0 @@ -440,6 +447,7 @@ def run(self, ctx: WorkflowContext, message: str) -> None: BlankFailureWorkflow, IdentityAcrossReplay, IdentityContinueAsNew, + PromotedContinueReplay, PersistedClockWorkflow, RedriveChangedStageWorkflow, RedriveSignalWorkflow, diff --git a/tests/test_worker.py b/tests/test_worker.py index 10090aa..db6ffc9 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -457,6 +457,10 @@ async def test_register(self, mock_client: AsyncMock) -> None: "minimum_protocol_version": "1.18", "reason": "sticky_cache_disabled", }, + "continue_as_new_target_build": { + "supported": True, + "minimum_protocol_version": "1.21", + }, }, "task_slots": { "workflow_available": 10,