Carry `ctx.enqueue()` and `ctx.emit()` calls made inside a durable unit in its recorded result, so replays re-apply them

Merged
DO
11h ago
+1971-269

Written by Claude Code on behalf of @DouweM.

Closes #7971

Why. ctx.enqueue() and ctx.emit() inside a durable unit weren't part of the unit's recorded result. So enqueue was refused on every engine, emit raised on Temporal and was lost on DBOS/Prefect replay, and a durable before_model_request that enqueued lost the message on replay (#15338). Per the maintainer's ruling A, the unit's recorded result now carries them, and the container queues and emits them when it gets the result. It does this on the first run and on every replay alike, so replays are deterministic. The carrier lives in the durable base, so every engine built on BaseDurabilityCapability gets it: Temporal, DBOS, Prefect, AWS Lambda, Azure Durable Task, Render, Absurd and pgtask.

New public surface: none. There's a private side_effects field on the recorded tool-call and capability-operation results. It's excluded when empty and is compare=False.

User-visible behavior

 @agent.tool  # under TemporalDurability / DBOSDurability / PrefectDurability / ...
 async def sync_files(ctx: RunContext, count: int) -> str:
-    await ctx.emit(SyncProgress(done=count))  # Temporal: UserError; DBOS/Prefect: live, lost on replay
-    ctx.enqueue('Summarize the diff.')         # every engine: UserError
+    await ctx.emit(SyncProgress(done=count))  # DBOS/Prefect: live as before, re-emitted on replay; Temporal: on completion
+    ctx.enqueue('Summarize the diff.')         # queued next to the tool's result, on every replay too
  • Units that carry: tool calls and validate_args for function, dynamic and MCP tools, DBOS function-tool child workflows, and @durable_operation capability methods.
  • Model-request hooks: they now get the guarded context, the same one-line change as #15343, so their enqueue is recorded instead of going straight to the live queue.
  • Order: messages first, then events, in the order they were made, before the result is unwrapped. Parallel tool calls' carried messages queue in tool-call order, not completion order.
  • Late calls are refused: a task the unit body started without awaiting can't add to the recorded result after the body returns; it gets the standard UserError, as on main.
  • Live on the first run: when the unit's body runs in the container's process (DBOS, Prefect, in-process harness engines), emit delivers live as before and records. The container skips re-emitting the events of an execution it saw run here, identified by a per-execution id that a process-local context variable around the call collects. A replay, cache hit or remote unit (Temporal) emits the recorded events.
  • Events are checked where they're emitted: in the unit for in-process engines, and in the container for contexts rebuilt elsewhere.
  • Only the unit's own guarded context records. A sub-agent run inside a tool keeps its events.

Verification

New tests are in tests/durable_exec/test_durable_unit_side_effects.py. They run on an in-process JSON-codec journal engine that replays recorded payloads without running the bodies.

  • First run vs replay: history and event stream are identical, and the tool body ran once.
  • Crash after the tool unit, then recovery: the enqueued message appears exactly once.
  • A durable before_model_request enqueue is recorded, replayed and matches a plain run.
  • A sub-agent inside a carried unit keeps its own events.
  • A misattributed event fails inside the unit.
  • An old payload loads unchanged.
  • Temporal's payload converter round-trips the carrier.

All 12 pass in-process, including a liveness test where the tool waits for the stream consumer to see its event (it times out on the previous head); forcing the container to re-emit makes the first-run exactly-once checks fail. Real DBOS (sqlite) and an ephemeral Prefect server deliver a tool event once, live, on the first run. On main the three behavioral tests fail: UserError (enqueue refused), and the message is lost on replay. The sub-agent and misattribution tests fail on this branch's first commit.

Existing tests that pinned the refusal are flipped (Temporal, DBOS, Prefect, AWS Lambda, Azure Durable Task, Render). There's a new Temporal Replayer test, test_temporal_tool_enqueue_and_emit_are_reapplied_on_replay. Temporal workflow tests skip locally on Python 3.15, and DBOS/Prefect need their backends, so CI is the first run for those. ruff is clean, the contract manifest is regenerated, and the API check reports nothing new against v2.77.0.

What changes for existing users

  • First run unchanged. On DBOS, Prefect and the in-process harness engines, events emitted inside a tool or durable operation are still delivered live, once. Replays and cache hits now re-emit the recorded events, where they used to be lost. On Temporal and other remote units, tool events used to raise; they now arrive when the activity completes.
  • At-least-once edge, unchanged: a crash after a live emit but before the unit's result is recorded re-runs the body, so that event can be delivered twice, as before.
  • In-flight workflows replay unchanged. Old recordings load with no side effects. Before this change these units either raised on enqueue (and on emit under Temporal), or their events were already missing on replay. So no in-flight history holds a recorded effect, and no compatibility impact label.
  • Finish rolling upgrades first. During a mixed-version rollout, an old container worker ignores the new field and drops what a new worker's unit carried. Finish the rollout before relying on tool enqueue/emit.

Follow-ups, not in this PR:

  • Carry side effects for event-stream-handler, model-request, discovery and workspace units, which still raise on enqueue.
  • request_compaction() / cancel() inside units.
  • dequeue / set_enqueue_priority on a unit's own messages.
  • Inbox for external events: #15395.

#15343: this branch contains the same run_context=durable_ctx line. Whichever lands second needs a trivial rebase, and #15343's rejects_enqueue test then becomes "records".

PR decisions
  • Ruling A (Douwe, 2026-11-30): carry enqueue/emit in the unit's recorded result, and file the inbox follow-up (#15395).
  • Pre-push review, call 1 of 3, at 68e78549e9 (tree f13f88351f, full branch vs merge base ffd953b3b2): a fresh read-only reviewer worked from an origin/main policy base. It found 3 blocking and 4 non-blocking issues, all remediated in 2914b6f2d2:
    • Recording is now scoped to the unit's own guarded context, so sub-agent events aren't captured.
    • Events are checked and attributed where they're emitted, and published as-is by the container.
    • Docs now say exactly which units carry side effects, including the failure and deprecated-wrapper cases.
    • The rollout note and the #15343 overlap are stated in this body.
    • The loss of live delivery is called out above, per ruling A (superseded below).
  • Independent durable review at bffdb1c6b9 (changes needed), fixed in 3cf4c38fba:
    • A late enqueue (or emit on a rebuilt context) from a task the unit body started without awaiting was silently dropped. The recording now closes when the body returns, and a late call falls back to the standard refusal.
    • Parallel tool calls' carried messages are now queued in tool-call order from the model response (PendingMessageQueue.append_in_call_order), not completion order, so the first run and a replay queue them identically.
    • Regression tests cover a spawned task, a rebuilt context, and two parallel tools finishing in reverse order. All three fail on bffdb1c6b9.
  • Pre-push review, call 3 of 3, at 3cf4c38fba (tree 89b639a694, delta from bffdb1c6b9): current at 3cf4c38fbac3ce617600b1244e05a4cab5f39580, no findings.
  • 2026-11-30 18:18 CST — coverage, test-only, no pre-push review (budget of 3 used): covered the two uncovered library lines with tests and removed a dead branch in a test. The lines are the closed-queue refusal in PendingMessageQueue.append_in_call_order and the no-position fallback of _tool_call_order, reached by a tool call the history doesn't hold, such as a nested CodeMode call. The dead branch was the if in the durable before_model_request test hook, whose run makes one request. No library code changed.
  • Live events ruling (Douwe, durable owner): don't regress first-run liveness on in-process engines; deliver live and record, skip re-emitting events from a body that ran here, emit recorded events otherwise. Implemented in e1fe9da267.
  • Pre-push review, call 2 of 3, at e1fe9da267 (tree e628cbd154, delta from f6a22c1cce): 3 findings, all fixed in bffdb1c6b9: the overview's failure bullet now covers events already delivered live, the UnitSideEffects docstring is updated, and execution_id is compare=False. It confirmed both call 1 fixes still hold.
  • CI fix at c52e2941b7 (2026-11-30 17:47 CST), pushed without a pre-push review because the budget is spent (3 of 3): merged origin/main (GitHub reported DIRTY; import/doc conflicts only). Durable library code changed: recording_unit_side_effects now restores _UNIT_RECORDING with set(previous) instead of reset(token), because a cancelled Temporal tool-call child workflow closes the body's coroutine in another Context (ValueError: ... created in a different Context in test_parent_cancellation_reaches_child_without_livelock[try-cancel]), the same pattern _instrumentation.py uses. Tests: the two Temporal emit tests rebuild the context with deserialize_run_context (as a worker does, so it has the EnqueueGuard that recording now requires); pyright fixes in the new tests; reverted unrelated import reflows in models/test.py, providers/deepseek.py and providers/vllm.py. Needs a new independent durable marker.

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.