Repository navigation
Conversation
2d277ad to
6bb9f79
Compare
brianstrauch
left a comment
There was a problem hiding this comment.
Please limit default automatic heartbeats to model calls; tools and backend operations should opt in.
brianstrauch
left a comment
There was a problem hiding this comment.
The backend dispatch change needs to preserve progress heartbeats for synchronous backends and keep native async methods independent of executor availability.
brianstrauch
left a comment
There was a problem hiding this comment.
Please ignore zero-valued close timeouts when capping the default heartbeat timeout.
|
Done in e957cab: the default is now 10 seconds, so the heartbeater beats every 5 seconds, and the README and tests use 10. I also replaced the committed pre-default history (it sat outside the |
brianstrauch
left a comment
There was a problem hiding this comment.
Two findings from the review. The 74 affected tests passed, and both findings were reproduced locally. Worker-crash recovery was not exercised.
brianstrauch
left a comment
There was a problem hiding this comment.
I reproduced a regression with model factories that need the activity’s event loop.
Without a heartbeat timeout the auto-heartbeater never beats, so the server cannot tell a crashed worker from a slow model call until start-to-close, and a cancelled workflow's model call never learns it was cancelled, since a Python activity sees cancellation only through a heartbeat response. Model calls (invoke_model, invoke_model_streaming) and get_model_profile are now scheduled with a default heartbeat_timeout of 10 seconds, the value the other plugins use. The default is capped by the schedule's own start_to_close_timeout or schedule_to_close_timeout, whichever is set. A per-model activity_options, the plugin's model_activity_options, or an explicit heartbeat_timeout=None still decide the schedule. Tools and backend operations get no default since they run application code; they still auto-heartbeat when heartbeat_timeout is set. The model activities call a synchronous model_provider on the activity's event loop, since providers may create loop-bound objects such as an aiohttp session; DeepAgentsPlugin(model_provider_in_thread=True) builds the model (the provider, then bind_tools or bind) on a worker thread instead, so a provider that blocks longer than the heartbeat timeout keeps heartbeating. A zero close timeout counts as unset when capping. backend_op runs synchronous backend methods and factories on a worker thread, with heartbeats handed back to the activity's loop, and native async ones directly on the loop. heartbeat_timeout is not part of command matching, so histories recorded before the default replay on the new code. Closes temporalio#341
|
Both threads are fixed. discussion_r4605381437: a synchronous discussion_r4605382955: a zero close timeout is now ignored when capping, so only the active one applies. |
3ec2e99 to
e0daab8
Compare
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| # Sync methods run on a worker thread so they don't block the event | ||
| # loop the heartbeat task needs; async methods run on the loop. | ||
| result = await _call_backend( | ||
| method, | ||
| *_serde.load_backend_result(input.args), | ||
| **_serde.load_backend_result(input.kwargs), | ||
| ) |
There was a problem hiding this comment.
[P2] Preserve an on-loop path for loop-bound backend methods
backend_op now offloads every method that is not declared async def, even when heartbeats are disabled. A synchronous backend method that needs the running loop, such as an aread wrapper that creates an aiohttp session before returning a coroutine, now fails with RuntimeError: no running event loop. I verified that a loop-dependent method succeeds on the base revision and fails on HEAD. Keep an on-loop path and make thread execution explicit for methods that can use it (AGENTS.md:71–72).
There was a problem hiding this comment.
Fixed in 8405d3c. backend_op calls a sync backend method on the activity event loop again by default and awaits what it returns. Running it on a worker thread is now explicit: DeepAgentsPlugin(backend_ops_in_thread=True), the same shape as model_provider_in_thread, documented in the README and the plugin docstring. Async methods run on the loop either way; sync factories still run on a thread, as before this PR. test_sync_backend_op_runs_on_the_loop_by_default covers a sync aread that needs the running loop (passes by default, raises with the option), and the blocking and progress-heartbeat tests now opt in.
| ) | ||
| return fn(*args, **kwargs) | ||
|
|
||
| result = await asyncio.to_thread(run) |
There was a problem hiding this comment.
[P2] Wait for running backend work before acknowledging cancellation
Cancelling the await on asyncio.to_thread() does not stop a synchronous backend method that has already started. I verified that the activity raises CancelledError while the backend is still running. For a workflow using WAIT_CANCELLATION_COMPLETED, this can let cleanup proceed while a cancelled write is still modifying external state. Wait for the running method to exit before acknowledging cancellation, or cancel it cooperatively.
There was a problem hiding this comment.
Fixed in 8405d3c. The thread path keeps the executor future and awaits it through asyncio.shield; on cancellation it waits for the thread to return before re-raising CancelledError. This applies wherever a sync call goes to a thread (backend_ops_in_thread, sync backend factories, model_provider_in_thread). test_cancelled_backend_op_waits_for_the_running_thread cancels during a blocked sync write and checks the activity is still pending until the write returns. The README notes the behavior.
| if context is not None and context.heartbeat is not None: | ||
| heartbeat = context.heartbeat | ||
|
|
||
| def heartbeat_from_thread(*details: Any) -> None: | ||
| loop.call_soon_threadsafe(heartbeat, *details) | ||
|
|
||
| activity._Context.set( # pyright: ignore[reportPrivateUsage] | ||
| dataclasses.replace(context, heartbeat=heartbeat_from_thread) |
There was a problem hiding this comment.
[P2] Preserve backend checkpoints in timer heartbeats
Forwarding progress heartbeats fixes the thread error, but the newly concurrent timer still sends empty details. With a sync backend that checkpoints and then blocks past the next timer tick, I observed the checkpoint as the final heartbeat on base and an empty heartbeat after it on HEAD. Since Temporal retains the latest heartbeat details, a retry can lose the saved checkpoint. Have timer heartbeats retain the latest application-supplied details.
There was a problem hiding this comment.
Fixed in 8405d3c. While the auto-heartbeater runs, it wraps the activity context heartbeat so it records the latest details the application sends, and the timer beats repeat them. It starts from the previous attempt's heartbeat_details, so a retry that has not re-checkpointed yet keeps them too. test_timer_heartbeats_keep_the_latest_checkpoint (sync method on a thread and async method on the loop) and test_timer_heartbeats_keep_the_previous_attempts_checkpoint cover it.
| ) | ||
|
|
||
|
|
||
| async def _call_backend(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: |
There was a problem hiding this comment.
[P3] Make the backend dispatch callable positional-only
A backend method called with fn=... used to receive that keyword unchanged. The new helper binds it to its own fn parameter, which already received the backend method positionally, so the activity raises TypeError before invoking the backend. I verified this against both revisions. Make the helper's callable parameter positional-only.
There was a problem hiding this comment.
Fixed in 8405d3c. _call_backend and the new on-loop _call_on_loop take the callable positional-only, so a backend method's fn= keyword reaches it. test_backend_op_forwards_fn_keyword covers both paths.
… keep heartbeat checkpoints backend_op calls a sync backend method on the activity's event loop again, since a method may need the running loop. DeepAgentsPlugin( backend_ops_in_thread=True) runs sync methods on a worker thread instead, so a blocking method keeps heartbeating. A cancelled call on a worker thread now reports the cancellation only after the thread returns. Timer heartbeats repeat the latest details the application sent (or the previous attempt's), instead of empty details that replace a checkpoint. The dispatch helpers take the callable positionally only, so a backend method's own fn= keyword reaches it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was changed
deepagents.invoke_modelanddeepagents.invoke_model_streaming) are scheduled with a defaultheartbeat_timeoutof 10 seconds, the value the other plugins use ([Feature Request] Default heartbeat timeout for every plugin's own activities #491). The default never exceeds the schedule's ownstart_to_close_timeoutorschedule_to_close_timeout; a zero value counts as unset, so only the close timeout that is in force caps it. A per-modelactivity_options, the plugin'smodel_activity_options, or an explicitheartbeat_timeout=Nonestill decide the schedule.model_provideron the activity's event loop, as before, because providers may create loop-bound objects such as anaiohttpsession.DeepAgentsPlugin(model_provider_in_thread=True)builds the model (provider, thenbind_tools/bind) on a worker thread instead, for a provider that blocks longer than the heartbeat timeout, such as one loading a local model, so it keeps heartbeating.deepagents.get_model_profileis scheduled with the model options, so it gets the same default; it now auto-heartbeats, and builds the model on the same path.deepagents.invoke_tool) and backend operations (deepagents.backend_op) get no default, since they run application code. They still auto-heartbeat whenheartbeat_timeoutis set.backend_opcalls a synchronous backend method on the activity's event loop by default, as before, because a method may need the running loop.DeepAgentsPlugin(backend_ops_in_thread=True)runs synchronous methods on a worker thread instead, so a blocking method such as a shell command keeps heartbeating. Synchronous factories run on a worker thread, as before. On a thread,activity.heartbeat(...)is handed back to the activity's loop, and a cancellation is reported only after the thread returns. Async methods and factories run directly on the loop, so they do not wait for a free executor thread.activity.heartbeat(...)(starting from the previous attempt's), so they no longer replace a checkpoint with empty details.backend_ops_in_thread.Why?
See #341. Without a heartbeat timeout the auto-heartbeater never beats, so the server cannot tell a crashed worker from a slow model call until start-to-close (five minutes), and a cancelled workflow's model call never learns it was cancelled, since a Python activity sees cancellation only through a heartbeat response. With 10 seconds, the heartbeater beats every 5 seconds, and the SDK sends at most one heartbeat per 8 seconds (80% of the timeout), so a cancel reaches a running model call within about the heartbeat timeout, and a crashed worker's call is retried after 10 seconds.
Replay:
heartbeat_timeoutis not part of command matching, so runs started before the default replay on the new code.test_history_without_heartbeat_timeout_replaysrecords a model call scheduled without a heartbeat timeout (through the opt-out) and replays it with the default configuration.Checklist
Closes [Bug] deepagents: model and tool activities get no heartbeat timeout by default, so the auto-heartbeater is inert, crash recovery waits out start-to-close, and cancellation never reaches a running model call #341
How was this tested:
tests/test_model_activity.py: the default (10 s) oninvoke_model, the cap by a shorter start-to-close (4 s), a per-model override, theNoneopt-out, and both zero configurations (start_to_close_timeout=0with a positiveschedule_to_close_timeout, and the reverse).test_loop_bound_model_provider_builds_on_the_loop: a provider that needs the running loop works by default for bothget_model_profileand the model call.test_slow_model_provider_keeps_heartbeating: withmodel_provider_in_thread=True, a provider that blocks 2.5 s under a 1 s heartbeat timeout succeeds on the first attempt for both (it heartbeat-times out with the model built on the event loop).tests/test_streaming.py:invoke_model_streaminggets the same default.tests/test_tools.py: tool activities get no default, and user options win.tests/test_backends.py: backend option overrides; withbackend_ops_in_thread=True, a blocking sync backend op that outlasts its heartbeat timeout still completes and sync progress heartbeats reach the server; an async op runs while the default executor is busy. WithActivityEnvironment: a sync method that needs the running loop works by default; a backend method's ownfn=keyword reaches it; a cancelled op on a thread waits for the method to return; timer heartbeats keep the latest and the previous attempt's checkpoint.tests/test_activity_registration.py: a second plugin instance with a differentbackend_ops_in_threadis refused.tests/test_replay.py: the replay test above.python/deepagents:make sync,make lint,make test(267 passed on Python 3.14; 266 passed, 1 skipped on 3.11, on current main), andscripts/ci/check_conventions.py.Any docs updates needed?
README updated here, including the cancellation bound with the SDK's heartbeat throttling.
Not covered: crash recovery and cancellation delivery are not exercised by killing a worker or timing a cancel; they follow from the heartbeat schedule the tests assert.