Repository navigation
strands_agents: give model and sandbox activities a 10-second default heartbeat timeout - #504
Conversation
… 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.
| import asyncio | ||
| import inspect |
There was a problem hiding this comment.
these seem like dangerous and unrelated imports, why are we now importing asyncio to set a timeout??
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
why does this need to be async now? could this be a breaking change?
There was a problem hiding this comment.
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.
| # Concurrent calls share one build. The shield keeps a cancelled call | ||
| # from cancelling the build the others wait for. |
There was a problem hiding this comment.
What does this mean? Can you clarify/simplify?
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
Why are we building factories to set a timeout?
There was a problem hiding this comment.
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.
| 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. |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
I like this better now, thanks
…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.
What was changed
TemporalAgent,TemporalModelandTemporalSandboxnow defaultheartbeat_timeoutto 10 seconds instead ofNone, so the model and sandbox activities heartbeat by default.auto_heartbeater). A timeout you set wins, andheartbeat_timeout=Noneturns heartbeats off, as before.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_configis 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.SageMakerAIModelandLlamaAPIModelcall their synchronous clients on the loop, so they needheartbeat_timeout=None(or a longer timeout).activity_as_toolandactivity_as_hookrun 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
aiohttpsession, 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_timeoutnow heartbeats, which in Temporal Cloud is at most one Action every 8 seconds of a running call.TemporalMCPClientisn't in this PR. Since #435, Strands requirestemporalio-mcp0.4, whose Activities heartbeat (#494). But Strands'TemporalMCPClientstill passesheartbeat_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
Closes [Feature Request] strands_agents: give model and sandbox activities a 10-second default heartbeat timeout #498
How was this tested:
test_modelnow checks the heartbeat timeouts in History: none forstrands_get_model_config, 10 seconds forinvoke_model. Without the change it fails withassert [None, None] == [None, datetime.timedelta(seconds=10)].test_sandbox_operations_are_durable_and_factory_runs_for_each_activitynow checks that all seven sandbox Activities get 10 seconds. Without the change, they get none.test_heartbeat_timer_counts_from_the_startblocks 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 withassert ([]).test_slow_model_factory_logs_a_warningbuilds 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 withassert ("Building model 'slow' took" in '') == True.make test(262 passed, 1 skipped),make lintand 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).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.