Skip to content

Make cooperative callback spawn readiness configurable (default 30 s) - #390

Merged
rmcdaniel merged 3 commits into
mainfrom
general/388-spawn-readiness-timeout
Nov 26, 2026
Merged

rmcdaniel merged 3 commits into
mainfrom
general/388-spawn-readiness-timeout

Conversation

@rmcdaniel

@rmcdaniel rmcdaniel commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Fixes #388

Problem

SupervisedCallback.start() waited a fixed 5 s for the spawned supervisor and callback to report readiness. Each cooperative activity starts two spawn-context interpreters that import the SDK and the handler. When about eight started at once in a 2-CPU container, the wait raised TimeoutError. The worker then reported it as an ordinary activity failure. The callback was also never marked stopped, so it kept its activity slot.

Change

  • worker.activity_spawn_timeout (property) sets the readiness wait, default 30 s (DEFAULT_SPAWN_READINESS_TIMEOUT), or DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT from the environment. It must be a positive, finite number, and a malformed environment value refuses run() before any work is claimed. It isn't a constructor argument, because any change to Worker.__init__ counts as a replay change to the regression-corpus guard. Remote and prepared-local callbacks both use it. Prepared-local starts are still capped by the attempt's remaining budget.
  • A missed wait closes the owner channel and joins the supervisor (allowing at least as long as the readiness wait). Only a clean supervisor exit proves the callback was reaped. The start then raises CallbackSpawnTimeout (a CallbackProcessLost subclass) and marks the callback stopped, which frees its slot. If the supervisor doesn't exit cleanly, it stays a plain CallbackProcessLost and keeps its capacity, as before.
  • The error message names the timeout and the fix: cooperative activity callback did not report spawn readiness within 30s; the host may be overloaded. Raise Worker.activity_spawn_timeout (DURABLE_WORKFLOW_ACTIVITY_SPAWN_TIMEOUT) or lower max_concurrent_activity_tasks.
  • The remote worker answers a CallbackSpawnTimeout by releasing the claim through the existing cross-SDK worker_lost contract (release_worker_lost): non_retryable=False, details cause activity_spawn_readiness_timeout. This is a retryable worker condition, not an activity failure. The callback had not reported readiness, and it's proved stopped before the release, so two executions can't overlap. release_worker_lost takes an optional message, and the lease-renewal message is unchanged.
  • A slow start now races against ownership observation and worker shutdown, so claim loss or shutdown doesn't wait for readiness. Any start failure whose supervisor exits cleanly marks the callback stopped and returns its slot.
  • Docs: docs/reference/worker.md has a new "Cooperative callback start timeout" section, and there's a CHANGELOG entry.

Tests

  • test_concurrent_cooperative_spawns_on_one_cpu_all_report_ready: pins the test process, and so its spawned children, to one CPU, starts 8 cooperative callbacks concurrently, and checks that all are ready and return typed results.
  • test_missed_spawn_readiness_stops_the_callback_and_names_the_setting: the callback is proved stopped, its directory is removed, the handler never ran, and the message names activity_spawn_timeout.
  • test_missed_spawn_readiness_releases_the_claim_as_retryable_worker_lost: the worker sends one worker_lost failure (non_retryable=False, cause activity_spawn_readiness_timeout), no completion, and gets its activity slot back.
  • test_shutdown_during_a_slow_start_aborts_without_waiting_for_readiness: the handler module stalls on import in spawned children; shutdown aborts the start within seconds and frees the slot.
  • Validation tests for readiness_timeout, the activity_spawn_timeout property and the environment variable.
  • The one-CPU test checks the scenario under the new default. On a fast machine it also passes with the old 5 s wait. The 0.001 s tests cover the timeout behavior.

Local: ruff and mypy are clean. test_activity_process.py, test_cooperative_remote_worker.py, test_activity_lease_worker.py, test_activity_worker_lost.py, test_prepared_local_activity_worker.py, test_activity_checkpoint.py and test_telemetry.py pass. CI runs the full suites.

🤖 Generated with Claude Code

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 <noreply@anthropic.com>
@rmcdaniel

Copy link
Copy Markdown
Member Author

Independent review: BLOCKING at head 263078f

The code change looks correct, and I found no broken process-ownership or stop-proof invariant. The one blocker is CI: the required Target branch qualification check depends on regression-corpus (.github/workflows/ci.yml:488-490), and that job fails at this head, so the PR can't merge as it stands.

What I verified

  • Stop proof. _close_unready (src/durable_workflow/_activity_process.py:289-297) sets stopped = True only after close() has joined the supervisor and its exitcode == 0. The supervisor exits 0 only by returning through its finally, which runs _stop_owned_callback (terminate, then kill, then an unbounded join()) before it exits. So a clean exit means the callback was reaped.
    • If the supervisor is still alive after the join timeout, close() raises and leaves _joined false. If it exits non-zero, _close_unready raises a plain CallbackProcessLost. In both cases stopped stays false and the callback keeps its capacity, as before.
    • If the start is cancelled during the longer join, the outer except BaseException: close() handles it and stopped also stays false.
  • Late readiness. If the callback has already sent B when the owner times out, closing the owner channel still makes the supervisor terminate and join the callback before it exits 0. The stop proof holds in that race too (see note 2).
  • Slots. CallbackSpawnTimeout is a CallbackProcessLost, so _execute_cooperative_remote_callable takes the abandoned path (worker.py:3799). Its finally sees callback.stopped and discards the callback from _remote_activity_processes, and claim.track() sees the callback as stopped. The new worker test checks that activity_available returns to 1.
  • worker_lost release. _release_unready_remote_activity (worker.py:3871) runs only from except CallbackSpawnTimeout (worker.py:3929), which is raised only after the join is proven. That meets the precondition in release_worker_lost's docstring: confirmed stopped. It sends non_retryable=False with cause activity_spawn_readiness_timeout. The fail path is covered by the authority's governs, the authority hasn't been lost on this path, and the lease keeps renewing while start() waits. The default lease-renewal message is unchanged.
  • Error path. The except asyncio.TimeoutError catches only the readiness wait_for. After _close_unready finishes, the outer close() returns at once because _joined is already set. A failure inside _close_unready propagates as a plain CallbackProcessLost, which ends as claim_aborted in the worker.
  • Prepared-local. The configured timeout is passed through. Starts are still capped by wait_for(callback.start(), timeout=self.attempt.remaining()) (_prepared_local_activity.py:310). Any start failure still ends as LocalActivityExecutionAborted, as before. The only difference is that a CallbackSpawnTimeout callback is now proved stopped and discarded, where before the start's close() path decided.
  • Validation. Non-positive, NaN, inf, bool and str values are rejected, and the default is 30.
  • Local checks. I ran these with PYTHONPATH pointing at this head:
    • test_activity_process.py, test_cooperative_remote_worker.py, test_activity_worker_lost.py and test_prepared_local_activity_worker.py: 139 passed.
    • ruff check src tests and mypy src are clean.
    • The three new spawn tests, run 9 times pinned to one CPU with taskset -c 0, passed every time (about 3.5 s per run).
  • Docs. docs/reference/worker.md has no locale copies, and the docs-portal check passes.

BLOCKING

  1. The Regression corpus CI job fails, and the required Target branch qualification check depends on it. The failure message is replay implementation changed but its corpus has no evidence on a newly added fixture path (base=177, current=177).
    • Cause: the replay guard in regression-corpus-policy.json matches changed worker.py functions whose text contains history. Here that function is Worker.__init__, which changes for activity_spawn_timeout at worker.py:1505. The other changed functions don't match.
    • This change has nothing to do with replay, but recent PRs that touched worker.py (Read the WorkerReplayClock entry carrier in replay_now() #380 to Keep the worker running through a Server failover's 500 and 503 #383) each added a fixture under tests/fixtures/replay_regressions/.
    • Fix: add a fixture in the same way, or adjust the policy if that is allowed. Either way it needs a new commit, so a new head.

Non-blocking

  1. "No application code ran" isn't strictly guaranteed. This claim appears at _activity_process.py:56, worker.py (_release_unready_remote_activity), docs/reference/worker.md:42 and CHANGELOG.md:14. The callback sends B and then immediately calls the handler. If the owner's timeout fires while B is on its way, the handler may already have started before the supervisor kills it. The release is still safe, because the callback is physically joined first, but the wording should say "almost certainly did not run" or "was stopped before reporting readiness".
  2. The concurrency test doesn't catch the original bug on a fast host. test_concurrent_cooperative_spawns_on_one_cpu_all_report_ready (tests/test_activity_process.py:305-325) does start 8 cooperative callbacks concurrently on one CPU, which meets the issue's wording. But I ran the same test body against origin/main, with its fixed 5 s wait, and it passed 3 out of 3 times in about 2.7 s. So it is a capacity smoke test. What actually tests the new behaviour is the two 0.001 s timeout tests. It also drives SupervisedCallback directly rather than through the worker. The elapsed < 30 assertion is loose enough that it shouldn't flake.
  3. The 0.001 s timeout tests have a small flake margin. Lines tests/test_activity_process.py:290 and tests/test_cooperative_remote_worker.py:391 use readiness_timeout=0.001, so the join budget is max(5, 0.001) = 5 s. In that time the supervisor has to finish its spawn bootstrap, start the callback, see the owner's EOF and reap the callback. A very overloaded CI runner could exceed 5 s and fail with a plain CallbackProcessLost. That is unlikely, and it failed in none of my one-CPU runs.
  4. A slow start isn't raced against cancellation or claim loss. await callback.start() (worker.py:3782) is not raced with the observation or shutdown tasks. So a cancel request, or an elapsed deadline, that arrives during a slow start is only acted on after readiness or the timeout. That can now be up to 30 s, or about 60 s counting the join, where before it was 5 s. Ownership stays correct and shutdown still cancels the start, but cooperative-cancellation cleanup can be later than it was. The remote default is also not bounded by the activity's start-to-close or heartbeat deadlines, unlike prepared-local. Consider racing start() against observation and shutdown.
  5. Spawn timeout combined with a cancel request. If cancellation was requested during the start, the abandoned path first acknowledges the cancellation with the _acknowledge_stopped_remote_activity call at worker.py:3815. The body then also sends the worker_lost release, which the Server will probably refuse. release_worker_lost handles that as False, so the result is claim_aborted plus a warning log. That's harmless, but you could skip the release when the claim's status shows cancel_requested.

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 <noreply@anthropic.com>
@rmcdaniel

Copy link
Copy Markdown
Member Author

Independent review: PASS at head c8303f8

This is a re-review of the changes since 263078f. The earlier blocker is fixed, and I found nothing new that is unsafe. When I looked, the Python 3.10–3.15 and integration jobs at this head were still pending. Regression corpus passes.

What I verified

  • Corpus gate (was the blocker). Worker.__init__ is unchanged. Running scripts/ci/validate-regression-corpus.py --base-ref <merge-base> locally gives "status": "pass", and the CI Regression corpus job passes.

  • Marking stopped in start()'s generic except (_activity_process.py:289-294). stopped is set only when close() has finished and _exitcode == 0. _exitcode is assigned only in close(), after join(), and only when the supervisor is no longer alive.

    • If close() raises (the supervisor is still alive), or is itself cancelled, the if never runs and stopped stays false.
    • If Process.start() failed, _started is false, _exitcode stays None, and nothing is marked stopped.
    • The supervisor exits 0 only by returning through its finally. That finally terminates, kills and does an unbounded join() on the callback. So exit 0 proves the callback was reaped, whatever the reason the owner gave up: a cancel, a non-B boundary, or a disconnect.
    • This also improves on the old behaviour. Before, a start that failed after a clean supervisor exit fell through to stop() on a closed socket and kept its slot for good. Remote and prepared-local finish() both benefit.
  • Cancelled start (worker.py:3789-3800).

    • If observation or shutdown finishes first, the start task is cancelled and gathered, and the result is _RemoteActivityExecutionAborted, so claim_aborted. No worker_lost is sent, which is right when the claim was lost or the worker is shutting down.
    • A cancel during the first readiness wait reaches the generic except, which joins with 5 s.
    • A cancel during the long _close_unready join also reaches the generic except, which joins again and marks stopped only on exit 0.
    • If start finishes at the same moment as observation, starting.cancel() does nothing. A started callback then goes through the normal stop() path (S, then X). A CallbackSpawnTimeout that coincides with claim loss is swallowed into claim_aborted, and that callback is already stopped.
    • The start task begins running before asyncio.wait can return. So it can't be cancelled before Process.start() and leave an unspawned callback in the process set.
  • The worker_lost release still happens only through except CallbackSpawnTimeout, after the proven join. It is unchanged apart from the comment.

  • Setting and validation. The property reads the environment variable once and caches it. The setter validates the value, and bool is rejected. _begin_run (worker.py:5704) refuses a malformed environment value before any work is claimed. Prepared-local reads the same property.

  • Join margin is now at least 10 s (_activity_process.py:301).

  • New shutdown test. test_shutdown_during_a_slow_start_aborts_without_waiting_for_readiness exercises the cancelled-start path for real. The callback stalls at import for 60 s, and only in spawned children. The test checks:

    • the start is cancelled by shutdown;
    • the callback is proven stopped;
    • the slot is returned;
    • no fail or complete call is sent.

    No slow_import process was left behind after the runs.

  • Local checks. These ran with PYTHONPATH=src:.:

    • test_activity_process.py, test_cooperative_remote_worker.py, test_activity_worker_lost.py, test_prepared_local_activity_worker.py and test_activity_lease_worker.py: 178 passed.
    • ruff check src tests and mypy src are clean.
    • The four spawn and slow-start tests, run 6 times pinned to one CPU with taskset -c 0, passed every time (about 4.2 s per run).

Non-blocking

  1. Leftover wording. The Worker.activity_spawn_timeout property docstring (worker.py:~5685) still says "A start that misses the wait ran no application code". The comment in test_missed_spawn_readiness_releases_the_claim_as_retryable_worker_lost also says "has run no application code". The docs and CHANGELOG are fixed.
  2. Conservative slot leak if the start is cancelled twice. If the outer activity task is cancelled while it is gathering the already-cancelled start task (worker.py:3793), the generic except's close() is cancelled too, so stopped stays false. finally then calls stop() (worker.py:3826), which fails on the closed socket. That path can join with exit 0, but stop() never sets stopped. The slot is kept, and worker.stop() reports an unconfirmed callback. This is safe because no false stop proof is produced, and it is the same stop()-after-close pattern as before. A possible follow-up: in stop(), mark stopped when its fallback close() finds _exitcode == 0.
  3. Unchanged from the first review: earlier note 6 (a spawn timeout combined with a cancel request sends a release that is probably refused), and the one-CPU concurrency test is a smoke test. The PR body now says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

@rmcdaniel

Copy link
Copy Markdown
Member Author

Independent review: PASS at head 60b8b99

I reviewed the change since c8303f8, which I passed earlier (previous review). It touches only text, with no code change:

  • The Worker.activity_spawn_timeout docstring (src/durable_workflow/worker.py:5684-5687) no longer says "ran no application code". It now says the start "had not reported its handler started", and that the worker stops and joins the process before it releases the claim as worker_lost. That matches what the code does.
  • The comment in test_missed_spawn_readiness_releases_the_claim_as_retryable_worker_lost (tests/test_cooperative_remote_worker.py:417-418) is reworded the same way.

That fixes non-blocking note 1. Notes 2 and 3 are still open; they are safe behavior, as described in the previous review.

CI at this head has finished and every check passes:

  • Python 3.10–3.15, lint, package, integration and Regression corpus
  • Target branch qualification and SonarCloud
  • CodeQL and the docs portal

The published-* jobs were skipped. GitHub reports the merge state as CLEAN.

@rmcdaniel
rmcdaniel merged commit b612402 into main Nov 26, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cooperative activity spawn readiness times out after a fixed 5 s under load

1 participant