Repository navigation
Description
Summary
The plugin README says: "Use agent.invoke_async(message) instead of agent(message). The
synchronous form spawns a worker thread, which the workflow sandbox blocks." It does not block it
for agents that do their own I/O. Agent.__call__, A2AAgent.__call__, Graph.__call__,
Swarm.__call__ and Agent.structured_output run the async call with
strands._async.run_async, which starts a ThreadPoolExecutor thread and runs asyncio.run
there. The plugin passes strands through the sandbox, and the sandbox's importer and its
in_sandbox flag work per thread, so that thread runs with the host's modules and no restrictions,
off the Workflow event loop. A remote A2AAgent call, or a plain Strands Agent's model call,
completes there with no record in History, and a replay makes it again. Only TemporalAgent's sync
form fails, because its model needs the Workflow loop.
Versions
temporalio-strands-agents 0.1.0 and main at 6a7330a; also
temporalio.contrib.strands in temporalio 1.33.0. strands-agents 1.56.0 (1.51.0 at 1.33.0),
a2a-sdk 0.3.26 for the A2A route, Python 3.13.16, Temporal CLI 1.9.1.
Reproduction
One file, with a plain Strands Agent whose model logs each call with its thread name. A sandboxed
Workflow calls it with the sync form; the script then replays the History. It exits 0 when the
defect shows. Run with the temporal CLI on PATH.
sync_call_repro.py
"""A Strands sync agent call in a sandboxed plugin Workflow runs unrecorded and again on replay.
The Workflow calls a plain Strands Agent with the sync form, `Agent(model=...)("hi")`. Its model
counts calls and records the thread it runs on. On a Worker with StrandsPlugin, the call runs on a
new thread outside the Workflow sandbox, the Workflow completes with the model's answer, History has
no Activity for it, and a Replayer calls the model again.
Run: python sync_call_repro.py (starts its own dev server with the `temporal` CLI on PATH)
Exit 0 when the defect shows; 1 when the Workflow Task fails because the sync call is refused.
"""
import asyncio
import logging
import shutil
import sys
import uuid
from temporalio import workflow
from temporalio.api.enums.v1 import EventType
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Replayer, Worker
with workflow.unsafe.imports_passed_through():
from strands import Agent
from strands.models import Model
from temporalio.strands_agents import StrandsPlugin
# The model logs each call; the logging module is shared with the sandbox, and each record keeps
# the name of the thread that made the call.
CALLS: list[str] = []
class Collect(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
CALLS.append(record.threadName or "")
def calls() -> list[str]:
return list(CALLS)
class CountingModel(Model):
def update_config(self, **_):
return None
def get_config(self):
return {}
def structured_output(self, *_a, **_k):
raise NotImplementedError
async def stream(self, *_a, **_k):
logging.getLogger("repro.calls").warning("model call")
yield {"messageStart": {"role": "assistant"}}
yield {"contentBlockDelta": {"delta": {"text": "answer"}}}
yield {"contentBlockStop": {}}
yield {"messageStop": {"stopReason": "end_turn"}}
@workflow.defn
class SyncCall:
@workflow.run
async def run(self) -> str:
return str(Agent(model=CountingModel(), callback_handler=None)("hi")).strip()
async def main() -> int:
logging.getLogger("repro.calls").addHandler(Collect())
logging.getLogger("repro.calls").propagate = False
plugin = StrandsPlugin(models={})
async with await WorkflowEnvironment.start_local(dev_server_existing_path=shutil.which("temporal")) as env:
async with Worker(env.client, task_queue="sync", workflows=[SyncCall], plugins=[plugin]):
handle = await env.client.start_workflow(SyncCall.run, id=f"sync-{uuid.uuid4().hex[:6]}", task_queue="sync")
try:
result = await asyncio.wait_for(handle.result(), timeout=15)
except asyncio.TimeoutError:
result = None
history = await handle.fetch_history()
if result is None:
await handle.terminate("check over")
types = [e.event_type for e in history.events]
activities = types.count(EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED)
failures = [e.workflow_task_failed_event_attributes.failure.message for e in history.events
if e.event_type == EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED]
print(f"result: {result!r}; activities in History: {activities}; model calls (threads): {calls()}")
if result is None:
print(f"workflow task failed: {failures[0][:160] if failures else None}")
return 1
before = len(calls())
await Replayer(workflows=[SyncCall], plugins=[plugin]).replay_workflow(history)
print(f"after replay: model calls (threads): {calls()}")
first = calls()[0] if calls() else ""
defect = activities == 0 and before == 1 and len(calls()) == 2 and not first.startswith("temporal_workflow")
print("defect: the sync call ran off the Workflow thread, unrecorded, and again on replay" if defect else "no defect")
return 0 if defect else 1
if __name__ == "__main__":
sys.exit(asyncio.run(main()))Output on main:
result: 'answer'; activities in History: 0; model calls (threads): ['ThreadPoolExecutor-0_0']
after replay: model calls (threads): ['ThreadPoolExecutor-0_0', 'ThreadPoolExecutor-2_0']
defect: the sync call ran off the Workflow thread, unrecorded, and again on replay
The same happens with Strands' own first A2A example, A2AAgent(endpoint=...)("..."), against a
local A2A server: the server gets the card request and message/send, the Workflow completes with
the reply, History holds only the five Workflow Task and execution events, and a replay in a new
process sends the message again and starts a new remote task.
Expected
In Workflow code the sync form fails, as the README says, instead of making I/O that History does
not record.
Proposed fix
Wrap Strands' sync entry points once per process when StrandsPlugin is built (Agent.__call__,
Agent.structured_output, MultiAgentBase.__call__, Graph.__call__, Swarm.__call__, and
A2AAgent.__call__ when the a2a extra is installed). In Workflow code the wrapper raises
RuntimeError that points to await agent.invoke_async(...) and Activities; outside Workflows it
calls the original. run_async itself is left alone, because agent construction uses it to load
tools. Guard the refusal with workflow.patched(...), called only when a sync call happens in
Workflow code, so runs that already made such a call keep making it on replay.
This is a breaking change: Workflow code that called an A2AAgent, or a plain Agent, Graph or
Swarm with its own model, with the sync form now fails its Workflow Task. Move those calls into
Activities, for example with activity_as_tool.
A pull request with this change, a test in tests/test_model.py (it fails on main and passes
with the change) and an updated README note follows.
Activity