CodeMode serializes in-sandbox dispatch under `parallel_ordered_events`, so `asyncio.gather` is inert on every durable run
Capability
CodeMode
Bug Description
CodeMode decides whether nested sandbox calls may overlap with _global_mode_is_sequential, which is get_mode() != 'parallel' (code_mode/_toolset.py). That folds three run-scoped modes into two: 'parallel_ordered_events' is treated exactly like 'sequential', so deferred calls are held as bare coroutines and awaited one at a time (_monty_exec.py), and a model-written asyncio.gather inside a snippet costs the sum of its calls' latencies instead of the max.
This bites durable runs specifically, because parallel_ordered_events is the mode they are steered to: DBOSParallelExecutionMode is Literal['sequential', 'parallel_ordered_events'] — 'parallel' is excluded as non-deterministic — and DBOSDurability defaults to 'parallel_ordered_events'. So a DBOS agent silently loses in-sandbox parallelism, which is the headline benefit of CodeMode: the code_mode README's own comparison row reads "Parallelism expressed in Python", and its quick start showcases exactly this — "fetches all three feeds in parallel via asyncio.gather".
It is also surprising from the docs. pydantic-ai describes the two parallel modes as differing only in event emission order — "'parallel_ordered_events': Run tool calls in parallel, but events are emitted in order, after all calls complete" — and nested sandbox calls emit no run events, so nothing in that documented distinction points at sandbox dispatch. There is no warning, log, or return-metadata field saying the gather was serialized; the only symptom is latency.
I can see the counter-argument — pydantic/pydantic-ai-harness#524's description says the FIFO sandbox ordering is "what DBOS parallel_ordered_events replay depends on". If that is the intent, the ask is that it become expressible separately rather than inferred, e.g. a CodeMode(parallel_dispatch=...) parameter, because one knob is currently carrying two unrelated decisions: top-level checkpoint/event ordering, and whether the sandbox may overlap its dispatches. Users whose nested calls are not individually checkpointed pay a large latency cost for a determinism property they do not need — in our case the sandbox runs inside an enclosing durable step, so its nested calls record no checkpoints at all and there is nothing for replay to reorder, but there is no way to say so.
Minimal Reproduction
import asyncio
import time
from pydantic_ai import Agent
from pydantic_ai.messages import ModelResponse, TextPart, ToolCallPart, ToolReturnPart
from pydantic_ai.models.function import FunctionModel
from pydantic_ai.tool_manager import ToolManager
from pydantic_ai.tools import RunContext
from pydantic_ai.toolsets import FunctionToolset
from pydantic_ai_harness import CodeMode
LATENCY = 0.3
live = peak = 0
async def _work(name: str) -> str:
global live, peak
live += 1
peak = max(peak, live)
try:
await asyncio.sleep(LATENCY)
return name
finally:
live -= 1
toolset = FunctionToolset()
@toolset.tool
async def search_a(ctx: RunContext, q: str) -> str:
"""Slow tool A."""
return await _work("a")
@toolset.tool
async def search_b(ctx: RunContext, q: str) -> str:
"""Slow tool B."""
return await _work("b")
@toolset.tool
async def search_c(ctx: RunContext, q: str) -> str:
"""Slow tool C."""
return await _work("c")
SNIPPET = """
import asyncio
r = await asyncio.gather(search_a(q="x"), search_b(q="y"), search_c(q="z"))
print(r)
"""
def model_fn(messages, _info):
if any(isinstance(p, ToolReturnPart) for m in messages for p in getattr(m, "parts", [])):
return ModelResponse(parts=[TextPart(content="done")])
return ModelResponse(parts=[ToolCallPart(tool_name="run_code", args={"code": SNIPPET})])
async def run(mode):
global live, peak
live = peak = 0
agent = Agent(retries=0, toolsets=[toolset], capabilities=[CodeMode()])
with ToolManager.parallel_execution_mode(mode):
started = time.monotonic()
await agent.run("go", model=FunctionModel(model_fn, model_name="probe"))
return time.monotonic() - started, peak
async def main():
for mode in ("parallel", "parallel_ordered_events", "sequential"):
elapsed, pk = await run(mode)
print(f"{mode:<24} elapsed={elapsed:.2f}s peak_concurrency={pk}")
asyncio.run(main())Output — three independent 0.3s calls, gathered:
parallel elapsed=0.41s peak_concurrency=3
parallel_ordered_events elapsed=0.93s peak_concurrency=1
sequential elapsed=0.93s peak_concurrency=1Expected: parallel_ordered_events matches parallel here, or the serialization is opt-in/opt-out-able rather than derived from a mode that documents itself as being about event ordering.
pydantic-ai-harness version
0.21.0 (_global_mode_is_sequential is byte-identical in 0.25.0)
pydantic-ai version
2.31.1
Source: pydantic/pydantic-ai