From 263078ffdd99269f25dae4869b2b5552f125b66b Mon Sep 17 00:00:00 2001 From: Richard McDaniel <1130888+rmcdaniel@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:55:29 +0000 Subject: [PATCH 1/3] Make cooperative callback spawn readiness configurable A cooperative activity waited a fixed 5 s for its spawned supervisor and callback to report readiness. On a busy worker several starts at once missed it, and the TimeoutError became an activity failure while the unconfirmed process kept its activity slot. Worker(activity_spawn_timeout=...) now sets the wait, default 30 s. A missed wait raises CallbackSpawnTimeout only after the supervisor joined cleanly, so the callback is proved stopped and its slot is freed. The worker then releases the claim as a retryable worker_lost failure (cause activity_spawn_readiness_timeout) with a message that names the setting. Fixes #388 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 ++++ docs/reference/worker.md | 16 ++++++ src/durable_workflow/_activity_lease.py | 4 +- src/durable_workflow/_activity_process.py | 56 +++++++++++++++++-- .../_prepared_local_activity.py | 7 ++- src/durable_workflow/worker.py | 39 ++++++++++++- tests/test_activity_process.py | 55 ++++++++++++++++++ tests/test_cooperative_remote_worker.py | 44 ++++++++++++++- 8 files changed, 217 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 018c9fad..a8206c30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ 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, and + `Worker(activity_spawn_timeout=...)` sets the wait. A callback that misses it + ran no application code: the worker stops it, frees its activity slot and + releases the claim as a retryable `worker_lost` failure (cause + `activity_spawn_readiness_timeout`) whose message names the setting, instead + of reporting an activity failure (sdk-python#388). + ## [2.24.0] - 2026-11-26 ### Added diff --git a/docs/reference/worker.md b/docs/reference/worker.md index 63afea3c..9157de40 100644 --- a/docs/reference/worker.md +++ b/docs/reference/worker.md @@ -29,6 +29,22 @@ 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 `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. Raise the timeout +with `Worker(..., activity_spawn_timeout=60.0)`, or lower +`max_concurrent_activity_tasks`. + +A start that misses the timeout ran no application code. The worker stops +the process and 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. + ## Bounded failure reports This behavior is available in Python SDK 2.11.0 and later. diff --git a/src/durable_workflow/_activity_lease.py b/src/durable_workflow/_activity_lease.py index 2b738a74..94e42f4e 100644 --- a/src/durable_workflow/_activity_lease.py +++ b/src/durable_workflow/_activity_lease.py @@ -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): @@ -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) diff --git a/src/durable_workflow/_activity_process.py b/src/durable_workflow/_activity_process.py index 1df0b9fe..2723294b 100644 --- a/src/durable_workflow/_activity_process.py +++ b/src/durable_workflow/_activity_process.py @@ -10,6 +10,7 @@ import asyncio import inspect +import math import multiprocessing import pickle import selectors @@ -29,11 +30,41 @@ 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=...) changes it. +DEFAULT_SPAWN_READINESS_TIMEOUT = 30.0 +# 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. + + No application code ran. Raised only after the supervisor (and so the + callback) is joined, so the claim can be released for a retry. + """ + + 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=...) or lower max_concurrent_activity_tasks" + ) + + @dataclass(frozen=True) class CallbackInvocation: handler: Callable[..., Any] @@ -214,7 +245,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: @@ -241,13 +275,27 @@ 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() 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(_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) @@ -311,7 +359,7 @@ 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: @@ -319,7 +367,7 @@ async def close(self) -> None: 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 diff --git a/src/durable_workflow/_prepared_local_activity.py b/src/durable_workflow/_prepared_local_activity.py index 48a32762..3fec0a4a 100644 --- a/src/durable_workflow/_prepared_local_activity.py +++ b/src/durable_workflow/_prepared_local_activity.py @@ -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 @@ -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 @@ -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]] = [] diff --git a/src/durable_workflow/worker.py b/src/durable_workflow/worker.py index 5f19359d..1223afb4 100644 --- a/src/durable_workflow/worker.py +++ b/src/durable_workflow/worker.py @@ -50,7 +50,16 @@ current_activity_authority, release_worker_lost, ) -from ._activity_process import CallbackFailure, CallbackInvocation, CallbackProcessLost, SupervisedCallback +from ._activity_process import ( + ACTIVITY_SPAWN_READINESS_TIMEOUT, + 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 @@ -1401,9 +1410,16 @@ def __init__( external_storage_cache: ExternalPayloadCache | None = None, require_query_task_authority: bool = False, record_parallel_failure_order: bool | None = None, + activity_spawn_timeout: float = DEFAULT_SPAWN_READINESS_TIMEOUT, ) -> None: """Create a worker. + ``activity_spawn_timeout`` bounds, in seconds, how long a cooperative + worker waits for a supervised activity callback process to start and + report readiness (default 30). A start that misses it ran no + application code; the worker stops the process and releases the claim + as a retryable ``worker_lost`` failure. + ``record_parallel_failure_order`` lets new runs record the parallel failure-order marker before their first all-group, so their groups raise the first recorded member failure (sdk-python#307). ``None`` @@ -1486,6 +1502,7 @@ def __init__( raise ValueError("max_concurrent_worker_sessions must be at least 1") if heartbeat_interval <= 0: raise ValueError("heartbeat_interval must be positive") + self.activity_spawn_timeout = validate_spawn_readiness_timeout(activity_spawn_timeout) # Client supplies HTTP grace separately from this requested poll window. self._poll_timeout = poll_timeout @@ -2525,7 +2542,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( @@ -3751,7 +3769,7 @@ 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: @@ -3850,6 +3868,19 @@ 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, so no application code ran, + # and its supervisor was joined before this error was raised. 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"] @@ -3895,6 +3926,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" diff --git a/tests/test_activity_process.py b/tests/test_activity_process.py index decc3152..9eaffbfd 100644 --- a/tests/test_activity_process.py +++ b/tests/test_activity_process.py @@ -14,8 +14,10 @@ from durable_workflow import activity from durable_workflow._activity_process import ( + DEFAULT_SPAWN_READINESS_TIMEOUT, CallbackInvocation, CallbackProcessLost, + CallbackSpawnTimeout, SupervisedCallback, ) from durable_workflow.activity import ActivityInfo @@ -268,3 +270,56 @@ async def paused_close(self: SupervisedCallback) -> None: await asyncio.gather(result, return_exceptions=True) if not callback.stopped: await callback.stop() + + +def write_marker(marker: str) -> str: + Path(marker).write_text("ran") + return marker + + +@pytest.mark.parametrize("value", [0, -1.0, float("nan"), float("inf"), True, "30"]) +def test_readiness_timeout_must_be_a_positive_finite_number(value: Any) -> None: + with pytest.raises(ValueError, match="readiness_timeout must be a positive, finite number of seconds"): + SupervisedCallback(invocation(typed_result, b""), readiness_timeout=value) + + +def test_default_readiness_timeout_allows_a_busy_host() -> None: + assert DEFAULT_SPAWN_READINESS_TIMEOUT == 30.0 + + +async def test_missed_spawn_readiness_stops_the_callback_and_names_the_setting(tmp_path: Path) -> None: + marker = tmp_path / "ran" + callback = SupervisedCallback(invocation(write_marker, str(marker)), readiness_timeout=0.001) + with pytest.raises(CallbackSpawnTimeout, match=r"spawn readiness within 0\.001s.*activity_spawn_timeout") as raised: + await callback.start() + assert isinstance(raised.value, CallbackProcessLost) + assert raised.value.timeout == 0.001 + # The supervisor joined cleanly, so its callback is proved stopped. + assert callback.stopped is True + assert not Path(callback.directory).exists() + assert not marker.exists() + await callback.close() + + +@pytest.mark.skipif(not hasattr(os, "sched_setaffinity"), reason="needs CPU affinity") +async def test_concurrent_cooperative_spawns_on_one_cpu_all_report_ready() -> None: + # sdk-python#388: about eight spawn-context callbacks starting at once on a + # constrained worker missed a fixed 5 s readiness wait. Spawned children + # inherit this process's affinity, so all of them share one CPU here. + original = os.sched_getaffinity(0) + os.sched_setaffinity(0, {min(original)}) + callbacks = [SupervisedCallback(invocation(typed_result, bytes([index]))) for index in range(8)] + try: + started = time.monotonic() + await asyncio.gather(*(callback.start() for callback in callbacks)) + elapsed = time.monotonic() - started + outcomes = await asyncio.gather(*(callback.result(no_heartbeat) for callback in callbacks)) + finally: + os.sched_setaffinity(0, original) + for callback in callbacks: + if not callback.stopped: + await callback.stop() + await callback.close() + assert [outcome.value["bytes"] for outcome in outcomes] == [bytes([index]) for index in range(8)] + assert all(callback.stopped for callback in callbacks) + assert elapsed < DEFAULT_SPAWN_READINESS_TIMEOUT diff --git a/tests/test_cooperative_remote_worker.py b/tests/test_cooperative_remote_worker.py index 254c7562..33263ff8 100644 --- a/tests/test_cooperative_remote_worker.py +++ b/tests/test_cooperative_remote_worker.py @@ -93,7 +93,7 @@ async def application_failure(kind: str) -> None: raise ActivityCancelled() -async def make_owner(monkeypatch: pytest.MonkeyPatch) -> tuple[Worker, AsyncMock]: +async def make_owner(monkeypatch: pytest.MonkeyPatch, **options: Any) -> tuple[Worker, AsyncMock]: monkeypatch.delenv("DURABLE_WORKFLOW_WORKER_PROTOCOL_VERSION", raising=False) client = AsyncMock(spec=Client) client.get_cluster_info.return_value = compatible_cluster_info(worker_protocol={ @@ -104,7 +104,7 @@ async def make_owner(monkeypatch: pytest.MonkeyPatch) -> tuple[Worker, AsyncMock client.heartbeat_activity_task.return_value = status() client.acknowledge_activity_cancellation.return_value = stop_receipt() worker = Worker(client, task_queue="queue", worker_id="owner", capabilities=["cooperative_cancellation"], - max_concurrent_activity_tasks=1) + max_concurrent_activity_tasks=1, **options) await worker._register() return worker, client @@ -375,3 +375,43 @@ async def test_client_observation_bounds_the_total_retry_budget(monkeypatch: pyt ), timeout=7) assert asyncio.get_running_loop().time() - started < 6 send.assert_awaited_once() + + +def write_ran_marker(marker: str) -> None: + Path(marker).write_text("ran") + + +@pytest.mark.parametrize("value", [0, -5, float("nan"), float("inf")]) +def test_activity_spawn_timeout_must_be_positive_and_finite(value: float) -> None: + with pytest.raises(ValueError, match="activity_spawn_timeout must be a positive, finite number of seconds"): + Worker(AsyncMock(spec=Client), task_queue="queue", activity_spawn_timeout=value) + assert Worker(AsyncMock(spec=Client), task_queue="queue").activity_spawn_timeout == 30.0 + + +async def test_missed_spawn_readiness_releases_the_claim_as_retryable_worker_lost( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, +) -> None: + # sdk-python#388: a busy host that misses the readiness wait has run no + # application code. The claim is released for a retry, not failed. + worker, client = await make_owner(monkeypatch, activity_spawn_timeout=0.001) + marker = tmp_path / "ran" + worker.activities["remote"] = write_ran_marker + try: + assert await worker._run_activity_task(task(str(marker))) == "failed" + client.fail_activity_task.assert_awaited_once() + report = client.fail_activity_task.await_args.kwargs + assert report["task_id"] == "remote-task" + assert report["activity_attempt_id"] == "attempt" + assert report["lease_owner"] == "owner" + assert report["failure_type"] == "worker_lost" + assert report["non_retryable"] is False + assert report["details"] == {"reason": "worker_lost", "cause": "activity_spawn_readiness_timeout"} + assert "spawn readiness within 0.001s" in report["message"] + assert "activity_spawn_timeout" in report["message"] + client.complete_activity_task.assert_not_awaited() + assert not marker.exists() + # The stopped callback gives its capacity back. + assert not worker._remote_activity_processes + assert worker._current_task_slots()["activity_available"] == 1 + finally: + await worker.stop() From c8303f8d7ba22f85176b6d421f0e1b9c6975d646 Mon Sep 17 00:00:00 2001 From: Richard McDaniel <1130888+rmcdaniel@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:07:38 +0000 Subject: [PATCH 2/3] Configure spawn readiness outside Worker.__init__; yield a slow start Review of #390: - Move the setting to a Worker.activity_spawn_timeout property, with a DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT default checked before run. Worker.__init__ stays unchanged, so the replay regression corpus guard no longer sees an activity setting as a replay change. - Race the start against ownership observation and worker shutdown, so a slow start no longer delays claim loss or shutdown. - Any start failure whose supervisor exits cleanly marks the callback stopped, returning its slot. Allow at least 10 s for that join after a missed readiness wait. - Say the handler had not reported started, not that no application code ran. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 ++-- docs/reference/worker.md | 25 +++++---- src/durable_workflow/_activity_process.py | 17 ++++-- src/durable_workflow/worker.py | 67 ++++++++++++++++++----- tests/slow_import_activity.py | 19 +++++++ tests/test_cooperative_remote_worker.py | 64 +++++++++++++++++++--- 6 files changed, 162 insertions(+), 41 deletions(-) create mode 100644 tests/slow_import_activity.py diff --git a/CHANGELOG.md b/CHANGELOG.md index a8206c30..49af885f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,12 +9,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - Cooperative activity callbacks now wait up to 30 seconds, instead of a - fixed 5, for their spawned process to report readiness, and - `Worker(activity_spawn_timeout=...)` sets the wait. A callback that misses it - ran no application code: the worker stops it, frees its activity slot and - releases the claim as a retryable `worker_lost` failure (cause + 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 reporting an activity failure (sdk-python#388). + 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 diff --git a/docs/reference/worker.md b/docs/reference/worker.md index 9157de40..1d2754c1 100644 --- a/docs/reference/worker.md +++ b/docs/reference/worker.md @@ -32,18 +32,21 @@ 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 `activity_spawn_timeout` seconds -(default 30) for that process to start, import the handler and report +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. Raise the timeout -with `Worker(..., activity_spawn_timeout=60.0)`, or lower -`max_concurrent_activity_tasks`. - -A start that misses the timeout ran no application code. The worker stops -the process and 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. +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 diff --git a/src/durable_workflow/_activity_process.py b/src/durable_workflow/_activity_process.py index 2723294b..f32d3ff5 100644 --- a/src/durable_workflow/_activity_process.py +++ b/src/durable_workflow/_activity_process.py @@ -33,8 +33,9 @@ # 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=...) changes it. +# 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 @@ -53,15 +54,17 @@ class CallbackProcessLost(RuntimeError): class CallbackSpawnTimeout(CallbackProcessLost): """The callback did not report spawn readiness in time and was confirmed stopped. - No application code ran. Raised only after the supervisor (and so the - callback) is joined, so the claim can be released for a retry. + 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=...) or lower max_concurrent_activity_tasks" + "be overloaded. Raise Worker.activity_spawn_timeout (DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT) or lower " + "max_concurrent_activity_tasks" ) @@ -284,6 +287,10 @@ async def start(self) -> None: 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: @@ -291,7 +298,7 @@ async def _close_unready(self) -> None: # 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(_CLOSE_JOIN_TIMEOUT, self._readiness_timeout)) + 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 diff --git a/src/durable_workflow/worker.py b/src/durable_workflow/worker.py index 1223afb4..686eef33 100644 --- a/src/durable_workflow/worker.py +++ b/src/durable_workflow/worker.py @@ -52,6 +52,7 @@ ) from ._activity_process import ( ACTIVITY_SPAWN_READINESS_TIMEOUT, + ACTIVITY_SPAWN_TIMEOUT_ENV, DEFAULT_SPAWN_READINESS_TIMEOUT, CallbackFailure, CallbackInvocation, @@ -1361,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: @@ -1410,16 +1423,9 @@ def __init__( external_storage_cache: ExternalPayloadCache | None = None, require_query_task_authority: bool = False, record_parallel_failure_order: bool | None = None, - activity_spawn_timeout: float = DEFAULT_SPAWN_READINESS_TIMEOUT, ) -> None: """Create a worker. - ``activity_spawn_timeout`` bounds, in seconds, how long a cooperative - worker waits for a supervised activity callback process to start and - report readiness (default 30). A start that misses it ran no - application code; the worker stops the process and releases the claim - as a retryable ``worker_lost`` failure. - ``record_parallel_failure_order`` lets new runs record the parallel failure-order marker before their first all-group, so their groups raise the first recorded member failure (sdk-python#307). ``None`` @@ -1502,7 +1508,6 @@ def __init__( raise ValueError("max_concurrent_worker_sessions must be at least 1") if heartbeat_interval <= 0: raise ValueError("heartbeat_interval must be positive") - self.activity_spawn_timeout = validate_spawn_readiness_timeout(activity_spawn_timeout) # Client supplies HTTP grace separately from this requested poll window. self._poll_timeout = poll_timeout @@ -3775,11 +3780,22 @@ async def observe_ownership() -> None: 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: @@ -3799,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() @@ -3870,9 +3887,10 @@ async def _fail_unrenewable_activity_claim(self, task: dict[str, Any], authority async def _release_unready_remote_activity(self, task_id: str, attempt_id: str, error: CallbackSpawnTimeout) -> str: - # The callback never reported readiness, so no application code ran, - # and its supervisor was joined before this error was raised. Release - # the claim as a retryable worker condition, not an activity failure. + # 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, @@ -5656,11 +5674,34 @@ 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 ran no application code: the worker stops the process + and 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()) diff --git a/tests/slow_import_activity.py b/tests/slow_import_activity.py new file mode 100644 index 00000000..81062d03 --- /dev/null +++ b/tests/slow_import_activity.py @@ -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" diff --git a/tests/test_cooperative_remote_worker.py b/tests/test_cooperative_remote_worker.py index 33263ff8..f59c320e 100644 --- a/tests/test_cooperative_remote_worker.py +++ b/tests/test_cooperative_remote_worker.py @@ -18,6 +18,7 @@ from durable_workflow.errors import ActivityCancelled, NonRetryableError, ServerError from durable_workflow.retry_policy import TransportRetryPolicy from durable_workflow.worker import Worker +from tests import slow_import_activity from tests.test_activity_process import wait_for_exit, wait_for_file from tests.test_activity_retry_info import inspect_activity_context from tests.test_worker import compatible_cluster_info @@ -93,7 +94,7 @@ async def application_failure(kind: str) -> None: raise ActivityCancelled() -async def make_owner(monkeypatch: pytest.MonkeyPatch, **options: Any) -> tuple[Worker, AsyncMock]: +async def make_owner(monkeypatch: pytest.MonkeyPatch) -> tuple[Worker, AsyncMock]: monkeypatch.delenv("DURABLE_WORKFLOW_WORKER_PROTOCOL_VERSION", raising=False) client = AsyncMock(spec=Client) client.get_cluster_info.return_value = compatible_cluster_info(worker_protocol={ @@ -104,7 +105,7 @@ async def make_owner(monkeypatch: pytest.MonkeyPatch, **options: Any) -> tuple[W client.heartbeat_activity_task.return_value = status() client.acknowledge_activity_cancellation.return_value = stop_receipt() worker = Worker(client, task_queue="queue", worker_id="owner", capabilities=["cooperative_cancellation"], - max_concurrent_activity_tasks=1, **options) + max_concurrent_activity_tasks=1) await worker._register() return worker, client @@ -381,11 +382,33 @@ def write_ran_marker(marker: str) -> None: Path(marker).write_text("ran") -@pytest.mark.parametrize("value", [0, -5, float("nan"), float("inf")]) -def test_activity_spawn_timeout_must_be_positive_and_finite(value: float) -> None: +@pytest.mark.parametrize("value", [0, -5, float("nan"), float("inf"), True]) +def test_activity_spawn_timeout_must_be_positive_and_finite(monkeypatch: pytest.MonkeyPatch, value: float) -> None: + monkeypatch.delenv("DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT", raising=False) + worker = Worker(AsyncMock(spec=Client), task_queue="queue") + assert worker.activity_spawn_timeout == 30.0 with pytest.raises(ValueError, match="activity_spawn_timeout must be a positive, finite number of seconds"): - Worker(AsyncMock(spec=Client), task_queue="queue", activity_spawn_timeout=value) - assert Worker(AsyncMock(spec=Client), task_queue="queue").activity_spawn_timeout == 30.0 + worker.activity_spawn_timeout = value + worker.activity_spawn_timeout = 60 + assert worker.activity_spawn_timeout == 60.0 + + +@pytest.mark.parametrize(("raw", "expected"), [("45", 45.0), (" 2.5 ", 2.5), ("", 30.0)]) +def test_activity_spawn_timeout_reads_the_environment( + monkeypatch: pytest.MonkeyPatch, raw: str, expected: float, +) -> None: + monkeypatch.setenv("DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT", raw) + assert Worker(AsyncMock(spec=Client), task_queue="queue").activity_spawn_timeout == expected + + +@pytest.mark.parametrize("raw", ["soon", "0", "-1", "nan", "inf"]) +async def test_malformed_activity_spawn_timeout_environment_refuses_to_run( + monkeypatch: pytest.MonkeyPatch, raw: str, +) -> None: + monkeypatch.setenv("DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT", raw) + worker = Worker(AsyncMock(spec=Client), task_queue="queue") + with pytest.raises(ValueError, match="DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT must be a positive, finite"): + worker._begin_run() async def test_missed_spawn_readiness_releases_the_claim_as_retryable_worker_lost( @@ -393,7 +416,8 @@ async def test_missed_spawn_readiness_releases_the_claim_as_retryable_worker_los ) -> None: # sdk-python#388: a busy host that misses the readiness wait has run no # application code. The claim is released for a retry, not failed. - worker, client = await make_owner(monkeypatch, activity_spawn_timeout=0.001) + worker, client = await make_owner(monkeypatch) + worker.activity_spawn_timeout = 0.001 marker = tmp_path / "ran" worker.activities["remote"] = write_ran_marker try: @@ -415,3 +439,29 @@ async def test_missed_spawn_readiness_releases_the_claim_as_retryable_worker_los assert worker._current_task_slots()["activity_available"] == 1 finally: await worker.stop() + + +async def test_shutdown_during_a_slow_start_aborts_without_waiting_for_readiness( + monkeypatch: pytest.MonkeyPatch, +) -> None: + worker, client = await make_owner(monkeypatch) + worker.activity_spawn_timeout = 120 + worker.activities["remote"] = slow_import_activity.stalled_import_activity + # Only spawned children import the handler module after this, and stall. + monkeypatch.setenv(slow_import_activity.STALL_ENV, "60") + try: + execution = asyncio.create_task(worker._run_activity_task(task())) + while not worker._remote_activity_processes: + await asyncio.sleep(0.001) + callback = next(iter(worker._remote_activity_processes)) + await asyncio.sleep(0.5) + assert not execution.done() + worker._local_activity_shutdown.set() + assert await asyncio.wait_for(execution, timeout=15.0) == "claim_aborted" + # The cancelled start joined its supervisor cleanly, so the slot returns. + assert callback.stopped is True + assert not worker._remote_activity_processes + client.fail_activity_task.assert_not_awaited() + client.complete_activity_task.assert_not_awaited() + finally: + await worker.stop() From 60b8b9909c51fe6c749d165f2a731b18eb75071d Mon Sep 17 00:00:00 2001 From: Richard McDaniel <1130888+rmcdaniel@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:11:52 +0000 Subject: [PATCH 3/3] Drop the remaining 'ran no application code' wording Co-Authored-By: Claude Opus 5.5 --- src/durable_workflow/worker.py | 5 +++-- tests/test_cooperative_remote_worker.py | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/durable_workflow/worker.py b/src/durable_workflow/worker.py index 686eef33..a4d14e13 100644 --- a/src/durable_workflow/worker.py +++ b/src/durable_workflow/worker.py @@ -5682,8 +5682,9 @@ def activity_spawn_timeout(self) -> float: 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 ran no application code: the worker stops the process - and releases the claim as a retryable ``worker_lost`` failure. + 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: diff --git a/tests/test_cooperative_remote_worker.py b/tests/test_cooperative_remote_worker.py index f59c320e..3a143c60 100644 --- a/tests/test_cooperative_remote_worker.py +++ b/tests/test_cooperative_remote_worker.py @@ -414,8 +414,8 @@ async def test_malformed_activity_spawn_timeout_environment_refuses_to_run( async def test_missed_spawn_readiness_releases_the_claim_as_retryable_worker_lost( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ) -> None: - # sdk-python#388: a busy host that misses the readiness wait has run no - # application code. The claim is released for a retry, not failed. + # sdk-python#388: a callback that misses the readiness wait on a busy host + # is stopped and joined. The claim is released for a retry, not failed. worker, client = await make_owner(monkeypatch) worker.activity_spawn_timeout = 0.001 marker = tmp_path / "ran"