Skip to content

Breaking: refuse Strands' sync calls in workflow code - #192

Merged
campoy merged 8 commits into
mainfrom
fix/strands-python-sync-agent-call-escapes-sandbox
Oct 31, 2026
Merged

campoy merged 8 commits into
mainfrom
fix/strands-python-sync-agent-call-escapes-sandbox

Conversation

@campoy

@campoy campoy commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

StrandsPlugin now refuses Strands' sync calls in Workflow code. Strands runs each of them on a new thread, outside the Workflow sandbox and off the Workflow event loop, where nothing is recorded in History.

  • New private module _sync_calls.py. The plugin's workflow-runner hook calls refuse_sync_calls_in_workflows() once per process, for Workers and Replayers (sandboxed or not), so client-only processes are not patched. It guards the ThreadPoolExecutor that strands._async.run_async looks up on every call (most Strands sync entry points call run_async), so every reference to run_async is covered, including ones bound before the install. If Strands no longer has run_async, or run_async no longer uses a ThreadPoolExecutor, Worker and Replayer creation fail with an error that says so. strands.tools.mcp.MCPClient uses its own background thread and is not covered.
  • In Workflow code the guard raises RestrictedWorkflowAccessError, the sandbox's own error (a NondeterminismError), so workflow_failure_exception_types=[NondeterminismError] fails the run instead of retrying the task. Its message points to the call's async form, such as await agent.invoke_async(...) with a TemporalAgent or TemporalAgent nodes, or an Activity, and says that Strands features that make the call themselves don't work in Workflow code. Workflow code includes module-level code that the sandboxed runner runs when it imports a Workflow module, before the Workflow runtime is attached; the guard detects it with workflow.unsafe.in_sandbox(). Code inside workflow.unsafe.sandbox_unrestricted() is not refused. Outside Workflows it calls the original.
  • Strands also uses run_async while an Agent, Graph or Swarm is built, to load tool providers (TemporalMCPClient) and run init hooks. The guard allows it while one of those constructors runs on the current thread (a thread-local depth, so tasks created meanwhile don't inherit it).
  • README: the note on the sync form now says what is refused and why, what the error does to a run, and how to upgrade.

Breaking change: in Workflow code these used to complete, with their I/O unrecorded, and now fail the Workflow Task:

  • calling an A2AAgent, or a plain Strands Agent, Graph or Swarm with its own model, with the sync form, and agent.structured_output();
  • direct tool calls such as agent.tool.name(...);
  • by source, not run: Strands features that make such calls themselves: SummarizingConversationManager (already failed before, with _NotInWorkflowEventLoopError), the saves of a SnapshotSessionManager, so a Workflow that uses one stops working, and leaving a with agent: block with a memory manager (Strands 1.58.1+).

Inside a tool body, such as an async @tool that calls another agent with the sync form, Strands catches the error and gives the model an error tool result; the run does not fail. Before this change the nested call ran unrecorded and returned real text.

Move those calls into Activities, for example with activity_as_tool. Under the sandboxed runner, a sync call in a Workflow module's top-level code makes Worker creation fail (Failed validating workflow), and every replay of that Workflow fail, until it is removed. The title starts with Breaking: because release notes come from commit subjects.

The refusal has no version gate. A run that made such a call before this version makes it again on replay and now gets the error. If the Workflow does not catch it, its Workflow Task fails on every attempt and the run stays open, unless the Worker or Workflow lists NondeterminismError in its failure exception types, which fails the run instead. If it catches it, the run takes its error branch: replay fails with [TMPRL1100] when that branch schedules other commands, and otherwise carries on with state that no longer matches its History. Runs that never made a sync call in Workflow code are not affected.

Upgrade: let runs that made a sync call in Workflow code finish on the earlier version before you upgrade, or keep them there with Worker Versioning.

The branch is the fix commit on 5e91c26, a merge of main at 6a7330a, a commit that removes the version gate, a commit that extends the refusal to sandbox module imports, and 627dbee, which moves the guard from six Strands methods to run_async after review, a775aa9, which addresses the second review, 3ea52ac, which addresses the third, and 045b4fc, which addresses the fourth. Review the combined diff against main.

Why?

See #191. Strands' sync entry points run the call with strands._async.run_async, which runs asyncio.run on a new ThreadPoolExecutor thread. The plugin passes strands through the sandbox, and the sandbox's restrictions work per thread, so that thread runs unrestricted and off the Workflow event loop. The README said the sandbox blocks the sync form; it does so only for TemporalAgent, whose model needs the Workflow loop.

Checklist

  1. Closes [Bug] strands_agents: Strands' sync agent calls run unrecorded in Workflow code and again on replay #191

  2. How was this tested:

    • test_sync_call_is_refused in tests/test_model.py, for an agent call, a direct tool call, swarm(...), and a run_async bound by a module imported before the guard was installed (tests/prebound_run_async.py, imported by its dotted name so it passes through the sandbox): the Workflow does not catch the error, and with workflow_failure_exception_types=[NondeterminismError] it fails with the guard's RestrictedWorkflowAccessError; the agent case's History replays. With the guard turned off, they fail with DID NOT RAISE WorkflowFailureError; with only the executor guard removed, the prebound case fails too.
    • test_sync_call_workflow_builds_without_calls: the same Workflow builds an Agent with a tool and a Swarm and completes, and a sync call inside workflow.unsafe.sandbox_unrestricted() returns its answer. Without the constructor allowance building the Swarm is refused; without the sandbox_unrestricted() clause the sync call is refused, and the test fails quickly because its Worker lists NondeterminismError.
    • test_sync_call_in_sandbox_import_is_refused: a Workflow module (tests/sync_import_workflow.py) makes a sync Agent call at module level. The test first undoes any earlier install in its process, so it doesn't depend on test order. Worker(...) installs the guard and then raises Failed validating workflow, caused by the guard's error; re-running the module's code outside Workflow code still makes the call. It fails with the guard turned off and with the install removed from the plugin's workflow runner hook.
    • On 3ea52ac, in Docker with Python 3.13 and uv 0.12.24: every make lint step passes and make test passes (142 tests). On 045b4fc, locally: every make lint step passes; with the executor guard removed, the four refusal cases (including the prebound one) and the sandbox-import test fail; with the sandbox_unrestricted() clause removed, the build test fails in about 9 s; and a run_async that doesn't use ThreadPoolExecutor makes the install fail with the 'not supported' error. The local full suite and the install-in-run_context mutant were stopped before they finished; CI runs the full suite. Two probes, run on a775aa9 and not committed: a TemporalAgent whose async tool calls a plain agent with the sync form gets an error tool result with the guard's message, and a None entry under strands. in sys.modules does not break the install.
    • On the earlier method-list version of this change (not rerun on 627dbee): [Bug] strands_agents: Strands' sync agent calls run unrecorded in Workflow code and again on replay #191's reproduction exits 0 (defect) on main at 5e91c26, the same plugin source as 0.1.0, and at 6a7330a, and exits 1 with the change. A2A route, on 5e91c26 with a2a-sdk 0.3.26: on main a local A2A server gets the Workflow's message, History has no record of it, and a replay sends it again; with the change the server gets no request and the Workflow Task fails with the refusal. A2AAgent.__call__ goes through the same run_async.
    • Replay checks on 5e91c26 against a dev server, on Workers with no Workflow cache, run on the earlier, gated version of this change and on a control build without the gate. Each run was recorded as a plain Workflow, with the sync call in the Workflow's __init__, and as a Workflow class with __slots__:
      • on the control build, a main history whose sync call was not caught fails with the new RuntimeError, and main histories that catch it replay but take the refusal branch; a waiting main run finished on it completes with the refusal;
      • an extra Activity fails replay with [TMPRL1100] (control).
  3. Any docs updates needed?
    The plugin README's note on the sync form.

Not covered:

  • A sync call made while an Agent, Graph or Swarm is built, for example inside a tool provider's load_tools(), is not refused.
  • CI does not test A2AAgent: the a2a extra would add 15 packages to uv.lock (a2a-sdk[sql] brings SQLAlchemy and three database drivers), and it goes through the same guard as the tested calls.
  • Strands' summarizing conversation manager still fails in Workflows when it reduces context (as before); by source, it now fails with this guard's error, and the proactive compression path swallows it, so compression never happens. That is tracked separately.
  • Synchronous @tool functions don't run in Workflow code with this plugin (Strands runs them with asyncio.to_thread, which the Workflow event loop doesn't support). Pre-existing, not caused by this change; tracked separately.
  • Histories recorded with this change were not replayed on main.
  • temporalio 1.34.x still bundles the old code as temporalio.contrib.strands. No backport here.

Agent.__call__, A2AAgent.__call__ and the other sync entry points run the
call with strands._async.run_async, which starts a new thread. That thread
runs outside the workflow sandbox and off the workflow event loop, so an
A2AAgent call, or a plain Agent's own model call, made there is not
recorded in History and runs again on every replay. The README said the
sandbox blocks the sync form; it blocks it only for TemporalAgent, whose
model needs the workflow loop.

StrandsPlugin now wraps the sync entry points (Agent.__call__,
Agent.structured_output, MultiAgentBase.__call__, Graph.__call__,
Swarm.__call__ and, with the a2a extra, A2AAgent.__call__) so that in
workflow code they raise RuntimeError with a message that points to
invoke_async and activities. Outside workflows they are unchanged, and
agent construction, which also uses run_async, is not affected.

Breaking change: workflow code that called an A2AAgent, or a plain Strands
Agent, Graph or Swarm with its own model, with the sync form now fails its
workflow task instead of making the call unrecorded. Move those calls into
activities, for example with activity_as_tool. Runs that made such a call
before this change keep making it when they replay (patch
"strands-refuse-sync-agent-calls"); code without this patch cannot replay
runs that recorded the patch.
Fixes add no version gates for now, so remove the
`strands-refuse-sync-agent-calls` patch. Strands' sync agent calls now
raise in Workflow code in every run.

Breaking change: a run that made such a call before this version makes
it again on replay and now gets the error. If the Workflow does not
catch it, its Workflow Task fails on every attempt; if it catches it,
the run takes its error branch. Let those runs finish before you
upgrade, or use Worker Versioning.
@campoy
campoy force-pushed the fix/strands-python-sync-agent-call-escapes-sandbox branch from 7d407f5 to 36dfe92 Compare October 29, 2026 00:36
@campoy
campoy marked this pull request as ready for review October 29, 2026 01:17
@campoy
campoy requested a review from a team as a code owner October 29, 2026 01:17

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

Review of the sync-call guard. make lint and make test pass on the head (138 tests). Every finding below was reproduced against strands 1.56.0 and temporalio 1.34.0, and the replay one on the pinned dev server.

Gate. The first commit had a workflow.patched gate (a9c28c7 kept the in-flight run on its original branch in my control run). Without it, a run that caught the sync call's result silently takes its except branch on replay, with no task failure and no TMPRL1100, so the README sentence "fails on it when it replays" is false for the exact shape the PR's own SyncCallWorkflow models. See the comment on line 46.

Not anchored to a diff line: the SummarizingConversationManager case. Strands calls Agent.__call__ synchronously on the workflow loop from reduce_context (summarizing_conversation_manager.py:262), so with summarization_agent=TemporalAgent(...) a context overflow now raises this guard's RuntimeError inside the user's own await agent.invoke_async(...), with an inapplicable remedy in the message, and with summarization_agent=None it fails differently with _NotInWorkflowEventLoopError. Not a regression (both failed before), but the README never says summarization-based context reduction is unsupported in workflows.

_GUARDED = "__temporal_strands_sync_guard__"


def _targets() -> list[tuple[type, str]]:

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.

Altitude: a fail-open list of six methods instead of a guard on the one escape hatch. Every sync entry point funnels through strands._async.run_async, and each caller binds the name at import (from .._async import run_async in agent.py, a2a_agent.py, base.py, graph.py, swarm.py, registry.py, _caller.py, _discovery.py, summarizing_conversation_manager.py, snapshot_session_manager.py), so rebinding it per loaded strands.* module plus strands._async would cover all of them. strands-agents>=1.51.0 is unbounded and 1.58.1 already adds Agent.shutdown() calling run_async, reached from with agent:; it is not in this list, so with TemporalAgent(..., memory_manager=m) as agent: would flush memory on an off-loop thread, unrecorded and re-run on replay, with green CI. The same silence applies to SnapshotSessionManager.sync_agent, plugin async_init, and any MultiAgentBase subclass overriding __call__. A plugin-owned ContextVar allowance around TemporalAgent.__init__ would cover the one construction bridge the plugin relies on (ToolProvider.load_tools for TemporalMCPClient); copy_context() in run_async carries the marker into nested bridges (verified). At minimum keep these method guards for their error text and add the run_async guard as the fail-closed backstop.

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.

Agreed. 627dbee moves the guard to strands._async.run_async: it replaces it once per process, rebinds it in the Strands modules already imported (later imports get the guarded one), and allows it while Agent, Graph or Swarm.__init__ runs, which covers TemporalMCPClient tool loading and the multi-agent init hooks. I dropped the six method wrappers instead of keeping both: one guard fails closed, and the traceback shows which call it was. Direct tool calls, with agent: shutdown and snapshot session manager saves are now refused too; the PR body lists them under the breaking change.

(Swarm, "__call__"),
]
try:
from strands.agent.a2a_agent import A2AAgent

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.

This imports the whole a2a client/server stack (a2a.client, a2a.server.*, fastapi, starlette, uvicorn, protobuf gencode) on every StrandsPlugin() construction and tolerates only ImportError. A present-but-broken optional install aborts construction for every process, including client-only ones, although Strands itself defers this import behind strands/agent/__init__.py.__getattr__. Reproduced with strands 1.56.0, a2a-sdk 0.3.26 and protobuf 5.28.3 (allowed by temporalio's protobuf>=3.20,<8, below the a2a gencode's 5.29.3 floor): StrandsPlugin(...) raises google.protobuf.runtime_version.VersionError while import strands and every non-A2A use keep working. A failed import is also not cached, so it is retried on each construction. Suggest except Exception and computing the target list once.

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.

Gone in 627dbee: the module no longer imports A2AAgent, and the guard installs once per process (functools.cache).



def _guard(name: str, method: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(method)

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.

The Python-level guarded frame now sits between the caller and Strands' warnings.warn(..., stacklevel=2) in Agent.structured_output and the **kwargs deprecation in MultiAgentBase/Graph/Swarm.__call__. Once any StrandsPlugin() exists, those warnings are attributed to this file process-wide (activities, scripts, tests). For a __main__ script calling agent.structured_output(...), the DeprecationWarning is shown before StrandsPlugin() and silenced after (the warning module becomes temporalio.strands_agents._sync_calls, matching ignore::DeprecationWarning rather than default::DeprecationWarning:__main__), and filterwarnings = error::DeprecationWarning:myapp.* rules stop matching. A descriptor whose __get__ raises in-workflow and otherwise returns method.__get__(obj, objtype) preserves attribution and is still reached on the agent(...) call path (prototyped).

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.

Gone in 627dbee: no public method is wrapped any more. Only Agent, Graph and Swarm.__init__ get a wrapper, and neither Strands 1.56.0 nor 1.61.1 warns from those.

def guarded(self: Any, *args: Any, **kwargs: Any) -> Any:
# The sandbox imports Workflow modules before the Workflow runtime is
# attached, so module-level code there is Workflow code too.
if workflow.in_workflow() or workflow.unsafe.in_sandbox():

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.

Two problems with this predicate.

1. Replay divergence without the gate. An in-flight run recorded on the old build as try: answer = str(agent('classify')) except RuntimeError: answer = 'unknown' then await execute_activity(store, answer) replays on the new worker into the except branch. Core matches the store command by type and id and never compares inputs, so the run completes with activity_returned=stored:positive but answer=unknown: zero WorkflowTaskFailed, no TMPRL1100, and Replayer(..., plugins=[plugin]) on the old history also passes. Restoring the gate keeps such runs on their original branch; otherwise the README needs to say that a workflow that catches the error silently takes its error branch with state that no longer matches History.

2. Not unconditional. in_workflow() reads the running-loop attribute and in_sandbox() a thread-local, and both are false on the fresh thread run_async spawns. So a sync agent call that is one thread hop from workflow code runs unrefused and unrecorded: agent.tool.probe_tool(x='direct') (tools/_caller.py:139) ran the tool body with both predicates false, a nested plain Agent(model=MockModel([...]))('hi') returned normally, agent.messages grew with a random toolUseId, History had 0 activities, and Replayer re-executed the model call. The same applies to ToolProvider.load_tools() during Agent.__init__ and the Graph/Swarm init hooks. The PR body lists direct tool calls under "Not covered" but the README promises an unconditional RuntimeError. Either narrow the README or set a plugin ContextVar on the workflow task (run_async copies contextvars into its thread) and check it 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.

(1) We've decided not to add version gates to these fixes for now, since the 1.0 releases may break replay of older runs, so this stays ungated. The README now says what happens instead: a run that caught the error takes its error branch, which fails with a nondeterminism error if that branch schedules other commands, and otherwise carries on with state that no longer matches its History.

(2) With the guard on run_async (627dbee), a direct tool call is refused at the first hop; test_sync_call_is_refused now covers it. What's left is a sync call made inside an allowed constructor, such as a tool provider's load_tools(); the README says those aren't checked.

# attached, so module-level code there is Workflow code too.
if workflow.in_workflow() or workflow.unsafe.in_sandbox():
raise RuntimeError(
f"{type(self).__name__}.{name}() runs the call on a new thread, "

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.

The one message is inaccurate for some targets. For a TemporalAgent, "its model calls and other I/O would not be recorded" is false: off the workflow loop that call cannot run at all and raises _NotInWorkflowEventLoopError from TemporalModel._read_config before any I/O. For Swarm/Graph, await agent.invoke_async(...) names the wrong object (Swarm([TemporalAgent(...)])('hi') has no agent to call; the working form is await swarm.invoke_async('hi') with TemporalAgent nodes). Suggest wording like "cannot run on the Workflow event loop" and naming the async form per target, including structured_output_model= for structured output (note structured_output_async is not supported by TemporalModel). Also, RuntimeError is only a workflow-task failure here, so the run stays open until the worker is rolled back; a SyncCallInWorkflowError(RuntimeError) subclass would let users catch it precisely or list it in workflow_failure_exception_types without the overbroad [RuntimeError].

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.

Reworded in 627dbee: it now says the thread can't use the Workflow event loop, and names await agent.invoke_async(...) with structured_output_model= for structured output, and await graph.invoke_async(...). With one guard the message can't name the exact call, but the traceback does. I kept RuntimeError for now; happy to add a subclass in a follow-up if we want it as API.

"""Make Strands' sync agent calls raise in Workflow code; idempotent."""
for cls, name in _targets():
method = cls.__dict__.get(name)
if method is None or getattr(method, _GUARDED, False):

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.

if method is None ...: continue silently drops a target, and five of the six advertised targets have no test: Agent.structured_output and MultiAgentBase/Graph/Swarm.__call__ are never called synchronously in the tests, and A2AAgent (the headline case in the PR title) is unreachable in CI because a2a-sdk is not in uv.lock, the dev group or an extra. I reproduced the post-continue state: with Agent.__call__ restored to __wrapped__, a sandboxed workflow's Agent(...)('Hello') returned 'sync answer' with zero activity events. A Strands release that moves these methods to a base class, or renames strands.agent.a2a_agent (swallowed by the except ImportError above), removes the guard while nightly sync-latest stays green. Suggest adding strands-agents[a2a] to the dev group (resolvable under the two-week cooldown, a2a-sdk 0.3.26), one refusal test per target, and failing loudly (or asserting in a unit test) when an expected target is missing.

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.

Gone with the single guard in 627dbee. The tests now cover an agent call, a direct tool call and swarm(...), plus building them without calls. I left out the a2a extra: A2AAgent.__call__ goes through the same run_async, and the extra adds 15 packages to uv.lock (a2a-sdk[sql] brings SQLAlchemy and three database drivers). The A2A route was checked by hand, as the PR body says.

Comment thread python/strands_agents/README.md Outdated
```

Note: Use `agent.invoke_async(message)` instead of `agent(message)`. The synchronous form spawns a worker thread, which the workflow sandbox blocks.
Note: Use `agent.invoke_async(message)` instead of `agent(message)`. The synchronous form runs the call on a new thread, outside the workflow sandbox, where its model calls and other I/O would not be recorded. So in workflow code, including module-level code in workflow modules that the sandbox imports, the sync calls of Strands' `Agent`, `A2AAgent`, `Graph` and `Swarm`, and `Agent.structured_output()`, raise `RuntimeError`. Call agents that do their own I/O, such as an `A2AAgent`, from an activity, for example with `activity_as_tool`. A run that made such a call before you deploy this version fails on it when it replays: let those runs finish first, or use Worker Versioning.

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.

Two accuracy problems here. (1) "A run that made such a call ... fails on it when it replays": the bare RuntimeError is a Workflow Task failure, not a workflow failure, so such a run stays RUNNING with a retried task (rising attempt counter) until the worker is rolled back or Worker Versioning is used; and for the caught shape it does not fail at all (see the comment on _sync_calls.py:46). (2) Because in_sandbox() is also true while the sandbox imports workflow modules, an uncaught module-level sync call in a workflow module (or a non-passthrough helper it imports) makes Worker(...) construction and Replayer.replay_workflow(s) fail with RuntimeError('Failed validating workflow <name>'), which takes every workflow registered on that worker down; the "let those runs finish first" remedy cannot apply to that case. That matches the SDK's behavior for other module-level violations, so it is a documentation gap: say the worker refuses to start and the call must be removed.

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 627dbee: the README now says the error fails the Workflow Task, so the run stays open and the task is retried, and that a module-level call stops the Worker from starting until it's removed.

A sandbox factory may return an async context manager when its adapter
needs cleanup after the Activity finishes.
"""
refuse_sync_calls_in_workflows()

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.

The process-wide patch is installed in StrandsPlugin.__init__, so every process that constructs the plugin is patched, including the README's client-only Client.connect(..., plugins=[StrandsPlugin(...)]), and the coupling to the with_passthrough_modules('strands', ...) setting (the reason the SDK's thread restrictions cannot see run_async's executor) is invisible from here. Not a correctness bug since the wrapper is inert outside workflows. Verified alternative: call refuse_sync_calls_in_workflows() as the first line of _workflow_runner, before the isinstance(runner, SandboxedWorkflowRunner) branch since the hazard also exists under the unsandboxed runner. SimplePlugin invokes it from both configure_worker (before _WorkflowWorker creation and its validation import) and configure_replayer, a workflow_runner= override still passes through it, and client-only construction then leaves Agent.__call__ unpatched. The "Imported after the plugin installs its guard" comment in the sandbox-import test would need updating.

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.

Done in 627dbee: the guard installs from _workflow_runner, before the sandbox check, so client-only processes aren't patched. The sandbox-import test now installs it explicitly before its ordinary import.

async def run(self) -> str:
# A plain Strands agent with its own model, called with the sync form.
agent = Agent(model=MockModel(["sync answer"]), callback_handler=None)
try:

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.

Both new tests exercise only the caught path (try/except RuntimeError returning a sentinel string), so the behavior this PR ships for ordinary code is never asserted: an uncaught call fails the Workflow Task, and an uncaught module-level call makes Worker(...) raise Failed validating workflow. A later change that converts or swallows the guard's RuntimeError (an interceptor, StrandsFailureConverter, validation chaining) would pass both tests. Feasible variants, verified on the dev server: workflow_failure_exception_types=[RuntimeError] on Worker and Replayer (plugins append them; tests/test_sandbox.py has a precedent) gives WorkflowFailureError with cause.type == 'RuntimeError' and the guard message, and pytest.raises(RuntimeError, match='Failed validating workflow') around Worker(...) covers the sandbox-import case without a dev-server round trip.

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.

Done in 627dbee: the tests leave the error uncaught and set workflow_failure_exception_types=[RuntimeError] on the Worker and Replayer, and the module-level case expects Worker(...) to raise Failed validating workflow, caused by the guard's error. With the guard off, all four fail.

)

history = await handle.fetch_history()
assert get_activities(history) == []

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.

assert get_activities(history) == [] can never fail here: SyncImportWorkflow uses a plain Agent over the in-process MockModel and returns a module-level string, so no activity is scheduled whether or not the guard fires. If the in_sandbox() branch regressed, the startswith('refused: ...') assertion above fails first. As written it reads as proof that no unrecorded work happened. Drop it and the extra fetch_history, or make the two tests consistent about what "refused" must prove.

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.

Dropped in 627dbee, along with the extra fetch_history.

Review follow-up. Instead of wrapping six Strands methods, replace
strands._async.run_async, which every Strands sync entry point uses,
and allow it while an Agent, Graph or Swarm is built (tool providers
and init hooks). This also refuses direct tool calls, `with agent:`
shutdown and snapshot session manager saves in workflow code.

- Install the guard from the workflow runner hook, so client-only
  processes are not patched.
- Reword the error: name the async forms and say the thread cannot
  use the workflow event loop.
- README: the error fails the workflow task and the run stays open;
  a module-level call stops the worker from starting; a run that
  caught the error takes its error branch on replay.
- Tests: leave the error uncaught (workflow_failure_exception_types)
  for an agent call, a direct tool call and swarm(...); check that
  building still works; expect Worker validation to fail for a
  module-level call.
@campoy campoy changed the title Breaking: refuse Strands' sync agent calls in workflow code Breaking: refuse Strands' sync calls in workflow code Oct 29, 2026
@campoy

campoy commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

@DABH Thanks for the review. All threads are answered above; the main change is in 627dbee. Here's the reasoning behind the bigger decisions.

Guard on run_async instead of six methods. We compared three options: keep the method list and fix its gaps, guard run_async only, or both. We picked run_async only.

  • Pros: it fails closed, so a sync path Strands adds later (like Agent.shutdown() in 1.58.1) is refused with no change here. No public method is wrapped, which removes the warning, wrapt, a2a import and silent-drop issues. It's about the same size as the fixed list (75 lines vs 68), and one guard covers every kind of call.
  • Cons: it refuses more in Workflow code: direct tool calls, with agent: shutdown and snapshot session manager saves, so a Workflow that uses that session manager stops working. Each of these does unrecorded I/O today. All refusals share one message; the traceback shows the call. It depends on Strands' private strands._async.run_async: a rename fails loudly when the plugin is imported, but a second bridge function would be a gap. Constructors stay allowed, so sync calls made while an agent is built aren't checked.
  • Keeping both would have kept per-call messages, at the cost of the list's upkeep too.

No a2a extra in CI. The extra brings a2a-sdk[sql]: 15 more packages in uv.lock (+517 lines), including SQLAlchemy and three database drivers, installed by every plugin CI job. A2AAgent.__call__ goes through the same run_async as the tested calls, so the test would add little. Con: CI doesn't exercise the headline case of #191; it was checked by hand against a local A2A server, on the earlier version.

No version gate. We've decided not to add version gates to these fixes for now, since the 1.0 releases may break replay of older runs. Pro: simpler code and no marker in new histories. Con: runs that made a sync call before the upgrade don't replay as recorded; the README and PR body say what happens and how to upgrade (let them finish, or use Worker Versioning).

RuntimeError, not a subclass. A subclass would let users catch it precisely or list it in workflow_failure_exception_types, but it's new public API. Happy to add it in a follow-up.

Install from _workflow_runner. Workers and Replayers get the guard, sandboxed or not; client-only processes aren't patched.

Summarizing conversation manager: agreed it isn't a regression. It's tracked separately, so I left it out of this PR; by source it now fails with this guard's error. The PR body lists it under "Not covered".

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

Second pass, on the rewritten head. Guarding strands._async.run_async itself closes the thread-hop and fail-open gaps from the previous round, the a2a import and method wrappers are gone, the patch now installs from _workflow_runner, the tests cover the uncaught path and worker validation, and the README now describes the task-failure semantics. Lint and the new tests pass; the guard behaves identically on strands 1.51.0, 1.56.0 and 1.62.0. Findings below were verified by running probes against this branch unless marked otherwise.

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Two things to decide on purpose: the construction allowance is a blanket bypass with a ContextVar that leaks into tasks created during construction (line 55), and a refusal raised inside a tool body is swallowed by Strands' tool executor, so the README's 'fails the workflow task' does not hold for the agents-as-tools pattern (README line 80).

Pre-existing, found while checking what worked before (not caused by this PR): synchronous @tool functions never execute in workflow code with this plugin. Strands runs every sync tool body through asyncio.to_thread, which needs loop.run_in_executor, and the SDK's workflow loop does not implement it, so the tool raises NotImplementedError and Strands turns it into an error ToolResult (reproduced end to end: the workflow completes with {'status': 'error', 'content': [{'text': 'Error: NotImplementedError - '}]}). tests/test_tool.py's 'in-workflow' calculator/letter_counter cases pass only because they assert the final text and activity names, never the tool results. Worth its own issue.

def _allow_during(init: Callable[..., None]) -> Callable[..., None]:
@functools.wraps(init)
def wrapper(self: Any, *args: Any, **kwargs: Any) -> None:
token = _constructing.set(True)

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.

P2: the construction allowance is a blanket bypass, and the ContextVar leaks. Anything Strands runs through run_async while Agent/Graph/Swarm.__init__ is on the stack is unguarded and unrecorded: an AgentInitializedEvent hook calling event.agent('warm up') runs a full model call on a bridge thread that re-runs on every replay (reproduced); SnapshotSessionManager.initialize reads session storage at construction; an async plugin init_agent doing network I/O; a ToolProvider.load_tools that builds and calls a nested agent. The README's 'calls made while they are built are not checked' acknowledges this, but its justification ('Strands uses the same thread to load their tools') is wrong: run_async always starts a new thread, which is exactly why the allowance exists. Separately, because _constructing is a ContextVar, every asyncio task or loop.call_soon callback created on the workflow loop during construction (a hook doing asyncio.ensure_future(...)) inherits True for its whole lifetime, so sync calls made later from that task are never refused (reproduced: 'task saw _constructing = True; later sync call: ALLOWED'). A thread-local re-entrancy counter would not leak this way, since construction is synchronous on the calling thread.

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 a775aa9: the allowance is now a thread-local depth counter, so tasks and callbacks created during construction don't inherit it. The README no longer gives the wrong reason; it just says calls made while agents, graphs and swarms are built aren't checked. I kept the allowance as wide as the constructor: Graph and Swarm run their init hooks through run_async on every build, so anything narrower breaks building them.

# Strands modules bind run_async when they are imported; rebind the ones
# already loaded. Modules imported later get the guarded one.
for name, module in list(sys.modules.items()):
if name.startswith("strands.") and vars(module).get("run_async") is _run_async:

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.

P2: vars(module) crashes Worker/Replayer construction on non-module sys.modules entries, and the failure is not cached. sys.modules['strands.<x>'] = None (the standard way to force an ImportError for an optional dependency, also monkeypatch.setitem) raises TypeError: vars() argument must have __dict__ attribute; an importlib.util.LazyLoader module under a strands. name is force-imported by the attribute access and raises ModuleNotFoundError for its missing dependency (both reproduced). The exception escapes functools.cache, so every subsequent Worker(...)/Replayer(...) with the plugin fails too. Test type(module) is types.ModuleType before touching the dict.

The identity test is also fragile in the other direction: a module whose run_async is temporarily something else when the first Worker is built (a pytest monkeypatch.setattr, a tracing wrapper, another plugin) is skipped; when that patch is undone the module reverts to the unguarded original, and the cache ensures it is never fixed for the rest of the process (reproduced: Agent.__call__ in workflow code allowed afterwards). If a user installed their wrapper before the plugin import, _run_async is the wrapper and every module holding the original stays unbound; if after, the plugin silently drops their wrapper for later imports.

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 a775aa9: it now skips anything that isn't a plain module (type(module) is types.ModuleType), so None entries and lazy modules are left alone, and a failed install is no longer cached. I left the identity check as is: if someone else has wrapped run_async when the first Worker is built, we can't tell whether to wrap their wrapper or replace it, and either guess can be wrong. Happy to revisit if it shows up outside tests.

Comment thread python/strands_agents/README.md Outdated
Note: Use `agent.invoke_async(message)` instead of `agent(message)`. The synchronous form spawns a worker thread, which the workflow sandbox blocks.
Note: Use `agent.invoke_async(message)` instead of `agent(message)`. Strands runs each synchronous call on a new thread, outside the workflow sandbox and off the workflow event loop, where its model calls and other I/O would not be recorded. So in workflow code, including module-level code in workflow modules, Strands' synchronous calls raise `RuntimeError`: calling an `Agent`, `A2AAgent`, `Graph` or `Swarm`, `agent.structured_output()`, direct tool calls such as `agent.tool.name()`, and anything else Strands runs the same way. Building agents, graphs and swarms still works: Strands uses the same thread to load their tools, and calls made while they are built are not checked. Call agents that do their own I/O, such as an `A2AAgent`, from an activity, for example with `activity_as_tool`.

The error fails the workflow task, so the run stays open and the task is retried until you deploy a fix. A synchronous call in a workflow module's top-level code fails when the worker loads the module, so the worker does not start until you remove the call. A run that made a synchronous call before you deploy this version no longer replays as recorded: if it did not catch the error, its workflow task fails on every attempt; if it caught the error, it now takes its error branch, which fails with a nondeterminism error when that branch schedules other commands and otherwise carries on with state that no longer matches its history. Let those runs finish first, or use Worker Versioning.

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.

P2: 'The error fails the workflow task' is false where the sync call sits inside a tool. For the agents-as-tools pattern (an async @tool that calls other_agent(q), agent.tool.x(), swarm(task), or strands_tools.use_agent/think/swarm/graph), Strands' tool executor catches the RuntimeError and turns it into an error ToolResult; the next model activity runs with 'Error: RuntimeError - Strands runs this sync call ...' as tool output and the workflow completes with no task failure and only a logger.exception line (reproduced on a dev server with TemporalAgent). Pre-PR the nested agent ran on a thread and returned real text, so production runs degrade silently rather than failing, and a pre-PR history replayed through this path changes the tool result but still schedules the same invoke_model activity, so there is no nondeterminism error either. Two other accuracy issues in this paragraph: a module-level sync call 'fails when the worker loads the module' only under SandboxedWorkflowRunner, since with UnsandboxedWorkflowRunner or @workflow.defn(sandboxed=False) the module is imported once on the host with neither in_sandbox() nor a workflow loop, the real call runs at import, and the worker starts normally; and even under the sandbox the user's own host import of the workflow module runs the call once, unguarded, before Worker(...) installs the guard.

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 a775aa9: the README now says that inside a tool Strands catches the error and gives the model an error tool result (I reproduced it with a TemporalAgent whose async tool calls a plain agent), and that a top-level call stops the worker only under the sandboxed runner. The user's own import of the module isn't Workflow code, so it isn't refused before or after the guard is installed.

if not _constructing.get() and (
workflow.in_workflow() or workflow.unsafe.in_sandbox()
):
raise RuntimeError(

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.

P2: Strands-internal sync bridges that fire inside await agent.invoke_async(...) now raise this error with advice the user already followed. SummarizingConversationManager.reduce_context (called synchronously by Agent._execute_event_loop_cycle on context overflow) goes through run_async, so TemporalAgent(conversation_manager=SummarizingConversationManager(...)) fails the workflow task on the first overflow (not ContextWindowOverflowException, so the plugin's workflow_failure_exception_types does not fail the run), and the proactive-compression path wraps reduce_context in except Exception: logger.debug(...), so there the refusal is swallowed and compression silently never happens. SnapshotSessionManager.sync_agent/redact_latest_message from hooks during invocation, and on strands 1.62 (allowed by the unbounded >=1.51.0) Agent.shutdown() from __exit__ whenever a memory_manager is set (with TemporalAgent(..., memory_manager=m) as agent: raises on block exit, chaining over any in-block exception), hit the same guard. Not a regression (these paths failed off-loop before, with _NotInWorkflowEventLoopError), but the message and the README's enumerated list are wrong for them, and the README separately advertises conversation_manager support.

Two more wording points: await graph.invoke_async(...) is recommended unconditionally, but a Graph/Swarm whose nodes are plain Agents (as in SyncCallWorkflow) then runs model calls directly on the workflow loop, the very thing the guard exists to prevent; and for a direct tool call there is no async form at all (tools/_caller.py only has run_async(acall)), so the advice does not fit. Something like 'use the call's async form, such as await agent.invoke_async(...) with TemporalAgent nodes, or move it into an Activity' covers every entry point. The exception class for TemporalAgent(...)('x') also changes from TemporalError to RuntimeError, so a pre-PR workflow that caught TemporalError no longer takes its error branch on replay.

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.

Reworded in a775aa9 along your suggestion: use the call's async form, such as await agent.invoke_async(...) with a TemporalAgent or TemporalAgent nodes, or move the call into an Activity. A second sentence covers calls Strands makes itself (SummarizingConversationManager, SnapshotSessionManager), which don't work in Workflow code; the README lists those and with agent: with a memory_manager. The error is now a RestrictedWorkflowAccessError, which is a TemporalError, so a pre-PR Workflow that caught TemporalError from TemporalAgent(...)('x') still takes the same branch.

def _guarded_run_async(async_func: Callable[[], Awaitable[_T]]) -> _T:
# The sandbox imports Workflow modules before the Workflow runtime is
# attached, so module-level code there is Workflow code too.
if not _constructing.get() and (

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.

P3: this re-implements the sandbox's 'is this restricted workflow code' decision without the SDK's standard opt-out, and raises a type the SDK's mechanism cannot target. Every sandbox restriction honours workflow.unsafe.is_sandbox_unrestricted() first (the repo's langsmith and deepagents thread shims run their in-workflow path under sandbox_unrestricted()), so a caller who deliberately wraps a sync call in that escape hatch is still refused here; one clause fixes it. And the SDK provides the purpose-built error for exactly this situation: temporalio.worker.workflow_sandbox.RestrictedWorkflowAccessError(qualified_name, *, override_message=...), a NondeterminismError subclass that every sandbox restriction raises. With a bare RuntimeError, a worker configured the documented way (workflow_failure_exception_types=[NondeterminismError]) fails the workflow on a threading/concurrent.futures violation but retries the task forever on this one; users must list RuntimeError, which also turns every unrelated bug into a workflow failure (the PR's own tests do exactly that at lines 114 and 132). raise RestrictedWorkflowAccessError("strands._async.run_async", override_message=<current text>) keeps the default task-failure semantics, and the tests then use [NondeterminismError].

On the predicate itself: the in_sandbox() clause is what makes module-level refusal runner-specific (see README line 80), and it is stricter than the SDK's own treatment of the identical ThreadPoolExecutor() call, which the sandbox permits at import time (is_runtime=False) and refuses at runtime. Either drop the clause and the import-time artifacts (symmetric across runners) or state in the README and the comment above that import-time refusal exists only under the sandboxed runner.

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.

Both done in a775aa9: the guard honours workflow.unsafe.is_sandbox_unrestricted(), and raises RestrictedWorkflowAccessError("strands._async.run_async", override_message=...); the tests now use [NondeterminismError]. I kept the in_sandbox() clause, and the README says the top-level refusal applies only under the sandboxed runner.

def wrapper(self: Any, *args: Any, **kwargs: Any) -> None:
token = _constructing.set(True)
try:
init(self, *args, **kwargs)

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.

P3: the allowance is scoped to the exact Agent/Graph/Swarm.__init__ frame. Post-construction tool or plugin loading that Strands documents is refused: agent.tool_registry.process_tools([TemporalMCPClient('other')]) after construction, a Plugin with async def init_agent added later, BidiAgent (a LocalAgent, not an Agent subclass, whose __init__ calls process_tools and is not wrapped), a user MultiAgentBase subclass that mirrors Graph's constructor-time run_async, and a subclass whose __init__ continues after super().__init__() returns (self.tool_registry.process_tools([...]) there is refused although TemporalMCPClient.load_tools needs no workflow API). A subclass that captured Agent.__init__ into its own namespace before the Worker was built (__init__ = Agent.__init__) bypasses the wrapper entirely (reproduced: MyAgent.__init__ is wrapped: False). Also, when the refusal fires inside ToolRegistry.process_tools, Strands re-raises it as ValueError('Failed to load tool ...'), so the documented RuntimeError type, workflow_failure_exception_types=[RuntimeError] and the tests' message-prefix matching do not hold on that path (reproduced).

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.

I'd keep this as is. Each case you list is refused, which is the safe direction: the call fails loudly instead of running unrecorded, and on the process_tools path the ValueError still fails the task. Widening the allowance to later process_tools calls or late plugins would let real I/O through too. If adding a TemporalMCPClient after construction turns out to be something people need, we can allow its load_tools specifically.

return wrapper


@functools.cache

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.

P3: functools.cache does not serialize concurrent first calls, so two threads building Workers at the same time both run the body and Agent/Graph/Swarm.__init__ end up double-wrapped (reproduced: four threads, body ran four times). Harmless today (nested set/reset of the same ContextVar), but the 'runs once per process' docstring is not guaranteed and any future non-idempotent step would break. A lock, or an explicit flag set at the top, fixes it.

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 a775aa9: a lock and a flag set at the end replace functools.cache.


_T = TypeVar("_T")

_run_async = strands._async.run_async

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.

P3: the private strands._async.run_async is resolved at package import with no upper bound on strands-agents, so a rename upstream breaks import temporalio.strands_agents for every importer, including client-only code, with an AttributeError that names neither the guard nor the supported version. Resolving it inside refuse_sync_calls_in_workflows() and failing there with an actionable error (silently skipping the guard would reintroduce the original bug) keeps the failure loud but scoped; nothing in 1.62 provides a public bridge that would remove the patch. The module docstring's 'every sync entry point' also overclaims: strands.tools.mcp.MCPClient's sync entry points and tool execution use a dedicated background thread with run_coroutine_threadsafe, never run_async, so MCPClient(transport) tools and list_tools_sync()/call_tool_sync() are never refused.

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 a775aa9: strands._async.run_async is now looked up when the guard installs (Worker or Replayer creation), and if it's missing that fails with an error that names the guard and says the Strands version isn't supported. The docstring now says "most" entry points and that MCPClient uses its own background thread.

task_queue=task_queue,
workflows=[SyncCallWorkflow],
plugins=[plugin],
max_cached_workflows=0,

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.

P3 (tests): max_cached_workflows=0 has no effect here (the workflow fails in its first and only task, so there is nothing to evict), and the replay is repeated three times for three parametrizations that exercise the same process-global, cached guard (~45% of each case's wall time); keep one replay. SyncCallWorkflow also scripts model responses that are never consumed and builds a second named Agent only to seed the Swarm; agent = Agent(model=MockModel([]), tools=[echo_tool], callback_handler=None) and swarm = Swarm([agent]) give the same four outcomes.

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.

Done in a775aa9: dropped max_cached_workflows=0, kept one replay (the agent case), and the Workflow now builds one Agent with MockModel([]) and Swarm([agent]).

Comment thread python/strands_agents/README.md Outdated
```

Note: Use `agent.invoke_async(message)` instead of `agent(message)`. The synchronous form spawns a worker thread, which the workflow sandbox blocks.
Note: Use `agent.invoke_async(message)` instead of `agent(message)`. Strands runs each synchronous call on a new thread, outside the workflow sandbox and off the workflow event loop, where its model calls and other I/O would not be recorded. So in workflow code, including module-level code in workflow modules, Strands' synchronous calls raise `RuntimeError`: calling an `Agent`, `A2AAgent`, `Graph` or `Swarm`, `agent.structured_output()`, direct tool calls such as `agent.tool.name()`, and anything else Strands runs the same way. Building agents, graphs and swarms still works: Strands uses the same thread to load their tools, and calls made while they are built are not checked. Call agents that do their own I/O, such as an `A2AAgent`, from an activity, for example with `activity_as_tool`.

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.

P3 (docs): the two Note paragraphs repeat the top-level-code fact, explain plugin internals the user cannot act on, and expand the one-line migration note used at line 115 into a caught/uncaught taxonomy. A shorter form keeps every fact: list the refused calls once (including the internal bridges above), say building agents, graphs and swarms still works, state that the error fails the workflow task so the run stays open until a fix is deployed (a top-level call fails worker startup under the sandboxed runner), and keep the single 'let those runs finish first, or use Worker Versioning' sentence.

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.

Shortened in a775aa9 along those lines: one list of refused calls (including Strands' own bridges), building still works, the task failure, the startup failure under the sandboxed runner, and one upgrade sentence.

- Raise RestrictedWorkflowAccessError, the sandbox's own error, so
  workflow_failure_exception_types=[NondeterminismError] fails the run
  and code that caught TemporalError keeps working.
- Honour workflow.unsafe.sandbox_unrestricted().
- Track construction with a thread-local depth instead of a ContextVar,
  so tasks created while an agent is built do not inherit the
  allowance.
- Skip sys.modules entries that are not plain modules (None, lazy
  modules) when rebinding run_async.
- Install under a lock instead of functools.cache, and look up
  strands._async.run_async at install, failing with a clear error if
  it is missing.
- Reword the error for every entry point, including calls Strands
  makes itself.
- README: shorter note; list Strands' own sync calls; say a refusal
  inside a tool becomes an error tool result, and that a top-level
  call stops the worker only under the sandboxed runner.
- Tests: one replay, no Workflow cache setting, a simpler Workflow.
@campoy

campoy commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

@DABH Thanks for the second pass. All threads are answered; the changes are in a775aa9. On the pre-existing sync @tool issue from your summary: agreed, and it isn't caused by this PR. We already track it and will file it as its own issue; I added it to "Not covered" in the PR body.

The existing defect was already documented for:

A new issue tracking both has been created: #282

@campoy
campoy requested a review from DABH October 29, 2026 22:27

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

Third round, at head a775aa9. Same recipe: ten finder angles, 17 deduplicated candidates (14 from the finders, 3 from the gap sweep) each put through an adversarial verifier: 10 confirmed, 1 plausible, 6 refuted and dropped. make lint passes and make test runs 141 tests green on the head. Dropped after verification: a claimed 60 s timeout mode of test_sync_call_is_refused (the regression shows immediately in all three parametrizations); the three refused-call enumerations (they serve different audiences and match Strands 1.56 to 1.62); the per-module @tool helpers and the Worker consolidation (suite norm, no measurable saving); the sweep's 'no async form for direct tool calls' item (restates round-one item 6, and 'move the call into an Activity' is the wording from that round); and README line 115 on proactive compression (unchanged by the PR, and summarization was already a silent no-op on main by probe).

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Previous rounds. Addressed: the fail-open list of six wrappers is now a guard on strands._async.run_async with a rebind of loaded strands.* modules; the a2a stack is no longer imported; the message names the target and the error is RestrictedWorkflowAccessError, so workflow_failure_exception_types=[NondeterminismError] and a pre-existing except TemporalError both still match; is_sandbox_unrestricted() is honoured; the install runs from _workflow_runner instead of the plugin constructor; the uncaught path and the module-level import are tested; functools.cache gave way to a lock and flag; run_async is resolved lazily with an actionable error; the ContextVar leak became a thread-local depth counter; vars(module) is guarded by the ModuleType check; the README is shorter. Decisions I take as recorded: no version gate, the constructor-wide allowance, the identity check, the a2a extra staying out of CI, and the process_tools ValueError re-wrap left undocumented. One regression in the docs: the round-one README sentence about a run that caught the error (its error branch fails with TMPRL1100 or carries on with state that no longer matches History) survives only in the PR body now.

Where this round's items cluster: the guard covers the documented entry points, and what is left is the edges of the installation itself: a reference to run_async bound outside strands. before the install, a half-applied install that the retry cannot repair, two untested clauses, and documentation that states the task-failure outcome unconditionally.

PR body: 'makes Worker and Replayer creation fail (Failed validating workflow)' is wrong for the Replayer: Replayer(...) constructs successfully (its __init__ runs configure_replayer but never prepare_workflow), and the failure surfaces from the first replay_workflow or workflow_replay_iterator call, before any history is pushed (/tmp/pr192-probes/replayer_creation.py). README line 80 covers only the Worker and could add 'and fails every replay on a Replayer that registers that module'; the test could add a Replayer that constructs and whose replay_workflow(...) raises. The separate missing-run_async path is described correctly. Not verifiable here: the realism count for the pre-bound binding comes from a code search that was not re-run; A2AAgent, structured_output() and Graph remain untested in CI by your decision.

strands._async.run_async = guarded
# Strands modules bind run_async when they are imported; rebind the
# ones already loaded. Modules imported later get the guarded one.
for name, module in list(sys.modules.items()):

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.

P2: the guard is installed on the name binding, so a reference to run_async bound outside a strands. module before the first Worker or Replayer is built keeps the unguarded original. Confirmed end to end: a helper module does from strands._async import run_async at module level and is imported at process start; the Worker with StrandsPlugin is built afterwards; the workflow module imports the helper under with workflow.unsafe.imports_passed_through(): and calls helper.call_sync(agent, 'Hello') from @workflow.run. Under the default sandboxed runner the call is allowed, the model call runs on run_async's executor thread (is_run_async_bridge() True, workflow.in_workflow() False), nothing is recorded, and the Workflow completes with the answer (/tmp/pr192-probes/test_e2_prebound.py, six cases: direct and plain-sandboxed imports refused, passthrough and unsandboxed allowed). Not round-two item 11, which was about strands.* modules patched by someone else; this is the population the scan never visits. GitHub code search shows the module-level binding in a handful of application repos, so uncommon rather than contrived. Broader fix verified with the full suite (141 passed): guard strands._async.ThreadPoolExecutor, which run_async looks up as a module global on every call in every release from 1.34.1 to 1.62.0, so every caller of the original function object is covered and the sys.modules scan, identity check and ModuleType filter become unnecessary; keeping line 97 alongside it keeps failing loudly if a future Strands stops using the executor.

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.

Done in 3ea52ac: the guard now wraps strands._async.ThreadPoolExecutor, so every reference to run_async is covered, including ones bound before the install. The module scan, identity check and ModuleType filter are gone, and run_async is still replaced where it's defined, as you suggested. A new prebound case in test_sync_call_is_refused covers it: a helper module binds run_async at import, and the Workflow reaches it through a passthrough import. It's refused now, and the case fails with the executor guard removed.

if (
name.startswith("strands.")
and type(module) is types.ModuleType
and vars(module).get("run_async") is run_async

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.

P2 (plausible, cheap hardening): a first install that raises after line 97 but before _installed = True leaves the retry unable to finish the job, silently. Line 82 re-reads strands._async.run_async on every attempt, so after a failed first attempt the second compares module bindings against the first guarded instead of the original; every Strands module the failed attempt did not reach keeps the unguarded original, _installed becomes True, and nothing is logged. Reproduced with a real Worker by injecting a failure after strands.tools._caller in the loop (/tmp/pr192-probes/test_c2_retry_e2e.py): after attempt two agent('Hello') in Workflow code returns the model answer with zero ActivityTaskScheduled events while agent.tool.x() is refused. Trigger realism is low: nothing synchronous can raise in lines 97 to 108 in a sane process, so it takes a second Ctrl-C or the _ThreadLocalSysModules.items() iteration race (dictionary changed size during iteration, probe-confirmed) plus an in-process Worker rebuild. Fix: remember the original once in a module global before mutating anything, or tag guarded.__wrapped__ = run_async and compare inspect.unwrap(...) identities, or assign line 97 after the loop and the class wrapping.

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 by the same change in 3ea52ac: with no module scan, every install step is safe to repeat (wrapping the executor, run_async or a constructor twice only adds a second check), so a retry after a failed first attempt ends fully guarded.

Comment thread python/strands_agents/README.md Outdated
Note: Use `agent.invoke_async(message)` instead of `agent(message)`. The synchronous form spawns a worker thread, which the workflow sandbox blocks.
Note: Use `agent.invoke_async(message)` instead of `agent(message)`. Strands runs its synchronous calls on a new thread, outside the workflow sandbox and off the workflow event loop, where their model calls and other I/O would not be recorded. So in workflow code these raise `RestrictedWorkflowAccessError`: calling an `Agent`, `A2AAgent`, `Graph` or `Swarm`, `agent.structured_output()`, direct tool calls such as `agent.tool.name()`, and Strands features that make such calls themselves, such as `SummarizingConversationManager`, `SnapshotSessionManager`, and, in recent Strands versions, leaving `with agent:` when the agent has a `memory_manager`. Building agents, graphs and swarms still works, and calls made while they are built are not checked. Call agents that do their own I/O, such as an `A2AAgent`, from an activity, for example with `activity_as_tool`.

The error fails the workflow task, so the run stays open until you deploy a fix. Inside a tool, Strands catches it and gives the model an error tool result instead. Under the default sandboxed runner, a synchronous call in a workflow module's top-level code also stops the worker from starting. A run that made a synchronous call before you deploy this version no longer replays as recorded: let those runs finish first, or use Worker Versioning.

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.

P3: 'The error fails the workflow task, so the run stays open until you deploy a fix' is unconditional, but RestrictedWorkflowAccessError is a NondeterminismError, so on a Worker or @workflow.defn that lists NondeterminismError, TemporalError or Exception in its failure types (the SDK-documented fail-on-nondeterminism setup, and what this PR's own tests use) the refusal ends the run as Failed. That is a change from main for a TemporalAgent sync call, whose _NotInWorkflowEventLoopError is not a NondeterminismError. Probe on the dev server (/tmp/pr192-probes/c3_routing.py): head with the default config, RUNNING with one failed task; head with [NondeterminismError], FAILED with an ApplicationError of type RestrictedWorkflowAccessError and no failed task; main-like with [NondeterminismError], RUNNING. A reader who schedules the fix after the upgrade on the strength of 'stays open' loses those in-flight runs, and the PR body's upgrade paragraph makes the same unconditional claim. One qualifying clause in both places.

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.

Done in 3ea52ac: the README and the PR body's upgrade note now say the run stays open unless the Worker or Workflow lists NondeterminismError in its failure exception types, which fails the run instead.

"""The sandbox imports Workflow modules before the Workflow runtime is attached."""
# Outside Workflow code the guard lets the sync call run, so an ordinary
# import of the module still works.
refuse_sync_calls_in_workflows()

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.

P3 (tests): this test installs the guard itself before building the Worker, so it cannot detect a regression in the plugin's install timing. The guard must be installed by _workflow_runner during configure_worker, before _WorkflowWorker validation (_worker.py:410-411 then :539). Mutation 'install moved into run_worker' leaves the whole suite green (141 passed) while Worker(plugins=[StrandsPlugin()]) validates SyncImportWorkflow with the original run_async, the module-level Agent(...)('Hello') runs a real model call during sandbox import, and the Worker starts; the README's 'stops the worker from starting' is then false through the plugin path. A complete removal is still caught by the three activation tests. Verified fix (/tmp/pr192-probes/test_c4_fix.py): delete line 149 and its comment, keep the import and the pytest.raises block, then re-run the module-level code after the Worker build with importlib.reload(sync_import_workflow) and assert import_result == 'import answer'; passes on the head and fails for both mutants. The import of refuse_sync_calls_in_workflows at line 22 becomes unused.

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.

Done in 3ea52ac: the test no longer installs the guard itself. It relies on Worker(...) installing it before validation, and re-runs the module-level code with importlib.reload afterwards. With the install removed from _workflow_runner, it fails.



def _in_workflow_code() -> bool:
if _building.depth or workflow.unsafe.is_sandbox_unrestricted():

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.

P3 (tests): the is_sandbox_unrestricted() clause has no test. grep -rn 'sandbox_unrestricted\|unsafe' tests/ is empty; removing the clause leaves all 11 tests in test_model.py green, while a user who deliberately wrote with workflow.unsafe.sandbox_unrestricted(): agent('Hello') in Workflow code would get the refusal instead of the answer. /tmp/pr192-probes/test_unrestricted_probe.py catches the mutant (1 failed, 1 passed) and prints the answer on the head. A workflow branch that wraps agent('Hello') in the unrestricted block with MockModel(['answer']) under the same Worker config as test_sync_call_is_refused covers it; if the README mentions the hatch, say the call then runs on Strands' thread, unrecorded.

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.

Added in 3ea52ac: an unrestricted branch in SyncCallWorkflow wraps the sync call in sandbox_unrestricted() and returns the answer, and test_sync_call_workflow_builds_without_calls runs it. It fails with the clause removed.



def _workflow_runner(runner: WorkflowRunner | None) -> WorkflowRunner:
# Strands runs sync calls on its own thread, which no runner restricts.

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.

P3 (comment): '# Strands runs sync calls on its own thread, which no runner restricts.' omits the load-bearing half. The sandboxed runner's concurrent.futures and threading restrictions would intercept Strands' exact thread hop if the code were sandbox-loaded; what defeats them is the plugin's own passthrough of strands seven lines below, because host module globals are never proxied, and the SDK's threading matcher is only_runtime, so it could never cover the module-level case the guard handles via in_sandbox(). Probe with the passthrough set and the guard off (/tmp/pr192-probes/probe_c7_sandbox_loaded_hop.py): a sandbox-loaded ThreadPoolExecutor at runtime is intercepted, the host strands._async.run_async is not. Suggested: # Strands' sync calls start a new thread from the passed-through (host) strands modules, so the sandbox's threading restrictions never see the hop and nothing restricts that thread; refuse them here for every runner.

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.

Reworded in 3ea52ac along your suggestion.

from collections.abc import Awaitable, Callable
from typing import Any, TypeVar

from strands import Agent

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.

P3 (cleanup): run_async is resolved lazily under a curated 'not supported' error, but Agent, Graph and Swarm are hard-imported at module scope solely for the __init__ wrapping loop at line 107, so the same feature has two drift failure modes, and import temporalio.strands_agents now loads strands.multiagent (five modules, about 5 ms) in every process, client-only ones included, which main never did. Graph is not re-exported from strands.multiagent in any release from 1.34.1 to 1.62.1, so a future move makes import temporalio.strands_agents fail with a bare ImportError at line 21 before any Worker exists, with no hint that the guard's constructor allowance needs it, whereas the same drift in strands._async fails later with the curated message. A lazy copy with the three imports inside the existing try block (message generalized) passes all six lint tools and the relevant tests. Eager imports of private Strands paths are the package norm (_temporal_agent.py:6), so a decline is reasonable; the within-file asymmetry is the point.

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.

I'll leave these as they are: eager imports of Strands' paths are the package's norm, as you note, and a moved Graph failing loudly at import is acceptable to us.

"code. This strands-agents version is not supported."
) from err

def guarded(async_func: Callable[[], Awaitable[_T]]) -> _T:

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.

P3 (cleanup): guarded replaces the process-wide strands._async.run_async as a bare local closure with no functools.update_wrapper, unlike _allow_during at line 62. After any Worker or Replayer is configured, __name__, __qualname__, __module__ and __doc__ are the closure's, inspect.unwrap has no __wrapped__ to follow, and pickle.dumps(strands._async.run_async) raises PicklingError (probe /tmp/pr192-probes/c8_probe.py). Nothing in Strands or the plugin introspects it today. The statement form functools.update_wrapper(guarded, run_async) before line 97 passes every lint gate; the decorator form fails this repo's mypy check at the assignment on line 97.

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.

Done in 3ea52ac: functools.update_wrapper(guarded, run_async).

await handle.result()
cause = err.value.cause
assert isinstance(cause, ApplicationError)
assert cause.type == "RestrictedWorkflowAccessError"

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.

P3 (tests): the new tests hard-code the exception class name (here) and the message prefix (117 and 161-163) as literals although the module already imports from _sync_calls, which exposes _MESSAGE, and the SDK exports RestrictedWorkflowAccessError. The type literal was already retyped once inside this PR (from RuntimeError at 627dbee to the current name at a775aa9), and the prefix survived the _MESSAGE rewording only because the opening clause stayed. The stronger forms cause.type == RestrictedWorkflowAccessError.__name__, cause.message == _MESSAGE and isinstance(err.value.__cause__, RestrictedWorkflowAccessError) all hold exactly on the head (probe /tmp/pr192-probes/c13_probe.py); the prefix test at 161 would accept any exception type carrying that text, though no current Strands path produces one.

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.

Done in 3ea52ac: the tests compare with RestrictedWorkflowAccessError.__name__ and _MESSAGE, and the module-level test checks the cause with isinstance.

)
return run_async(async_func)

strands._async.run_async = guarded

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.

P3 (comment): line 97 and the loop at 100-106 are order-dependent alternatives, not a definition plus a sweep, and the comment does not say so. Because line 97 runs first, the identity check at 104 is False for strands._async and the loop skips it (probe: the loop rebinds nine consumer modules, never strands._async); with line 97 deleted the loop rebinds strands._async itself and the end state is byte-for-byte identical. Keep line 97 as the authoritative rebinding of the definition site and say in the comment that the loop is for consumer modules that bound the name at import.

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.

The loop is gone in 3ea52ac. The comments now say the executor guard covers every reference and the guard where run_async is defined is the fallback.

- Guard the ThreadPoolExecutor that strands._async.run_async looks up on
  every call, so a reference to run_async bound before the install is
  refused too. Drop the sys.modules scan; keep the guard where run_async
  is defined, now with functools.update_wrapper. Every install step is
  safe to repeat.
- README: the run stays open unless NondeterminismError is a failure
  exception type; a top-level call also fails every replay; a run that
  caught the error takes its error branch on replay.
- Tests: a prebound run_async case; a sandbox_unrestricted() case; the
  module-level test relies on the Worker to install the guard; compare
  with the error class name and _MESSAGE.
- Explain in _plugin.py why the sandbox misses the thread.
@campoy

campoy commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

@DABH Thanks for the third pass. All threads are answered; the changes are in 3ea52ac. From your summary: the PR body and README now say that a Replayer builds and then fails every replay of that Workflow, and the README has the sentence about runs that caught the error again. I didn't add a Replayer case to the test.

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

Fourth round, at head 3ea52ac (one commit over a775aa9). make lint passes and make test runs 142 tests green on the head (macOS, Python 3.14), and CI is green. Each finding below was checked with a mutation of the installed package (executor guard removed; install moved from _workflow_runner into the plugin's run_context; the is_sandbox_unrestricted() clause removed) or a binding probe in a fresh interpreter, and each suggested test fix was run against both the head and the mutant and passes every lint step. Refuted: the PR body's 'with only the executor guard removed, the prebound case fails too' (that case passes; the other three refusal cases and the sandbox-import test fail). I looked for callers the executor guard could now refuse wrongly and found none: in strands._async, ThreadPoolExecutor is used only by run_async in 1.51.0, 1.56.0 and 1.62.0, and the refused set is the round-three set plus references bound outside strands., as intended. Not re-run here: the Docker, Python 3.13 run in the body.

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Previous rounds. Addressed from round three: the pre-bound run_async P2 (the executor guard covers every holder of the original; the agent, tool and swarm cases now depend on it, though the case meant to show it does not, see line 31); the half-applied install P2 (with the scan gone every step re-reads and re-wraps the current binding, so a retry ends fully guarded); the README's 'stays open' now names the NondeterminismError exception; the is_sandbox_unrestricted() clause has a test that catches its removal (slowly, see line 148); the _plugin.py comment; update_wrapper; the tests compare with RestrictedWorkflowAccessError.__name__ and _MESSAGE; the line-97 comment went with the loop; the README and the body now say a Replayer builds and then fails every replay, and the README again says what happens to a run that caught the error. Partly addressed: the sandbox-import test no longer installs the guard itself, but it catches the install-timing regression only when it runs first in its process (line 170). Declines I accept: the eager Agent, Graph and Swarm imports, and no Replayer case in the test. Nothing blocking is open from earlier rounds.

Where this round's items cluster: the guard itself holds up; all four items are about how the new mechanism is tested or described. The prebound case is not pre-bound under the sandbox, the definition-site fallback reaches no module that is already loaded, the install-timing check depends on test order, and one regression shows up only as a 60 s timeout.

Approving: no P1 or blocking P2 remains, every earlier P2 is addressed and CI is green; the four P3 items below are non-blocking.

from tests.mock_model import MockModel

with workflow.unsafe.imports_passed_through():
from tests import prebound_run_async

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.

P3 (tests, non-blocking): the prebound case does not exercise a pre-bound reference. Under the sandboxed runner, from tests import prebound_run_async re-executes the helper inside the sandbox after the guard is installed, so the helper binds the guarded run_async and the case passes without the executor guard. The statement calls __import__('tests', fromlist=['prebound_run_async']). The sandbox importer decides on passthrough only for that name (workflow_sandbox/_importer.py:204-224 in SDK 1.34.0), and tests is already in the sandbox's sys.modules because the sandbox is re-importing tests.test_model. So the submodule is loaded fresh through the fromlist by importlib.__import__ (:261-262), which never reaches the passthrough check. Printing id(prebound_run_async) and hasattr(prebound_run_async.run_async, '__wrapped__') from this module confirms it: at collection the helper holds the original, and each sandboxed import gets a different module object holding guarded. Mutation with line 109 of _sync_calls.py removed (executor guard off): agent fails with MockModel script exhausted (the model ran on Strands' thread), tool and swarm give DID NOT RAISE, the sandbox-import test gives DID NOT RAISE, and prebound passes. That is the reverse of the body's claim. The executor guard is still covered, because the agent, tool and swarm paths go through bindings that strands.agent.agent, strands.tools._caller and strands.multiagent.base made at plugin import; only this case and the body claim are wrong. Verified fix: from tests.prebound_run_async import run_async as prebound_run_async here and prebound_run_async(lambda: agent.invoke_async("Hello")) at line 97. The dotted name is not in the sandbox's sys.modules, so it passes through and returns the host module's original binding. With that change the case passes on the head, fails under the mutant, and every lint step passes. Then correct the body's 'with only the executor guard removed, the prebound case fails too'.

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.

Thanks, you're right. Fixed in 045b4fc: the test now imports from tests.prebound_run_async import run_async as prebound_run_async, which passes through the sandbox and keeps the binding made at collection. With the executor guard removed, the case now fails. I corrected the PR body too.

# run_async looks up ThreadPoolExecutor on every call, so this guards every
# reference to run_async, also ones bound before this install.
setattr(strands._async, "ThreadPoolExecutor", guarded_executor)
# Guard run_async where it is defined too, in case a later Strands stops

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.

P3 (comment, non-blocking): line 112 is described as the fallback 'in case a later Strands stops using the executor', but with the module scan gone it reaches none of the Strands modules that are already loaded. In that case agent(...) in Workflow code would run unguarded, with no error. Probe in a fresh interpreter (import temporalio.strands_agents, then refuse_sync_calls_in_workflows()): after the install, nine modules still hold the original run_async: strands.agent.agent, strands.tools._caller, strands.tools.registry, strands.multiagent.base, .graph, .swarm, strands.plugins._discovery, strands.session.snapshot_session_manager and strands.agent.conversation_manager.summarizing_conversation_manager. This package imports strands and strands.multiagent before any Worker exists, so they all bind first. Only a module imported later, in practice strands.agent.a2a_agent, picks up guarded. Removing line 109 simulates exactly that drift: the agent, tool and swarm cases and the sandbox-import test all stop raising. The likelier form of the drift, Strands dropping the ThreadPoolExecutor import, already fails at line 83 with the 'not supported' error, so line 112 only matters if the import outlives its use. Suggested: make the drift fail closed at install by raising the existing RuntimeError when "ThreadPoolExecutor" not in inspect.unwrap(run_async).__code__.co_names. On the head that test is True before and after an install, and False for a threading.Thread variant. Then either drop line 112 or say it covers only modules that import run_async after the first Worker or Replayer. The body's 'in case a later Strands stops using the executor' needs the same correction, and 'If Strands no longer has run_async, Worker and Replayer creation fail' should also mention the ThreadPoolExecutor name, as the error message at line 86 does.

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 045b4fc: the install now raises the 'not supported' RuntimeError when run_async no longer names ThreadPoolExecutor (checked on inspect.unwrap(run_async).__code__.co_names), so that drift fails closed. I dropped the guard where run_async is defined, since it reached none of the modules already loaded. The PR body now says Worker and Replayer creation fail if run_async is missing or no longer uses a ThreadPoolExecutor.

"""The sandbox imports Workflow modules before the Workflow runtime is attached."""
from tests import sync_import_workflow

# Building the Worker installs the guard before it validates 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.

P3 (tests, non-blocking): this test catches the install-timing regression only when it builds the first Worker in its process. In the full suite an earlier test has usually installed the guard already, so the check depends on test order. Mutation with the install moved from _workflow_runner into the plugin's run_context: the test alone fails with DID NOT RAISE, but three full make test runs (-n auto --dist=worksteal, 142 tests each) are all green. _installed is process-wide, and any earlier async with Worker(...) in the same xdist process entered run_context. Verified fix: reset the install with monkeypatch at the start of the test, so this Worker must install the guard itself and teardown restores the earlier state: monkeypatch.setattr(_sync_calls, "_installed", False), monkeypatch.setattr(strands._async, "run_async", inspect.unwrap(strands._async.run_async)), monkeypatch.setattr(strands._async, "ThreadPoolExecutor", concurrent.futures.ThreadPoolExecutor), and monkeypatch.setattr(cls, "__init__", inspect.unwrap(cls.__init__)) for Agent, Graph and Swarm (the new update_wrapper and the existing functools.wraps make the unwraps work). With that change the full suite fails the mutant on this test, passes on the head, and every lint step passes. Running the Worker build in a subprocess would also work.

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.

Done in 045b4fc: the test first undoes any earlier install with monkeypatch (_installed, strands._async.ThreadPoolExecutor, and the unwrapped Agent, Graph and Swarm.__init__), so its Worker must install the guard itself. With the install moved into run_context, the full suite now fails on this test.

client,
task_queue=task_queue,
workflows=[SyncCallWorkflow],
plugins=[StrandsPlugin(models={"mock": lambda: MockModel([])})],

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.

P3 (tests, non-blocking): with the is_sandbox_unrestricted() clause removed, this test fails only through pytest-timeout after 60 s. This Worker lists no failure exception types, so the refusal becomes a Workflow Task retry loop. Mutation: test_sync_call_workflow_builds_without_calls fails with Timeout (>60.0s) from pytest-timeout, with no hint of the cause. Adding workflow_failure_exception_types=[NondeterminismError] to this Worker, as test_sync_call_is_refused does, makes the same mutant fail in 0.4 s with WorkflowFailureError, and the head still passes.

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.

Done in 045b4fc: this Worker now lists NondeterminismError, so that mutant fails quickly with WorkflowFailureError instead of timing out.

- Fail the install with the "not supported" error when run_async no
  longer uses ThreadPoolExecutor, and drop the guard where run_async is
  defined: it reached none of the Strands modules already loaded.
- Tests: import the prebound helper by its dotted name so it passes
  through the sandbox; undo any earlier install in the module-level test
  so it no longer depends on test order; list NondeterminismError in the
  build test's Worker so its mutant fails fast.
@campoy

campoy commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

@DABH Thanks for the approval and the fourth pass. All four threads are answered; the changes are in 045b4fc. The PR body now says what ran locally and what's left to CI.

@campoy
campoy merged commit a2b6efe into main Oct 31, 2026
27 checks passed
@campoy
campoy deleted the fix/strands-python-sync-agent-call-escapes-sandbox branch October 31, 2026 00:33
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.

[Bug] strands_agents: Strands' sync agent calls run unrecorded in Workflow code and again on replay

2 participants