Skip to content

strands_agents: give model and sandbox activities a 10-second default heartbeat timeout - #504

Merged
campoy merged 5 commits into
mainfrom
feat/strands-default-heartbeat-timeout
Nov 14, 2026
Merged

campoy merged 5 commits into
mainfrom
feat/strands-default-heartbeat-timeout

Conversation

@campoy

@campoy campoy commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

TemporalAgent, TemporalModel and TemporalSandbox now default heartbeat_timeout to 10 seconds instead of None, so the model and sandbox activities heartbeat by default.

  • The activities already heartbeat on a timer at half the timeout (auto_heartbeater). A timeout you set wins, and heartbeat_timeout=None turns heartbeats off, as before.
  • The timer now starts when the activity does, not at its first await. Before, a model factory that blocked the event loop for over half the timeout made the attempt fail with a heartbeat timeout. Now it takes the whole timeout, which is when the warning below fires.
  • strands_get_model_config is now scheduled without a heartbeat timeout. It builds the model and reads its config synchronously, so it can't heartbeat, and a model factory slower than the timeout would fail it.
  • A model factory slower than the heartbeat timeout now logs a warning on the worker. The factory runs on the worker's event loop, so the heartbeat timer can't run while it builds the model, and that attempt may fail with a heartbeat timeout. The next attempt reuses the built model.
  • The docstrings and the README say what the default does and how to turn it off. They also say that a model factory or model call that blocks the event loop longer than the timeout fails. In Strands 1.56.0, SageMakerAIModel and LlamaAPIModel call their synchronous clients on the loop, so they need heartbeat_timeout=None (or a longer timeout).

activity_as_tool and activity_as_hook run your own Activities, so they stay as they are.

Why not build models on a thread?

An automated review round suggested it, so a slow factory couldn't block the heartbeat timer. But that broke factories that need a running event loop, such as one that builds an aiohttp session, and the fix for that made this PR much bigger. A factory slower than 10 seconds is rare, and the retry reuses the model it built, so a warning that says what happened is enough.

Why?

Without a heartbeat timeout, these activities never heartbeat. So a cancel never reaches a running model call or sandbox command, and it runs to the end. A lost worker also goes unnoticed until the start-to-close timeout. #491 has the details, and the measurements behind 10 seconds.

Does this break anything? Not replay: when core replays a scheduled Activity, it only compares its ID and type, and the replay tests pass. But a call that didn't set heartbeat_timeout now heartbeats, which in Temporal Cloud is at most one Action every 8 seconds of a running call.

TemporalMCPClient isn't in this PR. Since #435, Strands requires temporalio-mcp 0.4, whose Activities heartbeat (#494). But Strands' TemporalMCPClient still passes heartbeat_timeout=None, so its Activities don't heartbeat yet. A follow-up can give it the 10-second default too.

This works with #497, which makes a cancelled tool call cancel the agent. I merged its branch on top of this one, and its cancellation tests pass with these defaults.

Checklist

  1. Closes [Feature Request] strands_agents: give model and sandbox activities a 10-second default heartbeat timeout #498

  2. How was this tested:

    • test_model now checks the heartbeat timeouts in History: none for strands_get_model_config, 10 seconds for invoke_model. Without the change it fails with assert [None, None] == [None, datetime.timedelta(seconds=10)].
    • test_sandbox_operations_are_durable_and_factory_runs_for_each_activity now checks that all seven sandbox Activities get 10 seconds. Without the change, they get none.
    • test_heartbeat_timer_counts_from_the_start blocks the event loop for 0.7 seconds under a 1-second heartbeat timeout, and checks that the first heartbeat comes before the timeout. With the old timer, the first heartbeat would come 1.2 seconds in, so the test fails with assert ([]).
    • test_slow_model_factory_logs_a_warning builds a model with a factory that takes 0.3 seconds, under a 0.1-second heartbeat timeout, and checks the warning. A fast factory logs nothing. Without the warning it fails with assert ("Building model 'slow' took" in '') == True.
    • Locally, make test (262 passed, 1 skipped), make lint and the conventions check pass, on Python 3.12 with uv 0.12.24. With Breaking: propagate Python Strands tool cancellation #497 merged in, its two cancellation test files and these tests pass (53 passed).
  3. Any docs updates needed?
    The docstrings and the README are updated here. Release notes should mention the new default, and how to turn it off.

… heartbeat timeout

TemporalAgent, TemporalModel and TemporalSandbox defaulted heartbeat_timeout to
None, and their activities heartbeat only when it's set. So a cancel never
reached a running model call or sandbox command, and a lost worker went
unnoticed until the start-to-close timeout.

Default it to 10 seconds. The activities already heartbeat on a timer at half
the timeout. Passing None still turns heartbeats off. The model config read runs
synchronously and can't heartbeat, so it's scheduled without a heartbeat
timeout.

Part of #491.
@campoy
campoy marked this pull request as ready for review November 13, 2026 01:13
@campoy
campoy requested a review from a team as a code owner November 13, 2026 01:13
Comment on lines +1 to +2
import asyncio
import inspect

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

these seem like dangerous and unrelated imports, why are we now importing asyncio to set a timeout??

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.

Fair, those came from an automated review round that went well past what this PR is about. I took them out: factories run as they did before. A factory slower than the heartbeat timeout now just logs a warning, and the README says which models block the event loop and need heartbeat_timeout=None.

self._builds: dict[str, asyncio.Future[Model]] = {}

def _get_model(self, name: str | None) -> Model:
async def _model(self, name: str | None) -> Model:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

why does this need to be async now? could this be a breaking change?

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.

It's synchronous again. And yes, running factories on a thread broke factories that need a running event loop, which is one more reason to drop it.

Comment on lines +121 to +122
# Concurrent calls share one build. The shield keeps a cancelled call
# from cancelling the build the others wait for.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What does this mean? Can you clarify/simplify?

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.

That comment was about sharing one model build between concurrent calls. It's gone with the rest of that change.

self._builds[name] = build
return await asyncio.shield(build)

async def _build(self, name: str) -> Model:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why are we building factories to set a timeout?

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.

We shouldn't. The thread was there so a slow factory on a cold worker couldn't block the heartbeat timer. That's rare, and the retry reuses the model it built, so now a slow factory just logs a warning that says what happened.

Comment on lines +51 to +53
on first use, then cached for the worker's lifetime. A synchronous factory
runs on a thread; an async one runs on the worker's event loop. Use the
same name in ``TemporalAgent(model=...)`` inside the workflow.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

same issue here

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.

Same fix: models takes the same factories as before.

Running factories on a thread kept a slow one from blocking the heartbeat
timer, but it broke factories that need a running event loop, and the fix for
that grew the change well past the heartbeat default. Go back to building
models as before. A factory slower than the heartbeat timeout now logs a
warning that says why the attempt may fail. The README and TemporalModel's
docstring say that a factory or model call that blocks the event loop longer
than the timeout fails, and name the Strands models that do.
The heartbeat task only started sleeping at the activity's first await, so a
factory that blocked the event loop for more than half the timeout pushed the
first heartbeat past the timeout, while the slow-factory warning only fires at
the full timeout. The timer now uses loop.call_later, as in Google ADK and
google-genai, so it counts from the start of the activity and a block shorter
than the timeout only delays the first heartbeat.

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I like this better now, thanks

@campoy
campoy merged commit 4ae1b5c into main Nov 14, 2026
27 checks passed
@campoy
campoy deleted the feat/strands-default-heartbeat-timeout branch November 14, 2026 21:31
campoy added a commit that referenced this pull request Nov 16, 2026
…ut (#551)

## What was changed

All 16 Gemini call activities (model calls, files, file search uploads,
interactions and managed agents) now heartbeat on a timer, and
`TemporalAsyncClient` gives them a 10-second `heartbeat_timeout` by
default.

- The timer beats at half the heartbeat timeout, and the first beat goes
out half the timeout into the call. So with the default, a call shorter
than 5 seconds sends none. Without a heartbeat timeout, the timer does
nothing.
- Temporal caps `heartbeat_timeout` at the activity's
`start_to_close_timeout`, and the timer uses the capped value. So a
shorter timeout, including a per-model-call `http_options.timeout` or
the Interactions and Agents `timeout` argument, makes beats come sooner.
With `http_options.timeout=2000`, History records a 2-second heartbeat
timeout, and a 1.7-second call sends one heartbeat. `files.upload`,
`files.download`, `files.register_files`, and file search store uploads
pass `http_options.timeout` to the HTTP client instead.
- The timer uses `loop.call_later` instead of a task, as Strands (#504)
and Google ADK (#520) do. A task only starts its sleep at the call's
first `await`, so anything that blocks the event loop before then pushes
every beat back.
- The interaction streams used to heartbeat once per event. They now use
the same timer, so a model that's quiet for a while before its first
event doesn't time out. With `heartbeat_timeout=None` or `timedelta(0)`,
streams no longer heartbeat per event and cannot receive cancellation.
With heartbeats enabled, a quiet stream stays alive until its HTTP or
activity timeout; heartbeats no longer check stream progress.
- The 10-second default is added to every config that leaves
`heartbeat_timeout` out, including your own `activity_config`. A timeout
you set wins, and `heartbeat_timeout=None` (or `timedelta(0)`) turns
heartbeats off.
- The README and the `activity_config` docstring say what the default
does, what it costs, how to turn it off, and how to upgrade and roll
back.

`activity_as_tool` runs your own activities, so it stays as it is. MCP
is out of scope for now.

Does any of these activities block the event loop, so the timer can't
run? Mostly no: google-genai reads upload files with `anyio`, and model,
files and file search store calls refresh credentials on a thread. But
on Vertex AI, `interactions` and `agents` don't. They get their token
through a sync provider that calls `credentials.refresh()` on the event
loop. That happens when the worker's `genai.Client` has no token yet,
and again when the token expires, about once an hour.

I checked it on a local dev server with a credential refresh that takes
11 seconds and HTTP 200 responses:

| Call | `heartbeat_timeout` | Result |
|---|---|---|
| `agents.list()` | default | fails with `activity Heartbeat timeout` |
| `interactions.create()` | default | fails with `activity Heartbeat
timeout` |
| `agents.list()` | `None` | succeeds |
| `models.generate_content()` | default | succeeds, and heartbeats |

With a 4-second refresh, both `agents.list()` and
`interactions.create()` succeed. This is google-genai's behavior, so
following AGENTS.md, the README documents it as a limit instead of
working around it here: if your credential refresh can be slower than
the heartbeat timeout, set a longer one, or `None`. A blocked loop also
stops the timers of other activities sharing it, so a slow refresh can
fail other running Gemini calls even if it takes less than their
heartbeat timeout. Moving that refresh off the event loop is a fix for
google-genai, outside this PR.

## Why?

Without timer heartbeats, most of these activities never hear a cancel,
so a running call goes on to the end. Earlier interaction streams could
receive cancellation through their per-event heartbeats, but only once
an event arrived. A lost worker also goes unnoticed until the 60-second
start-to-close timeout. And you couldn't set a heartbeat timeout
yourself, since the calls didn't heartbeat: most calls longer than it
failed. #491 has the details, and the measurements behind 10 seconds.

## Breaking change in 1.0.0

Replay still works: core only compares an activity's ID and type, and
heartbeats aren't in History.
`test_replay_history_recorded_with_text_bytes_in_the_input` replays a
History recorded with no heartbeat timeout, and it passes. But a passing
replay doesn't mean mixed versions work.

`temporalio-google-genai` 1.0.0 adds timer heartbeats and the 10-second
default. The timeout is recorded when the activity is scheduled. If a
worker on a version before 1.0.0 runs that activity, it doesn't
heartbeat on a timer (the interaction streams only heartbeat per event),
so a call longer than 10 seconds fails with a heartbeat timeout. Retries
keep the recorded timeout, so they fail the same way, and rolling back
doesn't clear it either. #520 measured this on a local dev server: an
activity that doesn't heartbeat failed 10.02 seconds in, and both
attempts of a retried one failed the same way.

The README has the guidance for in-flight runs:

- To upgrade to 1.0.0, put this version on every worker that runs the
Gemini activities before any workflow worker. If the same workers run
both, deploy with `heartbeat_timeout=None` in `activity_config`, and
remove that setting in a later deploy.
- To roll back from 1.0.0, first deploy this version with
`heartbeat_timeout=None`, wait until the calls scheduled before that
deploy finish, and then roll back.
- Runs pinned with Worker Versioning avoid both cases when their Gemini
activities use the workflow's task queue.

A config you pass replaces the defaults. Keep your activity timeouts
when disabling heartbeats; the README now shows
`ActivityConfig(start_to_close_timeout=timedelta(seconds=60),
heartbeat_timeout=None)` for these steps.

There are more costs. A call that didn't set `heartbeat_timeout` now
heartbeats, which in Temporal Cloud is at most one Action every 8
seconds of a running call with the default, and more often when a
shorter start-to-close timeout caps it. A cancelled call can send one
more as it stops, since core sends the heartbeat it was holding back
when an activity is cancelled. A call that blocks the worker's event
loop for longer than the heartbeat timeout now fails with a heartbeat
timeout. On Vertex AI, that includes a slow credential refresh in
`interactions` and `agents`.

## Checklist

1. Closes #550

2. How was this tested:
- `test_full_integration_with_mock_client` runs the real activities in a
workflow with four `activity_config`s, and reads the heartbeat timeout
of all 10 scheduled activities from History: no config and a config
without `heartbeat_timeout` get 10 seconds, `None` gets none. In
`heartbeat-1s`, all 10 calls take 1.5 seconds under a 1-second heartbeat
timeout with no retries, so it passes only if they heartbeat. Without
the change, the default cases fail with `assert [None, None, ...ne,
None, ...] == [datetime.tim...onds=10), ...]` and `heartbeat-1s` fails
with `TimeoutError: activity Heartbeat timeout`.
- `test_activity_heartbeats_on_a_timer` runs each of the 16 activities
three ways. The activity helper also checks that the test cases cover
every activity registered by `GeminiApiCaller.activities()`. A call that
takes 0.5 seconds under a 0.2-second heartbeat timeout heartbeats; a
fast call under the 10-second default sends none; and a 0.1-second call
with no heartbeat timeout sends none. Without the change, all 16 slow
cases fail with `assert False == True`. Without the timer's early return
for a missing timeout, all 16 `off` cases fail with `AttributeError:
'NoneType' object has no attribute 'total_seconds'`.
- `test_workflow_cancellation_stops_gemini_call` cancels a workflow
during a model call and a quiet interaction stream. Both cases wait for
the running SDK call to receive cancellation before the worker shuts
down.
- `test_interaction_stream_does_not_heartbeat_per_event` drains a
4-event interaction stream and expects no heartbeats. Without the change
it fails with `assert [(), (), (), ()] == []`.
- The Vertex refresh table and the 2-second timeout case above come from
a separate script on a local dev server: a real
`genai.Client(vertexai=True)` whose credentials sleep in `refresh()`,
mocked HTTP responses, and no retries. It reads the heartbeat timeout
from History and polls the workflow's pending activities for heartbeats
the service received.
- Locally, `make test` (267 passed, 1 skipped), `make lint`, `make
build`, the wheel check and the conventions check pass, on Python 3.12
with uv 0.13.5.

3. Any docs updates needed?
The README and the docstring are updated here. Release notes should call
this out as breaking, with the upgrade and rollback steps, how to turn
heartbeats off, and the Vertex AI credential refresh limit.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] strands_agents: give model and sandbox activities a 10-second default heartbeat timeout

2 participants