Skip to content

[python/deepagents] give model activities a default heartbeat timeout - #350

Open
pingu1m wants to merge 4 commits into
temporalio:mainfrom
pingu1m:fix/deepagents-default-heartbeat
Open

pingu1m wants to merge 4 commits into
temporalio:mainfrom
pingu1m:fix/deepagents-default-heartbeat

Conversation

@pingu1m

@pingu1m pingu1m commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

  • Model calls (deepagents.invoke_model and deepagents.invoke_model_streaming) are scheduled with a default heartbeat_timeout of 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 own start_to_close_timeout or schedule_to_close_timeout; a zero value counts as unset, so only the close timeout that is in force caps it. A per-model activity_options, the plugin's model_activity_options, or an explicit heartbeat_timeout=None still decide the schedule.
  • The model activities call a synchronous model_provider on the activity's event loop, as before, because providers may create loop-bound objects such as an aiohttp session. DeepAgentsPlugin(model_provider_in_thread=True) builds the model (provider, then bind_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_profile is scheduled with the model options, so it gets the same default; it now auto-heartbeats, and builds the model on the same path.
  • Tools (deepagents.invoke_tool) and backend operations (deepagents.backend_op) get no default, since they run application code. They still auto-heartbeat when heartbeat_timeout is set.
  • backend_op calls 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.
  • The auto-heartbeater's timer beats repeat the latest details the application sent with activity.heartbeat(...) (starting from the previous attempt's), so they no longer replace a checkpoint with empty details.
  • README: the activity-options section documents the default, the cap, the opt-out, that tools and backend operations opt in, and 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_timeout is not part of command matching, so runs started before the default replay on the new code. test_history_without_heartbeat_timeout_replays records a model call scheduled without a heartbeat timeout (through the opt-out) and replays it with the default configuration.

Checklist

  1. 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

  2. How was this tested:

    • tests/test_model_activity.py: the default (10 s) on invoke_model, the cap by a shorter start-to-close (4 s), a per-model override, the None opt-out, and both zero configurations (start_to_close_timeout=0 with a positive schedule_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 both get_model_profile and the model call. test_slow_model_provider_keeps_heartbeating: with model_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_streaming gets the same default.
    • tests/test_tools.py: tool activities get no default, and user options win.
    • tests/test_backends.py: backend option overrides; with backend_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. With ActivityEnvironment: a sync method that needs the running loop works by default; a backend method's own fn= 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 different backend_ops_in_thread is refused.
    • tests/test_replay.py: the replay test above.
    • In python/deepagents: make sync, make lint, make test (267 passed on Python 3.14; 266 passed, 1 skipped on 3.11, on current main), and scripts/ci/check_conventions.py.
  3. 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.

@pingu1m
pingu1m requested a review from a team as a code owner October 31, 2026 03:42
@CLAassistant

CLAassistant commented Oct 31, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@pingu1m
pingu1m force-pushed the fix/deepagents-default-heartbeat branch from 2d277ad to 6bb9f79 Compare October 31, 2026 03:48

@brianstrauch brianstrauch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please limit default automatic heartbeats to model calls; tools and backend operations should opt in.

@brianstrauch brianstrauch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The backend dispatch change needs to preserve progress heartbeats for synchronous backends and keep native async methods independent of executor availability.

@brianstrauch brianstrauch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please ignore zero-valued close timeouts when capping the default heartbeat timeout.

@campoy

campoy commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

@pingu1m, could this default to 10 seconds instead of 30? That's what every other plugin now uses for #491. The timeout sets how fast a cancel arrives: in #491's measurements, a cancel took up to 23 seconds to reach a running activity with 30, and up to 7 with 10.

@pingu1m

pingu1m commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

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 histories/<major>.x/ layout from #565) with a test that records a model call scheduled without a heartbeat timeout and replays it with the default configuration, and refreshed the description.

@brianstrauch brianstrauch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two findings from the review. The 74 affected tests passed, and both findings were reproduced locally. Worker-crash recovery was not exercised.

Comment thread python/deepagents/README.md Resolved
@pingu1m pingu1m changed the title fix(deepagents): schedule plugin activities with a default heartbeat timeout [python/deepagents] give model activities a default heartbeat timeout Nov 17, 2026

@brianstrauch brianstrauch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@pingu1m

pingu1m commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Both threads are fixed.

discussion_r4605381437: a synchronous model_provider is called on the activity's event loop again, as on main, for invoke_model, invoke_model_streaming and get_model_profile, so providers that bind to the loop (an aiohttp session) work. The worker-thread build is now an explicit opt-in, DeepAgentsPlugin(model_provider_in_thread=True), for a provider that blocks longer than the heartbeat timeout; the README says so. test_loop_bound_model_provider_builds_on_the_loop covers the default (it raised no running event loop before), and test_slow_model_provider_keeps_heartbeating now uses the opt-in.

discussion_r4605382955: a zero close timeout is now ignored when capping, so only the active one applies. test_model_activity_heartbeat_ignores_zero_close_timeout covers both configurations (start_to_close_timeout=0 with a positive schedule_to_close_timeout, and the reverse); both gave a zero heartbeat timeout before.

@pingu1m
pingu1m force-pushed the fix/deepagents-default-heartbeat branch from 3ec2e99 to e0daab8 Compare November 19, 2026 04:21

@temporal-factory temporal-factory Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The backend dispatch change breaks previously working calls and can acknowledge cancellation before a synchronous operation has stopped. The background heartbeat can also overwrite progress needed by a retry.

Comment on lines 628 to 634
# 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),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +265 to +272
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

pingu1m and others added 2 commits November 27, 2026 14:21
… 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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

4 participants