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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Changed

- Cooperative activity callbacks now wait up to 30 seconds, instead of a
fixed 5, for their spawned process to report readiness. Set the wait with
`DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT` or `worker.activity_spawn_timeout`.
A callback that misses it is stopped and joined, frees its activity slot, and
its claim is released as a retryable `worker_lost` failure (cause
`activity_spawn_readiness_timeout`) whose message names the setting, instead
of being reported as an activity failure. Claim loss or shutdown during a
slow start no longer waits for readiness (sdk-python#388).

## [2.24.0] - 2026-11-26

### Added
Expand Down
19 changes: 19 additions & 0 deletions docs/reference/worker.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,25 @@ isolated worker processes and their resource limits. The separately
negotiated cooperative-cancellation capability retains its supervised process
execution; selecting a default thread does not enable that protocol.

### Cooperative callback start timeout

With cooperative cancellation, each activity runs in a supervised
spawn-context process. The worker waits up to `worker.activity_spawn_timeout`
seconds (default 30) for that process to start, import the handler and report
readiness. A busy host can need much longer than an idle one, for example
when several activities start at once in a small container. Set
`DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT=60`, or assign
`worker.activity_spawn_timeout = 60.0` before running the worker, or lower
`max_concurrent_activity_tasks`. A malformed environment value stops the
worker from running.

A start that misses the timeout had not reported its handler started. The
worker stops and joins the process, then releases the claim as a retryable
`worker_lost` failure with cause `activity_spawn_readiness_timeout`, so the
Server can retry the attempt. The message names the timeout and the setting.
It is not reported as an activity failure. Claim loss or worker shutdown
during a slow start stops the start without waiting for readiness.

## Bounded failure reports

This behavior is available in Python SDK 2.11.0 and later.
Expand Down
4 changes: 2 additions & 2 deletions src/durable_workflow/_activity_lease.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def renewal_retry_delay(failures: int) -> float:


async def release_worker_lost(client: Any, *, task_id: str, activity_attempt_id: str, lease_owner: str,
cause: str, timeout: float) -> bool:
cause: str, timeout: float, message: str | None = None) -> bool:
"""Release a claim the worker cannot maintain, by the cross-SDK contract.

Call only after the execution is confirmed stopped (or never started):
Expand All @@ -61,7 +61,7 @@ async def release_worker_lost(client: Any, *, task_id: str, activity_attempt_id:
try:
await asyncio.wait_for(client.fail_activity_task(
task_id=task_id, activity_attempt_id=activity_attempt_id, lease_owner=lease_owner,
message=f"activity worker released the claim: lease could not be renewed ({cause})",
message=message or f"activity worker released the claim: lease could not be renewed ({cause})",
failure_type=WORKER_LOST_FAILURE_TYPE, failure_class=ActivityWorkerLost.__name__,
non_retryable=False, details={"reason": WORKER_LOST_FAILURE_TYPE, "cause": cause},
), timeout=timeout)
Expand Down
63 changes: 59 additions & 4 deletions src/durable_workflow/_activity_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import asyncio
import inspect
import math
import multiprocessing
import pickle
import selectors
Expand All @@ -29,11 +30,44 @@
from .errors import ActivityCancelled, NonRetryableError
from .interceptors import ActivityInterceptorContext, WorkerInterceptor

# A cooperative callback is two spawn-context interpreters (supervisor, then
# callback) that import the SDK and the handler before reporting readiness. On
# a busy host that takes far longer than an idle start, so the default wait is
# generous; Worker.activity_spawn_timeout or ACTIVITY_SPAWN_TIMEOUT_ENV changes it.
DEFAULT_SPAWN_READINESS_TIMEOUT = 30.0
ACTIVITY_SPAWN_TIMEOUT_ENV = "DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT"
# worker_lost release cause when a callback misses spawn readiness.
ACTIVITY_SPAWN_READINESS_TIMEOUT = "activity_spawn_readiness_timeout"
_CLOSE_JOIN_TIMEOUT = 5.0


def validate_spawn_readiness_timeout(value: float, name: str = "activity_spawn_timeout") -> float:
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
raise ValueError(f"{name} must be a positive, finite number of seconds")
return float(value)


class CallbackProcessLost(RuntimeError):
"""The owner could not prove the callback outcome or physical stop."""


class CallbackSpawnTimeout(CallbackProcessLost):
"""The callback did not report spawn readiness in time and was confirmed stopped.

The handler had not been reported started. Raised only after the
supervisor (and so the callback) is joined, so the claim can be released
for a retry without two executions overlapping.
"""

def __init__(self, timeout: float) -> None:
self.timeout = timeout
super().__init__(
f"cooperative activity callback did not report spawn readiness within {timeout:g}s; the host may "
"be overloaded. Raise Worker.activity_spawn_timeout (DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT) or lower "
"max_concurrent_activity_tasks"
)


@dataclass(frozen=True)
class CallbackInvocation:
handler: Callable[..., Any]
Expand Down Expand Up @@ -214,7 +248,10 @@ class SupervisedCallback:
never supplies stop evidence. The worker integration remains a separate gate.
"""

def __init__(self, invocation: CallbackInvocation) -> None:
def __init__(
self, invocation: CallbackInvocation, *, readiness_timeout: float = DEFAULT_SPAWN_READINESS_TIMEOUT,
) -> None:
self._readiness_timeout = validate_spawn_readiness_timeout(readiness_timeout, "readiness_timeout")
serialized = invocation.serialize()
self.directory = tempfile.mkdtemp(prefix="dw-activity-")
try:
Expand All @@ -241,13 +278,31 @@ async def start(self) -> None:
self._supervisor.start()
self._started = True
self._supervisor_channel.close()
message = await asyncio.wait_for(self._receive(), timeout=5.0)
try:
message = await asyncio.wait_for(self._receive(), timeout=self._readiness_timeout)
except asyncio.TimeoutError:
await self._close_unready()
raise CallbackSpawnTimeout(self._readiness_timeout) from None
if message != b"B":
raise CallbackProcessLost("callback did not prove spawn readiness")
except BaseException:
await self.close()
# A clean supervisor exit, including after the owner cancelled
# this start, proves its callback was reaped.
if self._exitcode == 0:
self.stopped = True
raise

async def _close_unready(self) -> None:
# The supervisor may still be starting on a busy host. Closing the
# owner channel makes it reap its callback and exit; allow it as long
# as readiness was allowed. Only a clean supervisor exit proves the
# callback joined, so anything else stays CallbackProcessLost.
await self.close(join_timeout=max(2 * _CLOSE_JOIN_TIMEOUT, self._readiness_timeout))
if self._exitcode != 0:
raise CallbackProcessLost("callback supervisor did not confirm a clean join after spawn timeout")
self.stopped = True

async def _receive(self) -> bytes:
try:
message = await asyncio.get_running_loop().sock_recv(self._owner, 1)
Expand Down Expand Up @@ -311,15 +366,15 @@ async def _confirm_join(self) -> None:
raise CallbackProcessLost("callback supervisor did not confirm a clean join")
self.stopped = True

async def close(self) -> None:
async def close(self, *, join_timeout: float = _CLOSE_JOIN_TIMEOUT) -> None:
if self._joined:
return
if not self._closed:
self._closed = True
self._owner.close()
self._supervisor_channel.close()
if self._started:
await asyncio.to_thread(self._supervisor.join, 5.0)
await asyncio.to_thread(self._supervisor.join, join_timeout)
if self._supervisor.is_alive():
raise CallbackProcessLost("callback supervisor has not confirmed shutdown")
self._exitcode = self._supervisor.exitcode
Expand Down
7 changes: 4 additions & 3 deletions src/durable_workflow/_prepared_local_activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from typing import Any

from . import serializer
from ._activity_process import CallbackInvocation, SupervisedCallback
from ._activity_process import DEFAULT_SPAWN_READINESS_TIMEOUT, CallbackInvocation, SupervisedCallback
from .cancellation import CancellationContext
from .client import Client
from .workflow import LocalActivityExecutionAborted
Expand Down Expand Up @@ -243,9 +243,10 @@ def remaining(self) -> float:
class PreparedLocalRunner:
def __init__(
self, client: Client, attempt: PreparedAttempt, *, observe: Callable[[Mapping[str, Any]], Any],
shutdown: asyncio.Event,
shutdown: asyncio.Event, spawn_timeout: float = DEFAULT_SPAWN_READINESS_TIMEOUT,
) -> None:
self.client = client
self.spawn_timeout = spawn_timeout
self.attempt = attempt
self.observe = observe
self.shutdown = shutdown
Expand Down Expand Up @@ -301,7 +302,7 @@ async def heartbeat(details: dict[str, Any] | None) -> None:
# Admission was fenced before any process existed.
await self.acknowledge_stop()
raise
callback = SupervisedCallback(invocation)
callback = SupervisedCallback(invocation, readiness_timeout=self.spawn_timeout)
self.callback = callback
processes.add(callback)
background: list[asyncio.Task[Any]] = []
Expand Down
85 changes: 80 additions & 5 deletions src/durable_workflow/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,17 @@
current_activity_authority,
release_worker_lost,
)
from ._activity_process import CallbackFailure, CallbackInvocation, CallbackProcessLost, SupervisedCallback
from ._activity_process import (
ACTIVITY_SPAWN_READINESS_TIMEOUT,
ACTIVITY_SPAWN_TIMEOUT_ENV,
DEFAULT_SPAWN_READINESS_TIMEOUT,
CallbackFailure,
CallbackInvocation,
CallbackProcessLost,
CallbackSpawnTimeout,
SupervisedCallback,
validate_spawn_readiness_timeout,
)
from ._cancellation_scope_history import CancellationScopeBudget, CancellationScopeDeliveryReceipt
from ._cooperative_cancellation import CancellationRequest, read_cancellation_history
from ._failure_reporting import REQUEST_BYTES, exception_message, normalize_local_failure
Expand Down Expand Up @@ -1352,6 +1362,18 @@ def _contract_version_matches(value: Any, expected: int) -> bool:
RECORD_PARALLEL_FAILURE_ORDER_ENV = "DURABLE_WORKFLOW_RECORD_PARALLEL_FAILURE_ORDER"


def _activity_spawn_timeout_from_environment() -> float:
"""The cooperative callback readiness wait from the environment, refused when malformed."""
raw = os.environ.get(ACTIVITY_SPAWN_TIMEOUT_ENV, "").strip()
if not raw:
return DEFAULT_SPAWN_READINESS_TIMEOUT
try:
value = float(raw)
except ValueError:
raise ValueError(f"{ACTIVITY_SPAWN_TIMEOUT_ENV} must be a positive, finite number of seconds") from None
return validate_spawn_readiness_timeout(value, ACTIVITY_SPAWN_TIMEOUT_ENV)


def _record_parallel_failure_order(value: bool | None) -> bool:
"""The worker's failure-order recording setting, refused when malformed."""
if value is None:
Expand Down Expand Up @@ -2525,7 +2547,8 @@ def observe(value: Mapping[str, Any]) -> None:
raise LocalActivityExecutionAborted("prepared group members observed different cancellation authority")
task["_prepared_cancellation_context"] = dict(value)

runner = PreparedLocalRunner(self.client, attempt, shutdown=self._local_activity_shutdown, observe=observe)
runner = PreparedLocalRunner(self.client, attempt, shutdown=self._local_activity_shutdown, observe=observe,
spawn_timeout=self.activity_spawn_timeout)
telemetry = current_execution_telemetry()
invocation = CallbackInvocation(
handler, tuple(call.command.arguments), ActivityInfo(
Expand Down Expand Up @@ -3751,17 +3774,28 @@ async def observe_ownership() -> None:
callback = SupervisedCallback(CallbackInvocation(
handler, args, info, task, self.interceptors, namespace=getattr(self.client, "namespace", None),
observability_supported=self._observability_claim(task, "activity"), remote=True,
))
), readiness_timeout=self.activity_spawn_timeout)
self._remote_activity_processes.add(callback)
claim = current_activity_authority.get()
if claim is not None:
claim.track(callback)
invocation: asyncio.Task[Any] | None = None
starting: asyncio.Task[None] | None = None
abandoned = False
observation = asyncio.create_task(observe_ownership())
shutdown = asyncio.create_task(self._local_activity_shutdown.wait())
try:
await callback.start()
# A slow start on a busy host still yields to claim loss and shutdown.
starting = asyncio.create_task(callback.start())
done, _ = await asyncio.wait([starting, observation, shutdown], return_when=asyncio.FIRST_COMPLETED)
if starting not in done:
starting.cancel()
await asyncio.gather(starting, return_exceptions=True)
if shutdown in done:
raise _RemoteActivityExecutionAborted("worker shutdown abandoned its remote activity claim")
await observation
raise _RemoteActivityExecutionAborted("remote ownership observer stopped without a response")
await starting
invocation = asyncio.create_task(callback.result(send_heartbeat))
done, _ = await asyncio.wait([invocation, observation, shutdown], return_when=asyncio.FIRST_COMPLETED)
if shutdown in done:
Expand All @@ -3781,7 +3815,8 @@ async def observe_ownership() -> None:
abandoned = True
raise
finally:
backgrounds = [background for background in (invocation, observation, shutdown) if background is not None]
backgrounds = [background for background in (starting, invocation, observation, shutdown)
if background is not None]
for background in backgrounds:
if not background.done():
background.cancel()
Expand Down Expand Up @@ -3850,6 +3885,20 @@ async def _fail_unrenewable_activity_claim(self, task: dict[str, Any], authority
log.warning("activity claim %s released as worker_lost: %s", task_id, error.reason)
return "failed"

async def _release_unready_remote_activity(self, task_id: str, attempt_id: str,
error: CallbackSpawnTimeout) -> str:
# The callback never reported readiness, and its supervisor (which
# reaps the callback) was joined before this error was raised, so
# nothing of this attempt still runs. Release the claim as a
# retryable worker condition, not an activity failure.
log.warning("remote activity %s did not start: %s", task_id, error)
released = await release_worker_lost(
self.client, task_id=task_id, activity_attempt_id=attempt_id, lease_owner=self.worker_id,
cause=ACTIVITY_SPAWN_READINESS_TIMEOUT, timeout=5.0,
message=f"activity worker released the claim: {error}",
)
return "failed" if released else "claim_aborted"

async def _run_activity_task_body(self, task: dict[str, Any]) -> str:
self._track_worker_session_from_task(task)
task_id: str = task["task_id"]
Expand Down Expand Up @@ -3895,6 +3944,8 @@ async def _run_activity_task_body(self, task: dict[str, Any]) -> str:
except _RemoteActivityExecutionAborted as error:
log.warning("remote activity %s claim abandoned: %s", task_id, error)
return "claim_aborted"
except CallbackSpawnTimeout as error:
return await self._release_unready_remote_activity(task_id, attempt_id, error)
except CallbackProcessLost as error:
log.warning("remote activity %s supervision failed: %s", task_id, error)
return "claim_aborted"
Expand Down Expand Up @@ -5623,11 +5674,35 @@ async def _run_until_activity_task(self, task: dict[str, Any]) -> None:
self._activity_inflight = max(0, self._activity_inflight - 1)
self._record_task_metrics("activity", outcome, time.perf_counter() - task_start)

@property
def activity_spawn_timeout(self) -> float:
"""Seconds a cooperative activity callback process may take to report readiness.

A cooperative worker runs each activity in a supervised spawn-context
process. The default is 30 seconds, or
``DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT`` when set. Assign a
positive number before running the worker to change it. A start that
misses the wait had not reported its handler started: the worker stops
and joins the process, then releases the claim as a retryable
``worker_lost`` failure.
"""
configured: float | None = getattr(self, "_activity_spawn_timeout", None)
if configured is None:
configured = _activity_spawn_timeout_from_environment()
self._activity_spawn_timeout = configured
return configured

@activity_spawn_timeout.setter
def activity_spawn_timeout(self, value: float) -> None:
self._activity_spawn_timeout = validate_spawn_readiness_timeout(value)

def _begin_run(self) -> None:
if self._run_started:
raise RuntimeError("worker is already running or has already run")
if self._stop.is_set():
raise RuntimeError("worker cannot run after stop() has been called")
# Refuse a malformed environment setting before claiming any work.
_ = self.activity_spawn_timeout
self._run_started = True
self._status.run_started()
self._status_tick_task = asyncio.get_running_loop().create_task(self._status_tick_loop())
Expand Down
19 changes: 19 additions & 0 deletions tests/slow_import_activity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""An activity whose module import stalls in spawned children (sdk-python#388).

The test process imports it normally. A test then sets the variable, so a
spawned callback that unpickles the handler stalls before reporting readiness,
as a callback does on an overloaded host.
"""
from __future__ import annotations

import os
import time

STALL_ENV = "DURABLE_WORKFLOW_TEST_STALL_ACTIVITY_IMPORT"

if os.environ.get(STALL_ENV):
time.sleep(float(os.environ[STALL_ENV]))


def stalled_import_activity() -> str:
return "ran"
Loading