Keep `DynamicWorkflow` sub-agents parallel under `DBOSDurability` and `AWSLambdaDurability` with dispatch-ordered durable IDs

Merged
MP
23d ago
+743-46

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.parallel is 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 the run_workflow tool call (which runs alone), so no other root step is needed.
  • The SDK already calls step() from branch worker threads: DurableContext uses a locked counter and per-context replay state, and ConcurrentExecutor runs each branch on a ThreadPoolExecutor worker. The new _run_branch gives each branch its own StepBridge on that worker. The sub-agent runs on the agent loop with that bridge in its _active_bridge context var.
  • Branch membership has to be deterministic, and parallel needs all branches up front. So MontyExecutor gets a flush hook, awaited when the script reaches a wait (a FutureSnapshot), 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 later parallel operation.
  • A sub-agent failure is returned as data from its branch ({'error': ...}), so one failed call doesn't fail the batch's all_successful completion.
  • Branch results and the aggregate BatchResult are checkpointed with the serdes from the sub-agent's AWSLambdaDurability(step_config=...), through ParallelConfig(serdes=..., item_serdes=...). The BatchResult goes through an adapter over its to_dict(). Sub-agents with different serdes run in separate parallel operations. 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 the run_workflow.summarize steps are numbered alpha then beta with their own outputs. It then crashes the workflow (left PENDING) and resumes it: the result is correct and no sub-agent model is called again.
  • tests/harness/aws_lambda/test_aws_lambda_dynamic_workflow.py runs the real SDK's @durable_execution handler 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_workflow parallel operation with one branch per sub-agent, each holding its own steps. A second invocation replays everything without calling a model. The script starts with await asyncio.sleep(0), so a wait with no sub-agents pending starts no parallel operation.
    • 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 parallel operation go back to STARTED, 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 a BaseException that 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 serdes in step_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 parallel operation.
  • 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_lambda and tests/harness/dynamic_workflow: 238 passed with SDK 3.0.1. tests/harness/aws_lambda also passes with the minimum supported SDK, 1.7.0 (106 passed). _bridge.py and _toolset.py have 100% line and branch coverage locally. ruff check, ruff format, and pyright are clean on the touched files. tests/harness/code_mode/test_temporal.py was flaky twice under -n 6 load, but passes alone and together with the new tests. Code Mode never sets flush.

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.step tools, 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. With forward_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 a run_workflow parallel operation with a parallel-branch-N child 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.parallel instead of running one at a time. I picked parallel over a run_in_child_context per call. run_in_child_context blocks 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. parallel derives 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.flush hook. Waits are deterministic in Monty, and by then every dispatched call has joined, in dispatch order. Batching inside _run_one alone would split a gather across 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, usage and the inherited model as serializable inputs registered before DBOS.launch(). That would break DBOS users whose deps can't be pickled.
  • Known DBOS tradeoff (from a review comment): inside the recording step, nested @DBOS.step functions 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 parallel operation is in flight doesn't cancel its branches (review thread). The handler can't leave parallel until the branches finish anyway. Cancelling them would make the SDK record their in-flight steps as failed, and on SDK 1.7.0 a CancelledError escaping 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 BaseException in a branch, such as the bridge's own "should not happen" AgentLoopGone, would leave the SDK's parallel coordinator waiting. Ordinary exceptions and suspensions are handled, and SDK 3.x handles this case too.
  • DurableStepContext still declares only step, so existing stand-ins keep type-checking. run_parallel reads parallel through a private _DurableParallelContext protocol, which the real DurableContext satisfies.
  • The removed global_sequential keying (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/main into the branch. main had added replay telemetry (record_durable_unit, replay_scope) to the bridge. Recording moved into the step-only _checkpoint, so the parallel request 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.