Keep `DynamicWorkflow` sub-agents parallel under `DBOSDurability` and `AWSLambdaDurability` with dispatch-ordered durable IDs
Part of the harness durable-parity audit, item 6 (DynamicWorkflow durable ordering). There is no issue.
Why we make these changes
DynamicWorkflow runs its script in workflow code, and the script can run sub-agents concurrently. A sub-agent with its own durability makes durable steps from that workflow code. DBOS and AWS Lambda both number steps in the order they start, so concurrent sub-agents' steps were numbered by timing, and recovery could replay one sub-agent's results into another call. On DBOS, a recovered gather(summarize('alpha'), summarize('beta')) returned ['summary of beta', 'summary of alpha']. On AWS Lambda, replay diverged.
With this PR, sub-agents still run in parallel on both engines, and each call gets a durable identity that comes from its dispatch position, not from completion order.
DBOS: one step per call, with its ID reserved in dispatch order. Each call to a sub-agent that has DBOSDurability is recorded as one DBOS step named {tool_name}.{agent_name} (e.g. run_workflow.summarize). The step ID is drawn with DBOS.reserve_step() in the suspension-free part of the dispatch, next to the max_agent_calls budget check. This is the same reservation DBOSDurability uses for its event-handler steps, including the SnapshotStepReservation fallback for dbos < 3.4.
AWS Lambda: one parallel branch per call. I checked this separately, and Lambda can run sub-agents in parallel too. Every sub-agent call the script makes up to its next wait runs as a branch of one context.parallel(...) operation named after the tool (run_workflow), with branches in dispatch order. Each branch gets a child context whose step IDs derive from the branch's position. The SDK runs each branch on a worker thread, and that thread services the branch's steps just as the handler thread services the root context's. A sub-agent keeps its own step-level checkpoints inside its branch.
How the Lambda path fits the bridge's single-handler-thread design:
- The handler thread still creates every root-context operation, in order.
context.parallelis one root operation, and the handler thread blocks in it while branches run, the same way it blocks in a step today. While it is blocked, the orchestrator is waiting inside therun_workflowtool call (which runs alone), so no other root step is needed. - The SDK already calls
step()from branch worker threads:DurableContextuses a locked counter and per-context replay state, andConcurrentExecutorruns each branch on aThreadPoolExecutorworker. The new_run_branchgives each branch its ownStepBridgeon that worker. The sub-agent runs on the agent loop with that bridge in its_active_bridgecontext var. - Branch membership has to be deterministic, and
parallelneeds all branches up front. SoMontyExecutorgets aflushhook, awaited when the script reaches a wait (aFutureSnapshot), before futures resolve. By then every call dispatched so far has run its suspension-free prefix and joined the batch, in dispatch order. Calls dispatched later go into a laterparalleloperation. - A sub-agent failure is returned as data from its branch (
{'error': ...}), so one failed call doesn't fail the batch'sall_successfulcompletion. - Branch results and the aggregate
BatchResultare checkpointed with theserdesfrom the sub-agent'sAWSLambdaDurability(step_config=...), throughParallelConfig(serdes=..., item_serdes=...). TheBatchResultgoes through an adapter over itsto_dict(). Sub-agents with differentserdesrun in separateparalleloperations. Sub-agents without durability stay out of branches and run as before. A suspension (SuspendExecution) in a branch goes through the SDK's own branch handling and leaves through the handler as before.
New public surface
none
User-visible behavior
dynamic_workflow/_toolset.py :: DynamicWorkflowToolset._run_one()
+├─ DBOS-durable sub-agent, in workflow code
+│ └─ DBOS.reserve_step() in dispatch order -> reservation.run_async('run_workflow.<agent>', run)
+├─ Lambda-durable sub-agent, in a durable handler
+│ └─ joins the batch -> MontyExecutor(flush=...) at the script's next wait
+│ └─ StepBridge.run_parallel -> context.parallel(branches in dispatch order, name='run_workflow')
+│ └─ per branch: child context + own StepBridge on the SDK's branch thread
└─ otherwise: run the sub-agent as before (concurrently)
Verification
tests/harness/dynamic_workflow/test_dbos.py: alpha's model blocks until beta finishes (asyncio.wait_for, no sleep), so the sub-agents have to run concurrently, and alpha, dispatched first, finishes last. The test checks that therun_workflow.summarizesteps are numbered alpha then beta with their own outputs. It then crashes the workflow (leftPENDING) and resumes it: the result is correct and no sub-agent model is called again.tests/harness/aws_lambda/test_aws_lambda_dynamic_workflow.pyruns the real SDK's@durable_executionhandler against an in-memory durable-execution service (DurableExecutionInvocationInputWithClient), so branch IDs and replay are the SDK's own, not a fake's. It covers:- With and without a durable orchestrator, using the same concurrency-forcing model: there is one
run_workflowparallel operation with one branch per sub-agent, each holding its own steps. A second invocation replays everything without calling a model. The script starts withawait asyncio.sleep(0), so a wait with no sub-agents pending starts noparalleloperation. - Crash recovery: after a full run, the test rewrites the checkpoints into those a process that died during alpha's last model request would leave. Alpha's branch and the
paralleloperation go back toSTARTED, and that request and everything after the operation are dropped. On re-invocation beta's branch replays entirely, alpha replays up to the lost request, and only that request runs again (calls[4:] == ['alpha 3']). Raising an exception to simulate the crash isn't portable: SDK 1.7.0's coordinator never completes when a branch raises aBaseExceptionthat isn't one of its own suspensions. - A sub-agent failure is recorded in its branch and replays (
retry_strategy=RetryPresets.none()). - With a sealing
serdesinstep_config, no stored payload contains a sub-agent's output in plaintext, and the run still replays. Before the fix, the batch result and each branch result were stored in plaintext. - Sub-agents without durability create no
paralleloperation.
- With and without a durable orchestrator, using the same concurrency-forcing model: there is one
- Without the Lambda branches (dispatch against the root context, as on
main) the Lambda tests don't pass: they hang until killed. I confirmed with the old code path that one sub-agent's model step holds the bridge's request lock while the other waits on it. tests/harness/aws_lambdaandtests/harness/dynamic_workflow: 238 passed with SDK 3.0.1.tests/harness/aws_lambdaalso passes with the minimum supported SDK, 1.7.0 (106 passed)._bridge.pyand_toolset.pyhave 100% line and branch coverage locally.ruff check,ruff format, andpyrightare clean on the touched files.tests/harness/code_mode/test_temporal.pywas flaky twice under-n 6load, but passes alone and together with the new tests. Code Mode never setsflush.
What changes for existing users
- DBOS: gathered sub-agents still run concurrently, and recovery now gives each call its own result. Each call is one DBOS step, so the sub-agent's own model requests and tool calls are no longer checkpointed one by one inside it. That includes
@DBOS.steptools, which run as plain calls with no role checks. If a call hadn't finished when the workflow crashed, recovery runs it again from the start. Withforward_usage, a replayed call's usage isn't added to the run's usage again. - AWS Lambda: gathered sub-agents run concurrently, as on
main, and recovery now gives each call its own checkpoints. Each sub-agent keeps per-step checkpoints inside its branch. The execution history gains arun_workflowparalleloperation with aparallel-branch-Nchild context per call. Recording a sub-agent's steps under a branch changes the step layout, so executions that were already in flight when this deploys won't replay. That's the same rule the Lambda docs give for any change to a run's shape. - Every other engine, and runs outside durable execution, behave as on
main.
PR decisions
- First rework, after Mike's review: the original version ran sub-agents one at a time under DBOS and Lambda. DBOS now reserves a step per call in dispatch order.
- Second rework, after Mike's follow-up: Lambda uses
context.parallelinstead of running one at a time. I pickedparallelover arun_in_child_contextper call.run_in_child_contextblocks its caller until the child finishes, so concurrent children would need their own threads. Their IDs would then be drawn from the parent's counter in thread-start order, and I would have to re-create the SDK's branch coordination, including suspension aggregation.parallelderives branch IDs from the index, starts branches in index order, and already handles a suspended branch. - Batches end at the script's waits, through a
MontyExecutor.flushhook. Waits are deterministic in Monty, and by then every dispatched call has joined, in dispatch order. Batching inside_run_onealone would split agatheracross event-loop iterations, which isn't deterministic. - DBOS uses a reserved step per call, not a child workflow. A child workflow would keep inner checkpoints, but it would need
deps,usageand the inherited model as serializable inputs registered beforeDBOS.launch(). That would break DBOS users whosedepscan't be pickled. - Known DBOS tradeoff (from a review comment): inside the recording step, nested
@DBOS.stepfunctions run as plain calls. That means no inner checkpoints and no DBOS role checks. This is documented. Lambda has no equivalent, because branches keep real child contexts. - Cancelling the orchestrator while a
paralleloperation is in flight doesn't cancel its branches (review thread). The handler can't leaveparalleluntil the branches finish anyway. Cancelling them would make the SDK record their in-flight steps as failed, and on SDK 1.7.0 aCancelledErrorescaping a branch would leave the coordinator waiting forever. Letting them finish keeps their checkpoints for the next invocation. - Known Lambda limitation: on SDK 1.7.0, a non-SDK
BaseExceptionin a branch, such as the bridge's own "should not happen"AgentLoopGone, would leave the SDK'sparallelcoordinator waiting. Ordinary exceptions and suspensions are handled, and SDK 3.x handles this case too. DurableStepContextstill declares onlystep, so existing stand-ins keep type-checking.run_parallelreadsparallelthrough a private_DurableParallelContextprotocol, which the realDurableContextsatisfies.- The removed
global_sequentialkeying (sequential_tools_in_durable_context) is no longer needed: no engine runs DynamicWorkflow sub-agents one at a time. Ordinary tool calls under Lambda still run one at a time. - Merged the latest
origin/maininto the branch.mainhad added replay telemetry (record_durable_unit,replay_scope) to the bridge. Recording moved into the step-only_checkpoint, so theparallelrequest is not counted as a durable unit, and branch steps credit the run's tally through the context they copy.
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
- PR title is fit for the release changelog.