diff --git a/CHANGELOG.md b/CHANGELOG.md index 392a369..f00b927 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `Replayer.replay()`, `replay_history()` and `apply_update()` accept the task's object as `replay_clock_entry`. `ctx.now()` still returns the fixed start time. (durable-workflow/.github#215) +- Workers with cooperative cancellation enabled advertise the `timeout_cleanup` + capability, version 1: `capabilities` lists it and `capability_manifest` + carries `{supported: true, minimum_protocol_version: "1.20", version: 1}`. A + native Server can then admit starts that reserve time for deadline-triggered + timeout cleanup on their queue. When workflow code lets the delivered + `WorkflowTimeoutCleanupRequested` escape, uncaught or re-raised, the + `fail_workflow` command carries `failure.interruption: "timeout_cleanup"`, + and the Server records the cleanup as completed. An exception the + application constructs or wraps, a compensation failure and an ordinary or + explicit `cause: "cancellation"` request stay ordinary failures, which the + Server records as failed cleanup. `FailWorkflow` gains an optional + `interruption` field. Workers without cooperative cancellation are unchanged + and never send the marker; listing `timeout_cleanup` without + `cooperative_cancellation` raises `ValueError`. + ([Server #1201](https://github.com/durable-workflow/server/issues/1201)) ## [2.23.1] - 2026-11-24 diff --git a/docs/cooperative-cancellation-design.md b/docs/cooperative-cancellation-design.md index 4bd79ac..ebbdba8 100644 --- a/docs/cooperative-cancellation-design.md +++ b/docs/cooperative-cancellation-design.md @@ -42,7 +42,33 @@ work deadline through the same cooperative delivery. The context then has `except WorkflowCancelled:` handlers therefore run on timeout too. Like `WorkflowCancelled`, it derives from `BaseException`, never from `asyncio.CancelledError`. Test `cause`, the cross-SDK discriminator, rather than -the type, to tell the two apart. The run still ends timed out. +the type, to tell the two apart. + +A worker registered with the `cooperative_cancellation` capability advertises +the `timeout_cleanup` capability, version 1 +([server#1201](https://github.com/durable-workflow/server/issues/1201)). The +Server admits a start with `timeout_cleanup_seconds` only on a task queue where +such a worker is live, and refuses it otherwise with +`timeout_cleanup_not_supported`. A worker without cooperative cancellation +does not advertise it, and listing `timeout_cleanup` without +`cooperative_cancellation` raises `ValueError`. + +The run always ends timed out. How workflow code finishes cleanup sets the +recorded cleanup outcome: + +- Returning, or letting the delivered `WorkflowTimeoutCleanupRequested` escape + (uncaught, re-raised, or raised again by `throw_if_cancellation_requested()`), + records `completed`. For the escaped interruption the worker adds + `failure.interruption: "timeout_cleanup"` to its `fail_workflow` command. The + marker is sent only for the exception object the runtime raised for this + run's root request with `cause: "timeout"`. It is never sent for an exception + the application constructs, or for a different exception raised `from` the + interruption, even of the same type. +- Raising any other exception, such as a failed compensation, records + `failed`, with the failure linked. +- Running past the cleanup deadline records `expired`. + +This support is experimental. It is opt-in for each start and for each worker. `cause` is `None` (absent) or `"cancellation"` for an ordinary request; any other value is refused. `cleanup_deadline_at` is the cleanup deadline. The diff --git a/src/durable_workflow/_timeout_cleanup.py b/src/durable_workflow/_timeout_cleanup.py new file mode 100644 index 0000000..c9127e5 --- /dev/null +++ b/src/durable_workflow/_timeout_cleanup.py @@ -0,0 +1,63 @@ +"""Worker side of deadline-triggered timeout cleanup (server#1201, workflow#863). + +A worker that delivers cooperative cancellation advertises ``timeout_cleanup`` +version 1, so the Server admits starts that reserve cleanup time on its queue. +When the engine's timeout request reaches workflow code as +:class:`~durable_workflow.errors.WorkflowTimeoutCleanupRequested` and the +workflow lets that exception escape, uncaught or re-raised, the +``fail_workflow`` command carries ``failure.interruption: "timeout_cleanup"``. +The Server then records the cleanup as completed, and the run still closes as +timed out. Any other failure, including one that wraps the interruption, is an +ordinary failure, which the Server records as failed cleanup. The marker never +starts cleanup; the Server accepts it only while the run's own engine timeout +request is active. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +from .cancellation import CancellationContext +from .errors import WorkflowTimeoutCleanupRequested + +CAPABILITY = "timeout_cleanup" +INTERRUPTION = "timeout_cleanup" +MINIMUM_PROTOCOL_VERSION = "1.20" +VERSION = 1 + + +def manifest_entry() -> dict[str, Any]: + """The registration ``capability_manifest`` entry native Server admits.""" + return {"supported": True, "minimum_protocol_version": MINIMUM_PROTOCOL_VERSION, "version": VERSION} + + +def failure_interruption( + failure: BaseException, *, delivered: Sequence[BaseException], run_id: str, +) -> str | None: + """The portable marker for an escaped timeout interruption, else ``None``. + + Only the exception object the runtime raised for this run's root request + with ``cause: "timeout"`` qualifies. An exception the application + constructs, a different exception raised from or wrapping the delivered + one, an ordinary or explicit ``cause: "cancellation"`` request and a + descendant or scoped request are not marked. The type alone never decides. + """ + if not isinstance(failure, WorkflowTimeoutCleanupRequested): + return None + if not any(failure is candidate for candidate in delivered): + return None + context = failure.context + if ( + not isinstance(context, CancellationContext) + or not context.is_timeout + or context.scope_origin is not None + or failure.request_id is None + or failure.request_id != context.request_id + or context.request_id != context.root_request_id + or context.parent_request_id is not None + or not run_id + or context.root_workflow_run_id != run_id + ): + return None + return INTERRUPTION diff --git a/src/durable_workflow/worker.py b/src/durable_workflow/worker.py index cf8c111..dcfe2bf 100644 --- a/src/durable_workflow/worker.py +++ b/src/durable_workflow/worker.py @@ -18,6 +18,7 @@ import asyncio import contextlib import contextvars +import dataclasses import hashlib import inspect import json @@ -41,7 +42,7 @@ import httpx -from . import _condition_input_order, _continue_as_new, serializer +from . import _condition_input_order, _continue_as_new, _timeout_cleanup, serializer from ._activity_lease import ( ACTIVITY_LEASE_RENEWAL_EXHAUSTED, ActivityLeaseAuthority, @@ -1425,6 +1426,8 @@ def __init__( if ("nexus_cooperative_cancellation" in self.capabilities and "cooperative_cancellation" not in self.capabilities): raise ValueError("Nexus cooperative cancellation requires cooperative_cancellation capability") + if _timeout_cleanup.CAPABILITY in self.capabilities and "cooperative_cancellation" not in self.capabilities: + raise ValueError("timeout cleanup requires cooperative_cancellation capability") if any(not capability for capability in self.capabilities): raise ValueError("worker capabilities must be non-empty strings") self.worker_id = worker_id or f"py-worker-{uuid.uuid4().hex[:8]}" @@ -1747,6 +1750,9 @@ async def _register(self) -> None: capabilities.extend(self.capabilities) if self._nexus_cooperative_cancellation_supported and "nexus_cooperative_cancellation" not in capabilities: capabilities.append("nexus_cooperative_cancellation") + # Timeout cleanup is delivered through cooperative cancellation (server#1201). + if self._cooperative_cancellation_supported and _timeout_cleanup.CAPABILITY not in capabilities: + capabilities.append(_timeout_cleanup.CAPABILITY) if ( self._local_activity_cancellation_policies and "prepared_local_activity_cancellation_policies" not in capabilities @@ -1794,6 +1800,8 @@ async def _register(self) -> None: "implementation": "owned_workflow_run_canonical_delivery", "binding_kinds": ["workflow_run"], }} if self._nexus_cooperative_cancellation_supported else {}), + **({_timeout_cleanup.CAPABILITY: _timeout_cleanup.manifest_entry()} + if self._cooperative_cancellation_supported else {}), **({"prepared_local_activities": { "supported": True, "minimum_protocol_version": "1.20", "implementation": "durable_sequential_admission", @@ -3217,6 +3225,13 @@ def execute_local(command: RecordLocalActivity) -> Any: return None workflow_commands = list(outcome.commands) + if not self._cooperative_cancellation_supported: + # Only a worker that advertised timeout_cleanup may send its marker (server#1201). + workflow_commands = [ + dataclasses.replace(command, interruption=None) + if isinstance(command, FailWorkflow) and command.interruption is not None else command + for command in workflow_commands + ] if not workflow_commands and _condition_input_order.PENDING_INPUT in task: await self.client.fail_workflow_task( task_id=task_id, diff --git a/src/durable_workflow/workflow.py b/src/durable_workflow/workflow.py index 8391374..1c21cbc 100644 --- a/src/durable_workflow/workflow.py +++ b/src/durable_workflow/workflow.py @@ -36,7 +36,7 @@ from pathlib import PureWindowsPath from typing import Any, TypeVar, cast -from . import _condition_input_order, replay_clock, serializer +from . import _condition_input_order, _timeout_cleanup, replay_clock, serializer from ._cancellation_scope import CancellationScopeHistory, scope_identity from ._cancellation_scope_history import ( CancellationScopeDeliveryIntent, @@ -79,6 +79,7 @@ WorkflowEntryArgumentsMismatchError, WorkflowPayloadDecodeError, WorkflowSourceLocation, + WorkflowTimeoutCleanupRequested, _cancellation_requested, validate_signal_name, ) @@ -1046,6 +1047,8 @@ class FailWorkflow: non_retryable: bool = False failed_step_sequence: int | None = None failed_activity_execution_id: str | None = None + interruption: str | None = None + """``"timeout_cleanup"`` when the delivered timeout interruption escaped workflow code (server#1201).""" def to_server_command( self, @@ -1070,6 +1073,8 @@ def to_server_command( if self.failed_step_sequence is not None and self.failed_activity_execution_id is not None: cmd["failed_step_sequence"] = self.failed_step_sequence cmd["failed_activity_execution_id"] = self.failed_activity_execution_id + if self.interruption is not None: + cmd["failure"] = {"interruption": self.interruption} return cmd @@ -2504,6 +2509,8 @@ def __init__( self._cancel_requested = bool(cancel_requested) self._cancellation_request_id: str | None = None self._cancellation_context: CancellationContext | ScopedCancellationContext | None = None + # Timeout interruptions this runtime raised, compared by identity (server#1201). + self._delivered_timeout_interruptions: list[WorkflowCancelled] = [] self._scope_cancellation_states: dict[str, ScopedCancellationContext] = {} self._scope_cleanup_proofs: dict[str, dict[str, str]] = {} self._cancellation_replay_time: datetime | None = None @@ -2665,11 +2672,29 @@ def is_cancellation_requested(self) -> bool: def throw_if_cancellation_requested(self) -> None: """Raise :class:`WorkflowCancelled` at an explicit safe point.""" if self._cancel_requested and self._cancellation_shield_depth == 0: - raise _cancellation_requested( + raise self._delivered_cancellation( "workflow cancellation was requested", request_id=self._cancellation_request_id, context=self._cancellation_context, ) + def _delivered_cancellation( + self, message: str, *, request_id: str | None, + context: CancellationContext | ScopedCancellationContext | None, + ) -> WorkflowCancelled: + """The exception the runtime raises for a delivered request, remembered when it is a timeout.""" + exception = _cancellation_requested(message, request_id=request_id, context=context) + if isinstance(exception, WorkflowTimeoutCleanupRequested): + self._delivered_timeout_interruptions.append(exception) + return exception + + def _workflow_failure(self, exception: BaseException) -> FailWorkflow: + """The ``fail_workflow`` command for an exception that escaped workflow code.""" + command = _fail_workflow_from_exception(exception) + command.interruption = _timeout_cleanup.failure_interruption( + exception, delivered=self._delivered_timeout_interruptions, run_id=self._run_id, + ) + return command + @property def cancellation_context(self) -> CancellationContext | ScopedCancellationContext | None: """Original metadata, visible only at committed cancellation delivery.""" @@ -8004,7 +8029,7 @@ def _consume_cancellation(command: Any, boundary: CancellationDelivery) -> _Repl authored_sequence += 1 try: _refresh_replay_logging() - advanced_cmd = _resume_business(gen.throw, _cancellation_requested( + advanced_cmd = _resume_business(gen.throw, ctx._delivered_cancellation( "workflow cancellation was requested", request_id=boundary.request_id, context=ctx._cancellation_context, )) @@ -9197,7 +9222,7 @@ def _advance_selection_clock(base: int, size: int, failure: BaseException | None except (LocalActivityExecutionAborted, ContinueAsNewTargetUnsupported): raise except WorkflowCancelled as exc: - return _state(pending + [_fail_workflow_from_exception(exc)]) + return _state(pending + [ctx._workflow_failure(exc)]) except Exception as exc: return _state(pending + [_fail_workflow_from_exception(exc)]) finally: diff --git a/tests/fixtures/replay_regressions/cooperative-timeout-cleanup-interruption-marker.json b/tests/fixtures/replay_regressions/cooperative-timeout-cleanup-interruption-marker.json new file mode 100644 index 0000000..de5347a --- /dev/null +++ b/tests/fixtures/replay_regressions/cooperative-timeout-cleanup-interruption-marker.json @@ -0,0 +1,135 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "cooperative-timeout-cleanup-interruption-marker", + "protocol_version": "1.20", + "bindings": [ + "python" + ], + "workflow": { + "type": "tests.replay.cooperative-timeout-cleanup-interruption", + "input": [], + "payload_codec": "avro", + "run_id": "run-1" + }, + "history": [ + { + "event_type": "TimerScheduled", + "payload": { + "sequence": 1, + "timer_kind": "durable_timer", + "delay_seconds": 120 + } + }, + { + "event_type": "WorkflowTimeoutCleanupStarted", + "workflow_command_id": "req-1", + "recorded_at": "2026-11-13T00:01:00Z", + "payload": { + "workflow_command_id": "req-1", + "timeout_kind": "execution", + "work_deadline_at": "2026-11-13T00:01:00.000000Z", + "cleanup_deadline_at": "2026-11-13T00:01:10.000000Z", + "hard_deadline_at": "2026-11-13T00:01:10.000000Z", + "detected_at": "2026-11-13T00:01:00.000000Z" + } + }, + { + "event_type": "CooperativeCancellationRequested", + "workflow_command_id": "req-1", + "recorded_at": "2026-11-13T00:01:00Z", + "payload": { + "workflow_command_id": "req-1", + "workflow_instance_id": "instance-1", + "workflow_run_id": "run-1", + "command_type": "request_cancellation", + "reason": "Workflow work deadline passed; timeout cleanup requested.", + "cleanup_deadline_at": "2026-11-13T00:01:10.000000Z", + "cancellation": { + "schema": "durable-workflow.cancellation-context/v1", + "request_id": "req-1", + "root_request_id": "req-1", + "root_workflow_instance_id": "instance-1", + "root_workflow_run_id": "run-1", + "parent_request_id": null, + "reason": "Workflow work deadline passed; timeout cleanup requested.", + "requester": { + "type": "system", + "id": "timeout_cleanup" + }, + "source": "system", + "requested_at": "2026-11-13T00:01:00.000000Z", + "cleanup_deadline_at": "2026-11-13T00:01:10.000000Z", + "lineage": [ + { + "request_id": "req-1", + "workflow_instance_id": "instance-1", + "workflow_run_id": "run-1" + } + ], + "cause": "timeout" + } + } + }, + { + "event_type": "CooperativeCancellationDelivered", + "workflow_command_id": "req-1", + "payload": { + "workflow_command_id": "req-1", + "workflow_run_id": "run-1", + "sequence": 1, + "call_kind": "timer", + "cancellation": { + "schema": "durable-workflow.cancellation-context/v1", + "request_id": "req-1", + "root_request_id": "req-1", + "root_workflow_instance_id": "instance-1", + "root_workflow_run_id": "run-1", + "parent_request_id": null, + "reason": "Workflow work deadline passed; timeout cleanup requested.", + "requester": { + "type": "system", + "id": "timeout_cleanup" + }, + "source": "system", + "requested_at": "2026-11-13T00:01:00.000000Z", + "cleanup_deadline_at": "2026-11-13T00:01:10.000000Z", + "lineage": [ + { + "request_id": "req-1", + "workflow_instance_id": "instance-1", + "workflow_run_id": "run-1" + } + ], + "cause": "timeout" + } + } + }, + { + "event_type": "TimerScheduled", + "payload": { + "sequence": 2, + "timer_kind": "durable_timer", + "delay_seconds": 1 + } + }, + { + "event_type": "TimerFired", + "payload": { + "sequence": 2 + } + } + ], + "expected": { + "command_sequence": [ + { + "type": "fail_workflow", + "command_type": "FailWorkflow", + "exception_type": "WorkflowTimeoutCleanupRequested", + "failure": { + "interruption": "timeout_cleanup" + } + } + ] + } +} diff --git a/tests/test_replay_regression_corpus.py b/tests/test_replay_regression_corpus.py index 20766f3..06844f2 100644 --- a/tests/test_replay_regression_corpus.py +++ b/tests/test_replay_regression_corpus.py @@ -349,6 +349,20 @@ def run(self, ctx: WorkflowContext): # type: ignore[no-untyped-def] return "not cancelled" +@workflow.defn(name="tests.replay.cooperative-timeout-cleanup-interruption") +class CooperativeTimeoutCleanupInterruptionWorkflow: + """Cleanup runs shielded, then the delivered timeout interruption escapes (server#1201).""" + + def run(self, ctx: WorkflowContext): # type: ignore[no-untyped-def] + try: + yield ctx.start_timer(120) + except WorkflowCancelled: + with ctx.cancellation_shield(): + yield ctx.start_timer(1) + raise + return "not cancelled" + + @workflow.defn(name="tests.replay.child-policy-author") class ChildPolicyAuthorWorkflow: def run(self, ctx: WorkflowContext): # type: ignore[no-untyped-def] @@ -470,6 +484,7 @@ def run(self, ctx: WorkflowContext, message: str) -> None: ColdReplacementSatisfiedConditionWorkflow, CooperativeReopenedConditionCleanupWorkflow, CooperativeTimeoutCleanupCauseWorkflow, + CooperativeTimeoutCleanupInterruptionWorkflow, GoldenSagaCompensationWorkflow, GoldenSignalWaitWorkflow, GoldenSingleActivityWorkflow, diff --git a/tests/test_timeout_cleanup.py b/tests/test_timeout_cleanup.py new file mode 100644 index 0000000..b58d338 --- /dev/null +++ b/tests/test_timeout_cleanup.py @@ -0,0 +1,430 @@ +"""Worker side of deadline-triggered timeout cleanup (server#1201). + +A cooperative worker advertises ``timeout_cleanup`` version 1. Only the +delivered root timeout interruption that escapes workflow code, uncaught or +re-raised, adds ``failure.interruption: "timeout_cleanup"`` to +``fail_workflow``. Every other failure stays an ordinary failure. +""" + +from __future__ import annotations + +from collections.abc import Callable +from copy import deepcopy +from typing import Any + +import pytest + +from durable_workflow import ( + CancellationContext, + WorkflowCancelled, + WorkflowTimeoutCleanupRequested, + serializer, + workflow, +) +from durable_workflow._failure_reporting import bound_failure_request +from durable_workflow._timeout_cleanup import failure_interruption, manifest_entry +from durable_workflow.errors import _cancellation_requested +from durable_workflow.worker import Worker +from durable_workflow.workflow import CompleteWorkflow, FailWorkflow, WorkflowContext, replay +from tests.test_cooperative_cancellation import observation +from tests.test_cooperative_cancellation_worker import ClaimServer + +MARKER = {"interruption": "timeout_cleanup"} + + +def context_snapshot(cause: str | None = "timeout", **overrides: Any) -> dict[str, Any]: + snapshot: dict[str, Any] = { + "schema": "durable-workflow.cancellation-context/v1", + "request_id": "request-1", + "root_request_id": "request-1", + "root_workflow_instance_id": "workflow-1", + "root_workflow_run_id": "run-1", + "parent_request_id": None, + "reason": "Workflow work deadline passed; timeout cleanup requested.", + "requester": {"type": "system", "id": "timeout_cleanup"}, + "source": "system", + "requested_at": "2026-09-30T12:00:00.000000Z", + "cleanup_deadline_at": "2026-09-30T12:10:00.000000Z", + "lineage": [{"request_id": "request-1", "workflow_instance_id": "workflow-1", "workflow_run_id": "run-1"}], + **({} if cause is None else {"cause": cause}), + } + snapshot.update(overrides) + return snapshot + + +def cleanup_started() -> dict[str, Any]: + return { + "event_type": "WorkflowTimeoutCleanupStarted", + "workflow_command_id": "request-1", + "recorded_at": "2026-09-30T12:00:00.000100Z", + "payload": { + "workflow_command_id": "request-1", "timeout_kind": "execution", + "work_deadline_at": "2026-09-30T12:00:00.000000Z", "cleanup_deadline_at": "2026-09-30T12:10:00.000000Z", + "hard_deadline_at": "2026-09-30T12:10:00.000000Z", "detected_at": "2026-09-30T12:00:00.000000Z", + }, + } + + +def requested(cause: str | None = "timeout") -> dict[str, Any]: + return { + "event_type": "CooperativeCancellationRequested", + "workflow_command_id": "request-1", + "recorded_at": "2026-09-30T12:00:00.000120Z", + "payload": { + "workflow_command_id": "request-1", "workflow_instance_id": "workflow-1", "workflow_run_id": "run-1", + "command_type": "request_cancellation", + "reason": "Workflow work deadline passed; timeout cleanup requested.", + "cleanup_deadline_at": "2026-09-30T12:10:00.000000Z", "cancellation": context_snapshot(cause), + }, + } + + +def delivered(cause: str | None = "timeout", sequence: int = 1) -> dict[str, Any]: + return { + "event_type": "CooperativeCancellationDelivered", + "workflow_command_id": "request-1", + "payload": { + "workflow_command_id": "request-1", "workflow_run_id": "run-1", "sequence": sequence, + "call_kind": "timer", "cancellation": context_snapshot(cause), + }, + } + + +def history(cause: str | None = "timeout", *, started: bool = True) -> list[dict[str, Any]]: + """History as native records it: the cleanup event only for an engine timeout request.""" + events = [{"event_type": "TimerScheduled", "payload": {"sequence": 1, "delay_seconds": 30}}] + if started: + events.append(cleanup_started()) + return [*events, requested(cause), delivered(cause)] + + +def shielded_cleanup(sequence: int = 2) -> list[dict[str, Any]]: + return [ + {"event_type": "TimerScheduled", "payload": {"sequence": sequence, "delay_seconds": 1}}, + {"event_type": "TimerFired", "payload": {"sequence": sequence}}, + ] + + +class CompensationFailed(Exception): + pass + + +def _uncaught(ctx: WorkflowContext): # type: ignore[no-untyped-def] + yield ctx.start_timer(30) + + +def _rethrown_after_compensation(ctx: WorkflowContext): # type: ignore[no-untyped-def] + try: + yield ctx.start_timer(30) + except WorkflowCancelled: + with ctx.cancellation_shield(): + yield ctx.start_timer(1) + raise + + +def _rethrown_by_name(ctx: WorkflowContext): # type: ignore[no-untyped-def] + try: + yield ctx.start_timer(30) + except WorkflowTimeoutCleanupRequested as interrupted: + raise interrupted + + +def _thrown_at_safe_point(ctx: WorkflowContext): # type: ignore[no-untyped-def] + try: + yield ctx.start_timer(30) + except WorkflowCancelled: + with ctx.cancellation_shield(): + yield ctx.start_timer(1) + ctx.throw_if_cancellation_requested() + + +def _compensation_failure(ctx: WorkflowContext): # type: ignore[no-untyped-def] + try: + yield ctx.start_timer(30) + except WorkflowCancelled: + raise CompensationFailed("compensation failed") from None + + +def _wrapped(ctx: WorkflowContext): # type: ignore[no-untyped-def] + try: + yield ctx.start_timer(30) + except WorkflowCancelled as interrupted: + raise CompensationFailed("wrapped") from interrupted + + +def _wrapped_in_the_same_type(ctx: WorkflowContext): # type: ignore[no-untyped-def] + try: + yield ctx.start_timer(30) + except WorkflowCancelled as interrupted: + raise WorkflowTimeoutCleanupRequested( + request_id=interrupted.request_id, context=interrupted.context, + ) from interrupted + + +def _constructed(ctx: WorkflowContext): # type: ignore[no-untyped-def] + yield ctx.start_timer(30) + raise WorkflowTimeoutCleanupRequested( + request_id="request-1", context=CancellationContext.from_dict(context_snapshot()), + ) + + +def _returns(ctx: WorkflowContext): # type: ignore[no-untyped-def] + try: + yield ctx.start_timer(30) + except WorkflowTimeoutCleanupRequested: + return "compensated" + return "finished" + + +def _workflow(body: Callable[[WorkflowContext], Any], name: str) -> type: + def run(self: Any, ctx: WorkflowContext): # type: ignore[no-untyped-def] + return (yield from body(ctx)) + + return workflow.defn(name=name)(type(name.replace("-", "_"), (), {"run": run})) + + +def _single_failure(commands: list[Any]) -> FailWorkflow: + assert len(commands) == 1 and isinstance(commands[0], FailWorkflow), commands + return commands[0] + + +@pytest.mark.parametrize("body,events,exception_type", [ + (_uncaught, history(), "WorkflowTimeoutCleanupRequested"), + (_rethrown_after_compensation, [*history(), *shielded_cleanup()], "WorkflowTimeoutCleanupRequested"), + (_rethrown_by_name, history(), "WorkflowTimeoutCleanupRequested"), + (_thrown_at_safe_point, [*history(), *shielded_cleanup()], "WorkflowTimeoutCleanupRequested"), +], ids=["uncaught", "rethrown-after-compensation", "rethrown-by-name", "safe-point"]) +def test_the_escaped_delivered_timeout_interruption_is_marked( + body: Callable[[WorkflowContext], Any], events: list[dict[str, Any]], exception_type: str, +) -> None: + failure = _single_failure(replay(_workflow(body, "timeout-marked"), events, [], run_id="run-1").commands) + + assert failure.exception_type == exception_type + assert failure.interruption == "timeout_cleanup" + assert failure.to_server_command("queue")["failure"] == MARKER + + +@pytest.mark.parametrize("body,events,cause,exception_type", [ + (_compensation_failure, history(), "timeout", "CompensationFailed"), + (_wrapped, history(), "timeout", "CompensationFailed"), + (_wrapped_in_the_same_type, history(), "timeout", "WorkflowTimeoutCleanupRequested"), + (_constructed, [ + {"event_type": "TimerScheduled", "payload": {"sequence": 1, "delay_seconds": 30}}, + {"event_type": "TimerFired", "payload": {"sequence": 1}}, + ], None, "WorkflowTimeoutCleanupRequested"), + (_uncaught, history(None, started=False), None, "WorkflowCancelled"), + (_uncaught, history("cancellation", started=False), "cancellation", "WorkflowCancelled"), + (_rethrown_after_compensation, [*history(None, started=False), *shielded_cleanup()], None, "WorkflowCancelled"), +], ids=[ + "compensation-failure", "wrapped", "wrapped-in-the-same-type", "constructed", + "ordinary-cancellation", "explicit-cancellation-cause", "rethrown-ordinary-cancellation", +]) +def test_other_failures_stay_ordinary_failures( + body: Callable[[WorkflowContext], Any], events: list[dict[str, Any]], cause: str | None, exception_type: str, +) -> None: + failure = _single_failure(replay(_workflow(body, "timeout-unmarked"), events, [], run_id="run-1").commands) + + assert failure.exception_type == exception_type + assert failure.interruption is None + assert "failure" not in failure.to_server_command("queue") + + +def test_cleanup_that_returns_completes_and_replays_the_cleanup_event() -> None: + outcome = replay(_workflow(_returns, "timeout-returns"), history(), [], run_id="run-1") + + assert outcome.commands == [CompleteWorkflow("compensated")] + + +def test_offline_replay_without_the_run_identity_does_not_mark() -> None: + failure = _single_failure(replay(_workflow(_uncaught, "timeout-offline"), history(), []).commands) + + assert failure.exception_type == "WorkflowTimeoutCleanupRequested" + assert failure.interruption is None + + +def test_the_rule_needs_the_runtime_delivered_root_timeout_object() -> None: + timeout = CancellationContext.from_dict(context_snapshot()) + interruption = _cancellation_requested("cancelled", request_id="request-1", context=timeout) + assert isinstance(interruption, WorkflowTimeoutCleanupRequested) + assert failure_interruption(interruption, delivered=[interruption], run_id="run-1") == "timeout_cleanup" + + descendant = CancellationContext.from_dict(context_snapshot( + request_id="request-child", parent_request_id="request-1", + lineage=[*context_snapshot()["lineage"], { + "request_id": "request-child", "workflow_instance_id": "child", "workflow_run_id": "child-run", + }], + )) + another_request = WorkflowTimeoutCleanupRequested(request_id="request-2", context=timeout) + descendant_request = WorkflowTimeoutCleanupRequested(request_id="request-child", context=descendant) + for case, failure, run_id in [ + ("constructed without context", WorkflowTimeoutCleanupRequested(), "run-1"), + ("constructed with only a request", WorkflowTimeoutCleanupRequested(request_id="request-1"), "run-1"), + ("constructed copy", WorkflowTimeoutCleanupRequested(request_id="request-1", context=timeout), "run-1"), + ("another request", another_request, "run-1"), + ("descendant", descendant_request, "child-run"), + ("another run", interruption, "run-2"), + ("no run", interruption, ""), + ]: + assert failure_interruption( + failure, delivered=[interruption, another_request, descendant_request], run_id=run_id, + ) is None, case + ordinary = _cancellation_requested( + "cancelled", request_id="request-1", context=CancellationContext.from_dict(context_snapshot(None)), + ) + wrapped = RuntimeError("wrapped") + wrapped.__cause__ = interruption + for case, failure in [("ordinary", ordinary), ("wrapped", wrapped)]: + assert failure_interruption(failure, delivered=[ordinary, wrapped, interruption], run_id="run-1") is None, case + + +def test_failure_report_bounding_keeps_the_marker() -> None: + command = FailWorkflow( + "x" * (200 * 1024), exception_type="WorkflowTimeoutCleanupRequested", + exception={"type": "WorkflowTimeoutCleanupRequested", "details": "y" * (200 * 1024)}, + interruption="timeout_cleanup", + ).to_server_command("queue") + body = {"lease_owner": "worker", "workflow_task_attempt": 1, "commands": [command]} + + bounded = bound_failure_request("/worker/workflow-tasks/task-1/complete", body) + + assert bounded["commands"][0]["failure"] == MARKER + assert len(bounded["commands"][0]["message"].encode()) < len(command["message"].encode()) + + +# Worker registration and delivery. + + +async def test_cooperative_registration_advertises_timeout_cleanup_version_one( + monkeypatch: pytest.MonkeyPatch, +) -> None: + server = ClaimServer() + await server.worker(monkeypatch) + registration = server.client.register_worker.await_args.kwargs + + assert "timeout_cleanup" in registration["capabilities"] + assert registration["capability_manifest"]["timeout_cleanup"] == { + "supported": True, "minimum_protocol_version": "1.20", "version": 1, + } + assert registration["capability_manifest"]["timeout_cleanup"] == manifest_entry() + + +async def test_an_explicit_capability_is_listed_once(monkeypatch: pytest.MonkeyPatch) -> None: + server = ClaimServer() + await server.worker(monkeypatch, capabilities=["cooperative_cancellation", "timeout_cleanup"]) + + assert server.client.register_worker.await_args.kwargs["capabilities"].count("timeout_cleanup") == 1 + + +async def test_a_worker_without_cooperative_cancellation_advertises_nothing(monkeypatch: pytest.MonkeyPatch) -> None: + server = ClaimServer() + monkeypatch.delenv("DURABLE_WORKFLOW_WORKER_PROTOCOL_VERSION", raising=False) + worker = Worker(server.client, task_queue="queue") + await worker._register() + registration = server.client.register_worker.await_args.kwargs + + assert "timeout_cleanup" not in registration["capabilities"] + assert "timeout_cleanup" not in registration["capability_manifest"] + + +def test_timeout_cleanup_requires_cooperative_cancellation() -> None: + with pytest.raises(ValueError, match="timeout cleanup requires cooperative_cancellation"): + Worker(ClaimServer().client, task_queue="queue", capabilities=["timeout_cleanup"]) + + +def _claimed(workflow_type: str, events: list[dict[str, Any]] | None = None) -> dict[str, Any]: + return { + "task_id": "task-1", "workflow_id": "workflow-1", "run_id": "run-1", + "workflow_type": workflow_type, "workflow_task_attempt": 4, + "payload_codec": "avro", "arguments": serializer.envelope([], codec="avro"), + "history_events": deepcopy(events or []), + **({} if events is not None else {"cancellation_request": observation()}), + } + + +def _engine_request(cause: str | None) -> list[dict[str, Any]]: + """What a worker first loads: the request, plus the cleanup event for a timeout.""" + return [*([cleanup_started()] if cause == "timeout" else []), requested(cause)] + + +@pytest.mark.parametrize("body,cause,exception_type,failure", [ + (_uncaught, "timeout", "WorkflowTimeoutCleanupRequested", MARKER), + (_rethrown_by_name, "timeout", "WorkflowTimeoutCleanupRequested", MARKER), + (_compensation_failure, "timeout", "CompensationFailed", None), + (_wrapped, "timeout", "CompensationFailed", None), + (_uncaught, None, "WorkflowCancelled", None), + (_uncaught, "cancellation", "WorkflowCancelled", None), +], ids=[ + "uncaught", "rethrown", "compensation-failure", "wrapped", "ordinary-cancellation", "explicit-cancellation-cause", +]) +async def test_cooperative_worker_sends_the_marker_only_for_the_escaped_interruption( + monkeypatch: pytest.MonkeyPatch, body: Callable[[WorkflowContext], Any], cause: str | None, + exception_type: str, failure: dict[str, str] | None, +) -> None: + server = ClaimServer(history=_engine_request(cause)) + definition = _workflow(body, "timeout-worker") + worker = await server.worker(monkeypatch, workflows=[definition]) + + commands = await worker._run_workflow_task(_claimed("timeout-worker")) + + assert server.trace == ["history", "delivery", "history", "completion"] + assert commands is not None and [command["type"] for command in commands] == ["fail_workflow"] + assert commands[0]["exception_type"] == exception_type + assert commands[0].get("failure") == failure + assert server.client.complete_workflow_task.await_args.kwargs["commands"][0].get("failure") == failure + server.client.fail_workflow_task.assert_not_awaited() + + +async def test_cooperative_cleanup_that_returns_sends_an_ordinary_completion(monkeypatch: pytest.MonkeyPatch) -> None: + server = ClaimServer(history=_engine_request("timeout")) + worker = await server.worker(monkeypatch, workflows=[_workflow(_returns, "timeout-worker-returns")]) + + commands = await worker._run_workflow_task(_claimed("timeout-worker-returns")) + + assert commands is not None and [command["type"] for command in commands] == ["complete_workflow"] + assert serializer.decode_envelope(commands[0]["result"]) == "compensated" + assert "failure" not in commands[0] + + +async def test_a_worker_without_cooperative_cancellation_never_sends_the_marker( + monkeypatch: pytest.MonkeyPatch, +) -> None: + server = ClaimServer() + monkeypatch.delenv("DURABLE_WORKFLOW_WORKER_PROTOCOL_VERSION", raising=False) + definition = _workflow(_constructed, "timeout-incapable") + worker = Worker(server.client, task_queue="queue", worker_id="cooperative-worker", workflows=[definition]) + await worker._register() + events = [ + {"event_type": "TimerScheduled", "payload": {"sequence": 1, "delay_seconds": 30}}, + {"event_type": "TimerFired", "payload": {"sequence": 1}}, + ] + + commands = await worker._run_workflow_task(_claimed("timeout-incapable", events)) + + assert commands is not None and [command["type"] for command in commands] == ["fail_workflow"] + assert commands[0]["exception_type"] == "WorkflowTimeoutCleanupRequested" + assert "failure" not in commands[0] + + +async def test_a_worker_without_cooperative_cancellation_strips_a_replayed_marker( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from durable_workflow import worker as worker_module + + original = worker_module.replay + + def marked(*args: Any, **kwargs: Any) -> Any: + outcome = original(*args, **kwargs) + outcome.commands = [FailWorkflow("forced", interruption="timeout_cleanup")] + return outcome + + monkeypatch.setattr(worker_module, "replay", marked) + server = ClaimServer() + monkeypatch.delenv("DURABLE_WORKFLOW_WORKER_PROTOCOL_VERSION", raising=False) + definition = _workflow(_uncaught, "timeout-stripped") + worker = Worker(server.client, task_queue="queue", worker_id="cooperative-worker", workflows=[definition]) + await worker._register() + + commands = await worker._run_workflow_task(_claimed("timeout-stripped", [])) + + assert commands is not None and [command["type"] for command in commands] == ["fail_workflow"] + assert "failure" not in commands[0]