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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
28 changes: 27 additions & 1 deletion docs/cooperative-cancellation-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
63 changes: 63 additions & 0 deletions src/durable_workflow/_timeout_cleanup.py
Original file line number Diff line number Diff line change
@@ -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
17 changes: 16 additions & 1 deletion src/durable_workflow/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import asyncio
import contextlib
import contextvars
import dataclasses
import hashlib
import inspect
import json
Expand All @@ -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,
Expand Down Expand Up @@ -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]}"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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,
Expand Down
33 changes: 29 additions & 4 deletions src/durable_workflow/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -79,6 +79,7 @@
WorkflowEntryArgumentsMismatchError,
WorkflowPayloadDecodeError,
WorkflowSourceLocation,
WorkflowTimeoutCleanupRequested,
_cancellation_requested,
validate_signal_name,
)
Expand Down Expand Up @@ -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,
Expand All @@ -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


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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,
))
Expand Down Expand Up @@ -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:
Expand Down
Loading