Repository navigation
Breaking: deliver OpenAI Agents Nexus tool cancellation before the workflow closes - #226
Conversation
…oses
When a workflow running an agent was cancelled while a
nexus_operation_as_tool call was in flight, the Agents SDK cancelled the
tool task and raised at once. The workflow closed in the same workflow
task that recorded the operation's cancel request, so the request was
never delivered: the operation kept running and finished its work,
although the tool uses the default WAIT_COMPLETED cancellation type.
The tool now starts the operation with start_operation and tracks it
while it waits. When Runner.run is cancelled, the runner waits for the
tracked operations to resolve before it re-raises, so the cancel request
is delivered, as when workflow code calls execute_operation itself. An
agent run as a tool adds its operations to the outer run too.
The wait is behind workflow.patched("openai_agents.wait-for-nexus-tool-cancel"),
asked only when a cancelled run has operations in flight. Runs that were
cancelled before this change closed at once and replay unchanged.
The cancelled runner waited for its tool operations with one asyncio.wait. If Workflow code cancels its Runner.run task and the Workflow is then cancelled while an operation finishes its own cancellation, the second CancelledError ended that wait. The Workflow closed with the operation still running, while a direct execute_operation call keeps waiting. Keep waiting through further cancel requests until every tracked operation is done, then re-raise the run's cancellation. The gate is unchanged. test_nexus_tool_cancel_workflow also runs with cancel_run_first: the Workflow cancels its run, the operation delays its cancellation until released, and the test cancels the Workflow once the cancel request is delivered.
…gate Fixes add no version gates for now, so remove the `openai_agents.wait-for-nexus-tool-cancel` patch and the replay test History that only checked it. A cancelled run now waits for its tools' Nexus operations in every run. Breaking change: a run cancelled before this version while a Nexus tool operation was in flight closed in the Workflow Task that recorded the cancel request. On replay it now waits for the operation and fails with a non-determinism error. Let those runs finish before you upgrade, or use Worker Versioning.
DABH
left a comment
There was a problem hiding this comment.
Review at head 3f3d16f (four commits over c664a34). On a worktree at the head, make lint is clean and make test passes 385; with the PR merged into current main (4bcde9a), lint is clean and 428 pass. The three new cases fail on main with only the test applied (workflow: RUNNING == CANCELED; run_during_start: FAILED == RUNNING; run_first: the cancel request is never delivered) and pass on the head. Replay: six histories recorded on main from an agent whose only tool is nexus_operation_as_tool, replayed with Replayer(plugins=[OpenAIAgentsPlugin()]) on the head, on the merge result and on the gated first commit 88723d9. Other probes: a nested agent-as-tool run, a mutation of the tracking loop, a double cancellation during the start against a direct execute_operation control, a parallel tool failing while the operation runs (head and main), error-level logging on Python 3.14, trial fixes for three of the items below, and the TypeScript sibling on main. Probed and found sound: eviction with max_cached_workflows=0 (no failed Workflow Tasks; the handle's cancel hits _add_command during eviction and the tracked future resolves); asyncio.timeout and wait_for around Runner.run (TimeoutError after the wait, operation CANCELED, and an outer cancel still wins because the suppressed cancels stay counted); two runs in asyncio.gather and an inline run in the main task; the unsandboxed runner (temporalio is a sandbox passthrough, so the runner and the tool share one ContextVar); the ContextVar set/reset placement; no import cycle between workflow.py and _openai_runner; and no timing sensitivity in the new cases, since the -slow Workflow and the withheld acknowledgement gate every RUNNING check. Not verified: the #225 reproduction script itself (the new workflow case covers the same path) and the 1.34.x backport question.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Where the problems cluster: the fix does what #225 asks for in Runner.run, and the path without cancellation schedules the same commands as before (runs recorded on main that are waiting on their operation or that completed replay cleanly). What needs work is around the edges of the new wait: the breaking-change disclosure says the runs that stop replaying are closed when some are still open and fail on upgrade; the same close-before-delivery happens when a parallel tool fails, a path the wait does not cover; one parity claim with execute_operation does not hold during the start; the wait is always WAIT_COMPLETED and, on Python 3.14, now logs an ERROR per cancelled run; and the nested-run path has no test.
Decision: COMMENT, because the P2 introduced here is an inaccurate replay disclosure (or a gate to restore) rather than a code defect, the other P2 is already on main, and the author should settle the disclosure before merge.
PR body: 'breaking old histories is accepted with the plugins' 1.0 releases' does not fit this plugin: PyPI already has temporalio-openai-agents 1.0.0 and 1.1.0 (#225 is filed against 1.1.0), so this break ships in the next major. The body still says 'Draft while the breaking change and these questions are open', but the PR is not marked draft. At this head the body's own replay statements hold for the cases it lists (the closed cancelled run fails; runs not yet cancelled replay).
Cross-language: the TypeScript sibling on main already delivers the cancel. A local probe that cancels a Workflow running nexusOperationAsTool after the operation started recorded NEXUS_OPERATION_CANCEL_REQUESTED, NEXUS_OPERATION_CANCEL_REQUEST_COMPLETED and NEXUS_OPERATION_CANCELED, and the backing Workflow ended cancelled, because agents-core awaits the tool promise, which settles only once the operation has ended. So this PR brings Python in line on delivery. One difference remains outside this PR: the TypeScript agent Workflow then closes FAILED (Agent workflow failed: Failed to run function tools: NexusOperationFailure ...), while a TypeScript direct call and this PR's Python run close CANCELED. agents-core 0.14.3's ToolCallError keeps the tool error in .error with no cause, and unwrapTemporalFailure (
ai-integrations/typescript/openai-agents/src/common/errors.ts
Lines 7 to 23 in 4bcde9a
cause and AggregateError.errors, so the cancellation is wrapped as AgentsWorkflowError. Worth a TypeScript issue.
| **kwargs, | ||
| ) | ||
| except asyncio.CancelledError: | ||
| await _wait_for_tool_operations(operations) |
There was a problem hiding this comment.
P2: the breaking-change note says the runs that stop replaying are closed, but a run that catches the Workflow's cancellation around Runner.run and keeps going is still open at the upgrade, and its next Workflow Task on this head fails with TMPRL1100. I recorded six histories on main (4bcde9a) with an agent whose only tool is nexus_operation_as_tool over a Workflow-backed operation and replayed them with Replayer(..., plugins=[OpenAIAgentsPlugin()]) on this head and on the PR merged into main. A Workflow cancelled while the operation ran whose code catches the cancellation and runs a cleanup step (except asyncio.CancelledError: await workflow.sleep(timedelta(hours=1)); raise), still RUNNING on main, fails with [TMPRL1100] Nondeterminism error: No command scheduled for event HistoryEvent(id: 21, TimerStarted). A Workflow whose code cancels its run task on a Signal and continues the same way, the case the body marks 'not checked', fails the same way. The disclosed case, closed CANCELED, fails with No command scheduled for event HistoryEvent(id: 21, WorkflowExecutionCanceled), as the body says. A run waiting on its operation, a run whose operation completed, and a run cancelled while the start was pending (closed at once on both builds) replay cleanly. On main the two open runs stay open and their cancel request is then delivered (TIMER_STARTED, NEXUS_OPERATION_CANCEL_REQUEST_COMPLETED, NEXUS_OPERATION_CANCELED), so the first Workflow Task after the deploy (that NEXUS_OPERATION_CANCELED, the timer, or a cleanup Activity) replays them on the new build and fails them until they are reset or moved back to the old build. Catching asyncio.CancelledError to run cleanup is a common Workflow pattern, so these are the affected runs most likely to be in flight at a deploy. All six histories replay on 88723d9, and also on this head with its gate put back as one line in _wait_for_tool_operations (if operations and workflow.patched("openai_agents.wait-for-nexus-tool-cancel"):), where the three new cases still pass. Fix: restore that gate, or correct the Breaking change and Upgrade paragraphs to say that runs cancelled on an earlier version while a Nexus tool operation ran, whose code then caught the cancellation or that cancelled their own run and kept going, are still open and fail on upgrade, so they must finish first or stay on the old build with Worker Versioning. Release notes are generated from commit subjects, so the release draft needs that sentence added by hand.
There was a problem hiding this comment.
Thanks for recording those. We're keeping the gate out: we aren't adding version gates to these fixes, and since 1.0.0 and 1.1.0 are out, this break needs the next major, 2.0.0.
I rewrote the Breaking change and Upgrade notes in the description. Open runs whose code caught the cancellation, or cancelled their own run, and kept going fail on their next Workflow Task, so they must finish first or stay on the old build with Worker Versioning. The notes also cover runs that failed because another tool failed, since e981e6f waits there too (see the parallel-tool thread), and say the release draft needs the note added by hand.
Replayed on e981e6f with Histories recorded on main: the closed cancelled runs fail with WorkflowExecutionCanceled, an open run that caught its first run's cancellation fails with ActivityTaskScheduled, and a run that failed because a second tool failed fails with WorkflowExecutionFailed. Runs that were never stopped replay.
| if operations: | ||
| pending = list(operations) | ||
| while not all(operation.done() for operation in pending): | ||
| with contextlib.suppress(asyncio.CancelledError): |
There was a problem hiding this comment.
P3: 'keeps waiting ... as a direct execute_operation call does' holds once the operation has started, but not while it is starting: there a direct call ends on the Workflow's cancellation and the agent run does not. Probe with the start's acknowledgement withheld; Workflow code cancels its task, then the client cancels the Workflow. A direct execute_operation task is RUNNING after the task cancel and CANCELED right after the Workflow cancel, with the backing Workflow left RUNNING. The agent run on this head is RUNNING after both, ends CANCELED only once the start is acknowledged, and the backing Workflow ends CANCELED. The second cancellation stops at this suppress: the tool task, which the Agents SDK has already let go, is never cancelled again, so the SDK's rule that a Workflow cancellation ends a pending start (reraise_on_workflow_cancellation=True in _outbound_start_nexus_operation) never applies. The agent behaviour is arguably the better one, since the operation does get cancelled, but while a start is pending (for example, the handler's Worker is down) a Workflow cancellation no longer closes the run. Either say so in the docstring and the PR body, or record asyncio.current_task() in _track_tool_operation and cancel those tasks again when a further CancelledError lands here. I tried the second (a dict from each done future to its task, re-cancelled in an except asyncio.CancelledError that replaces the suppress): the agent run then matches the direct call in this probe, and the three new cases still pass, because once the operation has started the extra cancel reaches the SDK's handle task, which keeps waiting. The comment at workflow.py:302-304 ('a cancelled task keeps waiting for the start to resolve') likewise holds for a task cancellation only.
There was a problem hiding this comment.
Agreed, done in e981e6f the way you tried it: each tracked operation keeps its tool's task, and a further CancelledError during the wait cancels those tasks again instead of being suppressed. A Workflow cancellation now ends a pending start as it does for a direct call, and a started operation keeps waiting (run_first still passes).
New case workflow_during_start: the Workflow cancels its run during a withheld start, then the test cancels the Workflow. It closes CANCELED and the operation's Workflow is still RUNNING, as with a direct call. With the old suppress, it times out instead. The comment in workflow.py now says a cancelled start keeps waiting unless the Workflow itself is cancelled.
| except asyncio.CancelledError: | ||
| await _wait_for_tool_operations(operations) | ||
| raise | ||
| except AgentsException as e: |
There was a problem hiding this comment.
P2 (non-blocking, already on main): a parallel tool that fails while a Nexus tool operation is in flight still closes the Workflow before the operation's cancel request is delivered, which is #225 with a different trigger. When a sibling fails, the Agents SDK cancels the remaining tool tasks, drains them for at most 0.25 s and raises the failure (_raise_failure_after_draining_siblings in agents/run_internal/tool_execution.py), so this branch runs and the CancelledError one does not. Probe: one model response with two calls, hold and an activity_as_tool whose activity raises ApplicationError(non_retryable=True) once the operation has started. Head and main give the same result: the caller fails with AgentsWorkflowError: ... Error running tool rv_probe_fail: Activity task failed, the history ends NEXUS_OPERATION_CANCEL_REQUESTED, WORKFLOW_EXECUTION_FAILED, and the backing Workflow is still RUNNING 3 s later. Adding await _wait_for_tool_operations(operations) at the top of this branch fixes the probe: the caller fails with the same error after NEXUS_OPERATION_CANCELED, the backing Workflow ends CANCELED, and test_nexus_tool_workflow and the three new cases still pass. It carries the same replay caveat for runs that failed this way. Either include it here or list it under 'Not covered' with a follow-up issue.
There was a problem hiding this comment.
Included in e981e6f: the AgentsException branch now waits for the tracked operations first.
New case tool_fails: a second tool fails once the operation has started. The Workflow fails with that tool's error after NEXUS_OPERATION_CANCELED, and the operation's Workflow ends CANCELED. Without the wait, the operation's Workflow stays RUNNING. The description's replay note now lists runs that failed this way: a History recorded on main for this case fails on e981e6f with No command scheduled for event HistoryEvent(id: 21, WorkflowExecutionFailed).
| arg, | ||
| schedule_to_close_timeout=schedule_to_close_timeout, | ||
| ) | ||
| result = await handle |
There was a problem hiding this comment.
P3: on Python 3.14, the top of the CI matrix, a plain Workflow cancellation with a Nexus tool operation in flight now logs NexusOperationError exception in shielded future at ERROR with a traceback. The Agents SDK awaits each tool's task through asyncio.shield(invoke_task), and the 3.14 shield reports an inner task that fails after the outer was cancelled (_log_on_exception, absent from 3.10 to 3.13); the Workflow instance's exception handler logs it unless the run is being evicted. On main the tool task outlived a Workflow that closed at once, so the plain-cancel probe logs nothing; on this head it logs once per run, and make test PYTEST_ARGS="-n 0 -o log_cli=true --log-cli-level=ERROR tests/test_openai.py -k test_nexus_tool_cancel_workflow" shows three entries, one per new case. Main already logs it for runs that stay open after the cancellation (the cleanup and run-cancel probes). An ERROR with a traceback for an expected cancellation trips log-based alerting. _log_on_exception skips cancelled futures, so ending the tool's task as cancelled in this situation avoids it, for example by having the runner mark its tracked operations when it catches the cancellation and having run_operation re-raise asyncio.CancelledError from a NexusOperationError whose cause is a cancellation for a marked operation; otherwise mention the log in the docstring.
There was a problem hiding this comment.
Fixed in e981e6f along the lines you suggested. When the runner starts waiting after a cancellation or a failure, it marks its tracked operations, and the tool turns a NexusOperationError caused by a cancellation into asyncio.CancelledError for a marked operation.
Every case of test_nexus_tool_cancel_workflow now checks that no ERROR is logged. Without the change, on Python 3.14 that check fails in workflow, run_first, nested and tool_fails with NexusOperationError exception in shielded future. In tool_fails the Agents SDK also logged Background function tool task raised during cancellation cleanup after failure propagation., which the same change removes.
| # delivers the operation's cancel request before the Workflow closes. Tracking starts | ||
| # before the start request: a cancelled task keeps waiting for the start to resolve. | ||
| with _track_tool_operation(): | ||
| handle = await nexus_client.start_operation( |
There was a problem hiding this comment.
P3 (design): the tool now always cancels with WAIT_COMPLETED, and neither its signature nor its docstring says so. Before this PR a cancelled agent Workflow closed at once; now it closes only after every Nexus tool operation has ended. The SDK documents that a WAIT_COMPLETED operation 'may not complete as cancelled', so a handler that catches the cancellation and finishes its work, or one that is slow or unreachable, keeps the agent Workflow open until the operation ends or its schedule_to_close_timeout (None by default here) fires; the run_first case already shows the agent Workflow RUNNING after a Workflow cancel while the operation delays. Cleanup that Workflow code runs after catching the cancellation is delayed the same way: recorded on this head, the cleanup timer from the replay probe starts only after NEXUS_OPERATION_CANCELED. activity_as_tool exposes cancellation_type; this tool has no equivalent. Suggest a cancellation_type: NexusOperationCancellationType = NexusOperationCancellationType.WAIT_COMPLETED parameter passed to start_operation (per the SDK's documented semantics, WAIT_REQUESTED resolves the handle once the cancel request is acknowledged, so the runner's wait would still deliver it without waiting for the operation to end), and a docstring sentence saying that cancelling the run waits for its Nexus tool operations before the Workflow closes.
There was a problem hiding this comment.
Added in e981e6f: cancellation_type: NexusOperationCancellationType = NexusOperationCancellationType.WAIT_COMPLETED, passed to start_operation. The docstring now says that when the run is cancelled, or stops because another tool failed, it cancels the operation and waits as cancellation_type says, so with the default the Workflow closes only after the operation has ended.
New case wait_requested: with WAIT_REQUESTED and an operation that delays its cancellation, the Workflow closes CANCELED after NEXUS_OPERATION_CANCEL_REQUEST_COMPLETED, while the operation's Workflow is still RUNNING.
| """Keep a tool's Nexus operation pending in the runs until the block exits.""" | ||
| runs = _tool_operations.get() | ||
| done: asyncio.Future[None] = asyncio.get_running_loop().create_future() | ||
| for operations in runs: |
There was a problem hiding this comment.
P3 (tests): nothing tests the nested case, which is the reason a tool adds its future to every enclosing run's set. Mutation for operations in runs[-1:]: (innermost run only) leaves all 385 tests green, the three new cases included. Probe: an outer agent whose only tool is inner.as_tool(tool_name='inner', ...), the inner agent holding the nexus_operation_as_tool tool, Workflow cancelled once the operation started. On this head the caller records NEXUS_OPERATION_CANCEL_REQUEST_COMPLETED and NEXUS_OPERATION_CANCELED and the backing Workflow ends CANCELED; under the mutation the events stop at NEXUS_OPERATION_CANCEL_REQUESTED and the backing Workflow stays RUNNING, because the outer Agents SDK lets go of the cancelled agent-tool task and the outer runner's set is empty. A fourth case in test_nexus_tool_cancel_workflow with that agent pair and TestModel responses [tool_call('{"input": "go"}', 'inner'), tool_call(held_id, 'hold')] covers it.
There was a problem hiding this comment.
Added a nested case in e981e6f with your agent pair and responses. Under your runs[-1:] mutation it fails with the operation's Workflow still RUNNING; it passes on the head.
- A further cancel request during the wait goes to the tools' tasks again, so a Workflow cancellation ends a start that is still pending, as it does for a direct execute_operation call. - The runner also waits when a tool fails and the Agents SDK cancels the run's other tools. - After the run stopped, a tool whose operation ends as cancelled ends its task as cancelled instead of raising NexusOperationError, so neither asyncio (Python 3.14) nor the Agents SDK logs an ERROR for it. - nexus_operation_as_tool takes a cancellation_type option, passed to start_operation, defaulting to WAIT_COMPLETED. - test_nexus_tool_cancel_workflow gets workflow_during_start, nested, tool_fails and wait_requested cases, and every case checks that no ERROR is logged.
|
Thanks for the review. The changes are in
|
Resolve the conflict with #232 in TemporalOpenAIRunner.run: keep the Nexus tool operation tracking and enter _inline_sync_function_tools() in the same with statement.
DABH
left a comment
There was a problem hiding this comment.
Second round, at head 122303f (e981e6f plus a merge of main at 88745dc). On a worktree at the head, make lint is clean and make test passes 452 on Python 3.14; on a local merge with current main (61fe33a) lint is clean and 454 pass; CI is green, including Python 3.10. Replay: nine histories recorded on current main from agents whose only Nexus work is nexus_operation_as_tool, replayed on the head with Replayer(..., plugins=[OpenAIAgentsPlugin()]), plus six head-recorded histories of the new paths (Workflow cancel; run cancel then Workflow cancel while the operation delays its cancellation; the same with two operations in one turn; sibling failure; nested; run cancel then Workflow cancel during a withheld start), each replayed on the head five times in separate processes. Each new clause was mutated against test_nexus_tool_cancel_workflow. Probes, run on the head and, where it applies, on main: the seven cases with max_cached_workflows=0; a streamed run; two run cancellations during a withheld start; a Workflow cancellation during the wait after a tool failure; a tool raising a non-Temporal error beside a running operation, with a fix-forward replay; an agent run started in a task that a tool spawned; an operation cancelled by a client of its handler while the run is live; asyncio.timeout around Runner.run; trial fixes for the first two P2s below; and the TypeScript sibling's code on main. Probed and found sound: a further cancel during the wait records no second NEXUS_OPERATION_CANCEL_REQUESTED (one per operation in every history, including two operations cancelled twice), so the re-cancel loop's set order never reaches History; the head-recorded histories replay deterministically; eviction after every Workflow Task leaves no tasks behind and logs no ERROR; asyncio.timeout still ends in TimeoutError with cancelling() back at 0, and a Workflow cancel during that wait still closes CANCELED. Not verified: the TypeScript sibling-failure behaviour below (code reading only) and the 1.34.x backport question.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Previous rounds. All six items are addressed, each rerun at this head. Replay disclosure: you kept the gate out, which I take as decided, and the rewritten note now matches what happens. Of nine histories recorded on current main, the closed cancelled run fails with No command scheduled for event ... WorkflowExecutionCanceled, the closed run whose sibling tool failed with ... WorkflowExecutionFailed, and four open runs with ... TimerStarted (cleanup after catching the Workflow's cancellation; a Workflow that cancelled its own run and kept going; the same with the run cancelled while the start was withheld; a Workflow that caught the sibling failure). A run waiting on its operation, a completed run and a Workflow cancelled during a withheld start replay. Sibling failure: the caller now records NEXUS_OPERATION_CANCEL_REQUEST_COMPLETED and NEXUS_OPERATION_CANCELED before WORKFLOW_EXECUTION_FAILED, and the operation's Workflow ends CANCELED; the first two P2s below are about the edges of that wait, which I suggested last round. Start-phase parity: a Workflow cancellation during a withheld start now closes at once with the operation still RUNNING, as a direct call does, and a second run cancellation during the start records nothing new. cancellation_type is in, and wait_requested covers it. The Python 3.14 ERROR is gone, and removing the conversion makes six of the seven cases fail. nested fails under the innermost-only mutation. The body no longer claims 1.0 or Draft.
Where the problems cluster: the waits do what the tests pin, and History stays deterministic. What is left is the boundary of what the runner waits for and what happens during the wait: after a tool failure it also waits when the error will fail the Workflow Task rather than the Workflow, and it swallows a Workflow cancellation that arrives meanwhile; and it waits for operations of agent runs that a tool spawned and that nothing stops. The docstring promises more than the code does, and two clauses that decide outcomes have no test.
Decision: COMMENT, because the three P2s are edge cases introduced by the new waits, each with a contained fix (trial fixes for the first two pass the PR's cases), and nothing from the last round is open.
PR body: the replay statements hold at this head (above). Small corrections: removing the cancellation conversion fails six of the seven cases on Python 3.14 (run_during_start and wait_requested as well as the four listed) and only tool_fails on 3.10, the CI minimum; 'after the run stopped waiting for it' should say that the Agents SDK stopped awaiting the tool's task (the runner is still waiting then); a direct execute_operation call raises the operation's NexusOperationError rather than returning it; the 389-test count predates the merge (452 now). If the line-477 condition lands, 'or, by the same logic, its failure' in the 'Open runs' bullet covers only failures that fail the Workflow (the one I recorded on main, a run that caught a sibling ApplicationError failure, fails here with ... TimerStarted, as the bullet expects).
Cross-language: this PR gives the Python tool two behaviours that the TypeScript sibling on main lacks: a cancellation type option (NexusOperationAsToolOptions in typescript/openai-agents/src/workflow/nexus-tools.ts has only service, endpoint, scheduleToCloseTimeout and strict), and cancelling the operation when a sibling tool fails. From the code, agents-core 0.14.3 aborts siblings through an AbortSignal and then awaits Promise.allSettled over every tool run (runner/siblingCancellation.js), while the TypeScript Nexus tool never reads details.signal, so after a sibling failure TypeScript keeps waiting for the operation to finish without sending a cancel request (code reading only, not probed). Worth adding to the TypeScript issue suggested last round.
| raise | ||
| except AgentsException as e: | ||
| # When a tool fails, the Agents SDK also cancels the run's other tools. | ||
| await _wait_for_tool_operations(operations) |
There was a problem hiding this comment.
P2: this wait also runs for tool errors that fail the Workflow Task rather than the Workflow, so it commits the parallel operation's cancel request in a successful task before the task failure, and the fix-forward that task failures exist for then fails replay. _reraise_workflow_failure rewraps only errors whose cause is a Temporal failure; anything else (a plain exception from a function_tool(..., failure_error_function=None), for example) leaves as UserError, which is not in the plugin's workflow_failure_exception_types, so the Workflow Task fails and the Worker retries it until a fix is deployed. Probe: one model response calling hold (nexus_operation_as_tool, operation backed by a Workflow that runs until cancelled) and boom (function_tool(failure_error_function=None) raising RuntimeError('tool bug') on a Signal). On main the first task after the Signal fails (Error running tool boom: tool bug), the operation's Workflow stays RUNNING, and replaying that History with boom fixed to return 'ok' succeeds. On this head the same task completes with NEXUS_OPERATION_CANCEL_REQUESTED, the operation ends NEXUS_OPERATION_CANCELED (its Workflow CANCELED), only then do the tasks fail with the same error, and replaying with the fixed boom fails with [TMPRL1100] Nondeterminism error: No command scheduled for event HistoryEvent(id: 20, NexusOperationCancelRequested). So a tool bug now cancels an operation of a run that stays open, and the run needs a reset after the fix. When I suggested this line last round I missed that distinction. Trial fix: wait only when the error will fail the Workflow, if (e.__cause__ is not None and workflow.is_failure_exception(e.__cause__)) or workflow.is_failure_exception(e): await _wait_for_tool_operations(operations). The probe then matches main (task fails at once, operation RUNNING, fixed replay OK), and the seven new cases plus test_nexus_tool_workflow pass. The trade-off is that Workflow code catching such an error gets no wait, as on main.
There was a problem hiding this comment.
+1, this one should block merge. A tool bug currently fails just the Workflow Task, so the fix is to deploy a fixed tool. With this change, that same bug cancels the parallel Nexus operation in a task that completes, and the fixed build then fails replay. That's a regression from main for a common situation. Please take the trial fix here: only wait when the error will fail the Workflow (workflow.is_failure_exception on the error or its cause). Workflow code that catches such an error not getting the wait, same as on main, is a fair trade-off. Please add a test case for it (tool raises a plain exception beside a running operation; the operation stays RUNNING and a replay with the fixed tool succeeds).
There was a problem hiding this comment.
Good catch, and thanks Jason. I took the trial fix: after a tool failure, the runner waits only when the error fails the Workflow. Code that catches a task-failing error gets no wait, as on main.
New case tool_bug: a tool raises RuntimeError next to a running operation. The Workflow Task fails, no cancel request is recorded, the operation keeps running, and the History replays with the tool fixed. A History of the same run recorded on main replays on this branch too.
| while not all(operation.done.done() for operation in pending): | ||
| try: | ||
| await asyncio.wait([operation.done for operation in pending]) | ||
| except asyncio.CancelledError: |
There was a problem hiding this comment.
P2: a Workflow cancellation that arrives during the wait after a tool failure is swallowed here, and the runner then raises the tool failure, so Workflow code that handles that failure carries on and the Workflow completes as if it had never been cancelled. Each CancelledError caught here goes to the tool tasks, where the SDK absorbs it for a started operation (_await_temporal_operation calls uncancel()), and the failure branch (raise e at line 481) never re-raises it; Temporal delivers a Workflow cancel request once, as cancel() on the main task. Probe: tools hold (the operation delays its cancellation until released) and fail; Workflow code try: return (await Runner.run(...)).final_output / except Exception: await workflow.sleep(2 s); return 'handled ...'; Signal fail, wait for NEXUS_OPERATION_CANCEL_REQUEST_COMPLETED, cancel the Workflow, release the operation. Head: History WORKFLOW_EXECUTION_CANCEL_REQUESTED ... NEXUS_OPERATION_CANCELED ... TIMER_STARTED, TIMER_FIRED ... WORKFLOW_EXECUTION_COMPLETED, result 'handled NonRetryableAgentsWorkflowError'. Main, same client steps: CANCELED (the cancellation lands in the handler's sleep, TIMER_CANCELED, WORKFLOW_EXECUTION_CANCELED). Without the except, the head closes FAILED with the tool error. Python 3.14's TaskGroup handles the same race by raising the child error and re-arming the parent's cancellation (uncancel() then cancel() in _aexit), but re-arming only reaches Workflow code that awaits Runner.run in the same task; a run in its own task, as in this PR's test Workflow, finishes with the failure and drops it. Suggested: have _wait_for_tool_operations return whether a cancel arrived, and in the failure branch raise asyncio.CancelledError() from e when one did. Trial: with that and the condition from the comment at line 477, this probe closes CANCELED, the tool-bug probe still matches main, and the seven cases plus test_nexus_tool_workflow pass. In the CancelledError branch, folding a Workflow cancellation into the run's re-raised CancelledError is ordinary asyncio (Workflow code that cancelled its own run and catches CancelledError can check asyncio.current_task().cancelling()), so a test of that pattern is enough there.
There was a problem hiding this comment.
+1 to fixing this in this PR. A Workflow that's asked to cancel shouldn't be able to complete normally because the request arrived during this wait. On main it closes CANCELED. The suggested shape looks right: _wait_for_tool_operations reports whether a cancel arrived, and the failure branch raises asyncio.CancelledError() from e when one did. DABH's trial ran it together with the line-477 fix and the seven cases still passed. A test case reproducing the probe (tool fails, Workflow cancelled during the wait, handler catches the failure) would lock it in.
There was a problem hiding this comment.
Fixed as you suggested: the wait returns whether a cancel arrived, and the failure branch raises asyncio.CancelledError() from the tool's error when one did.
New case workflow_during_failure covers your probe. The Workflow now closes CANCELED; before, it completed.
| done=asyncio.get_running_loop().create_future(), | ||
| ) | ||
| for operations in runs: | ||
| operations.add(operation) |
There was a problem hiding this comment.
P2: an agent run started in a task that a tool spawns inherits this tuple, so its operations land in the enclosing run's set, and when the enclosing run stops it waits for operations that nothing cancels; the Workflow cannot close until they end on their own. A task created inside a tool copies the context, including _tool_operations, whether or not the Agents SDK will ever cancel that task. Probe: the outer agent's spawn tool runs asyncio.create_task(Runner.run(inner)) and then either keeps waiting or awaits asyncio.wait([task]) (which does not cancel what it waits on); the inner agent's nexus_operation_as_tool starts an operation backed by a Workflow that runs until cancelled; the client cancels the agent Workflow once NEXUS_OPERATION_STARTED is handled. Head, both variants: still RUNNING 6 s after the cancel request, History ending WORKFLOW_EXECUTION_CANCEL_REQUESTED and a completed task with no NEXUS_OPERATION_CANCEL_REQUESTED, and it stays open until the operation ends or the execution timeout fires. Main: CANCELED at once. Fix: record the run that owns each operation and have a stopping run wait only for its own operations and for those of nested runs that are themselves stopping (an agent run as a tool stops once its tool task is cancelled); at the least, say in the docstring that an agent run started in a task spawned by a tool delays the enclosing run's stop until its operations end.
There was a problem hiding this comment.
Ideally it'd be nice to have this addressed too. The proper fix (record which run owns each operation; a stopping run waits only for its own operations and those of nested runs that are also stopping) is preferred.
But if that won't fit before 2.0, a docstring note would be acceptable: an agent run started in a task a tool spawns delays the enclosing run's stop until its operations end. Then file a follow-up issue for the real fix.
There was a problem hiding this comment.
I went with the real fix. Each operation belongs to the run whose tool started it, and a stopping run waits only for its own operations and those of nested runs that are stopping too.
The task structure can't tell which nested runs will stop (asyncio.gather cancels them, create_task doesn't), so the run checks with workflow.wait_condition, after the cancellation has spread. It only does this when an operation is pending.
New case spawned is your probe: the Workflow closes CANCELED right away, as on main. Before, it timed out.
|
|
||
| When the agent run is cancelled, or stops because another tool failed, it | ||
| cancels the operation and waits as ``cancellation_type`` says before it | ||
| raises. With the default, ``WAIT_COMPLETED``, the Workflow closes only after |
There was a problem hiding this comment.
P3: this paragraph is unconditional, but the wait it describes happens only in Runner.run, and with the default the Workflow can still close before the operation ends. Probed at this head: a Runner.run_streamed run cancelled after NEXUS_OPERATION_STARTED closes with NEXUS_OPERATION_CANCEL_REQUESTED, WORKFLOW_EXECUTION_CANCELED, and the operation's Workflow is still RUNNING 3 s later; a Workflow cancelled while the start is pending closes with NEXUS_OPERATION_CANCEL_REQUESTED, WORKFLOW_EXECUTION_CANCELED and the operation still RUNNING, which is what this PR's workflow_during_start case asserts. Per the SDK's NexusOperationCancellationType docs, ABANDON sends no cancel request and TRY_CANCEL does not guarantee delivery if the caller exits first, so 'it cancels the operation' holds for neither. The runtime limits are in the PR body's 'Not covered', which users will not see, and the comment at lines 318-321 and the _tool_operations comment in _openai_runner.py ('one set per active agent run') have the same gap. Suggested: 'When a Runner.run agent run is cancelled, or stops because another tool failed, the tool cancels the operation as cancellation_type says (ABANDON sends no request; with TRY_CANCEL the request may not be delivered) and the run waits for it before it raises. With the default, WAIT_COMPLETED, the Workflow closes only after the operation has ended, unless the Workflow itself is cancelled before the operation has started. Runner.run_streamed does not wait.'
There was a problem hiding this comment.
Used your wording, narrowed to errors that fail the Workflow. The comment in the tool matches, and the _tool_operations comment went away with the rewrite.
| except NexusOperationError as e: | ||
| # The run stopped and the Agents SDK cancelled this call. End it as | ||
| # cancelled, so that asyncio and the Agents SDK do not log its error. | ||
| if tracked.cancelled and isinstance(e.cause, CancelledError): |
There was a problem hiding this comment.
P3 (tests): nothing tests this tracked.cancelled guard or the inner run's own wait, and the guard decides the outcome. With tracked.cancelled and removed, all seven cases pass, but an operation cancelled by someone else while the run is live changes result. Probe: a client cancels the handler's Workflow after NEXUS_OPERATION_STARTED, with a final reply queued for the model. At this head, as on main, the agent Workflow fails with AgentsWorkflowError: ... Error running tool hold: nexus operation completed unsuccessfully caused by NexusOperationError caused by CancelledError. Without the guard the tool raises asyncio.CancelledError, the Agents SDK hands it to the FunctionTool's default formatter (its task is not in the SDK's teardown set, and this tool's failure_error_function=None covers only argument errors), the model gets 'An error occurred while running the tool. Please try again. Error: Tool execution cancelled.', and the Workflow completes. Likewise, with only the outermost run tracking (runs[:1] in _track_tool_operation), all seven cases pass, so the inner run's own set never decides a case. Suggested: an external_cancel case asserting that cause chain, and a nested case whose inner agent has a second tool that fails. Smaller: the ERROR check at tests/test_openai.py:858 reads every record captured in the worker process, not just this Workflow's, and the finally at :861 calls held_handle.describe() unguarded, which raises RPCError when the operation's Workflow never started and hides the real failure.
There was a problem hiding this comment.
Added external_cancel (fails without the tracked.cancelled guard) and nested_tool_fails (fails if the inner run skips its wait). The finally now ignores an RPCError from describe().
The ERROR check now skips "Task was destroyed but it is pending", which a Workflow closed with a pending task (like spawned) can log during a later test. I hit that once. The other errors come from the loop's logger with no Workflow ID, so I couldn't filter by Workflow.
- After a tool fails, wait for the run's Nexus operations only when the error fails the Workflow. An error that fails the Workflow Task leaves no new commands, so a Worker with the tool fixed replays the History. - If the Workflow is cancelled during that wait, raise the cancellation instead of the tool's error. - Track each operation in the agent run whose tool started it. A stopping run waits for its own operations and for those of nested runs that stop with it, checked once the cancellation has reached them. An agent run in a task that a tool started, and that nothing cancels, no longer delays the stop. - Say in the tool's docstring when the run waits and when it does not. - Add test cases for these, for an operation cancelled by its handler's client, and for a nested agent whose other tool fails.
campoy
left a comment
There was a problem hiding this comment.
Thanks for the second round, @DABH, and @JasonSteving99 for weighing in.
I rebased and pushed one commit with the fixes; details are in each thread.
| raise | ||
| except AgentsException as e: | ||
| # When a tool fails, the Agents SDK also cancels the run's other tools. | ||
| await _wait_for_tool_operations(operations) |
There was a problem hiding this comment.
Good catch, and thanks Jason. I took the trial fix: after a tool failure, the runner waits only when the error fails the Workflow. Code that catches a task-failing error gets no wait, as on main.
New case tool_bug: a tool raises RuntimeError next to a running operation. The Workflow Task fails, no cancel request is recorded, the operation keeps running, and the History replays with the tool fixed. A History of the same run recorded on main replays on this branch too.
| while not all(operation.done.done() for operation in pending): | ||
| try: | ||
| await asyncio.wait([operation.done for operation in pending]) | ||
| except asyncio.CancelledError: |
There was a problem hiding this comment.
Fixed as you suggested: the wait returns whether a cancel arrived, and the failure branch raises asyncio.CancelledError() from the tool's error when one did.
New case workflow_during_failure covers your probe. The Workflow now closes CANCELED; before, it completed.
| done=asyncio.get_running_loop().create_future(), | ||
| ) | ||
| for operations in runs: | ||
| operations.add(operation) |
There was a problem hiding this comment.
I went with the real fix. Each operation belongs to the run whose tool started it, and a stopping run waits only for its own operations and those of nested runs that are stopping too.
The task structure can't tell which nested runs will stop (asyncio.gather cancels them, create_task doesn't), so the run checks with workflow.wait_condition, after the cancellation has spread. It only does this when an operation is pending.
New case spawned is your probe: the Workflow closes CANCELED right away, as on main. Before, it timed out.
|
|
||
| When the agent run is cancelled, or stops because another tool failed, it | ||
| cancels the operation and waits as ``cancellation_type`` says before it | ||
| raises. With the default, ``WAIT_COMPLETED``, the Workflow closes only after |
There was a problem hiding this comment.
Used your wording, narrowed to errors that fail the Workflow. The comment in the tool matches, and the _tool_operations comment went away with the rewrite.
| except NexusOperationError as e: | ||
| # The run stopped and the Agents SDK cancelled this call. End it as | ||
| # cancelled, so that asyncio and the Agents SDK do not log its error. | ||
| if tracked.cancelled and isinstance(e.cause, CancelledError): |
There was a problem hiding this comment.
Added external_cancel (fails without the tracked.cancelled guard) and nested_tool_fails (fails if the inner run skips its wait). The finally now ignores an RPCError from describe().
The ERROR check now skips "Task was destroyed but it is pending", which a Workflow closed with a pending task (like spawned) can log during a later test. I hit that once. The other errors come from the loop's logger with no Workflow ID, so I couldn't filter by Workflow.
What was changed
This PR makes the run wait for its Nexus operations before it stops, the same way a direct
execute_operationcall does.nexus_operation_as_toolnow starts its operation withstart_operationand awaits the handle, which is whatexecute_operationdoes. It tracks the operation from the start request until the operation resolves, so a start that isn't acknowledged yet is covered too.TemporalOpenAIRunner.runkeeps the set of operations its tools track. WhenRunner.runraisesasyncio.CancelledErrorand some are still pending, it waits for them, then re-raises. The cancel request goes out, and the Workflow closes afterNEXUS_OPERATION_CANCELED, just like a directexecute_operationcall with the same default,WAIT_COMPLETED.NexusOperationError. Otherwise asyncio on Python 3.14 logs an ERROR for the shielded tool task, and the Agents SDK logs another one when a different tool failed.nexus_operation_as_toolhas a newcancellation_typeoption, passed tostart_operation. It defaults toWAIT_COMPLETED, the SDK's default and what the tool did before. WithWAIT_REQUESTED, for example, the run waits only until the cancel request is delivered.If the run isn't cancelled and no tool fails, nothing changes: the tool schedules the same command as before.
Thanks to DABH, whose review brought the wait on a failed tool, passing a second cancel to the tools' tasks, the Python 3.14 log fix and
cancellation_type.Why?
Cancel a Workflow while one of its agent's Nexus tools is running, and the tool's operation keeps going. The caller sees a normal cancellation, but the operation runs to the end and does all its work.
Why? When the run is cancelled, the Agents SDK's tool runner cancels the pending tool tasks and re-raises right away. The cancelled tool task does send the operation's cancel request, but the Workflow closes in the same Workflow Task, so the request never goes out.
Is this a breaking change?
Yes. The wait has no version gate, and we're not adding version gates to these fixes.
temporalio-openai-agentsalready shipped 1.0.0 and 1.1.0, so this needs the next major release, 2.0.0.Before, when an agent run stopped while a tool's Nexus operation was running (cancelled, or failed because another tool failed), the Workflow went on in the same Workflow Task. Now the run waits there for the operation. So those Histories no longer replay, and fail with
[TMPRL1100] Nondeterminism error: No command scheduled for event ...:... WorkflowExecutionCanceledor... WorkflowExecutionFailed. This hits queries, resets and replay tests.... TimerStartedor... ActivityTaskScheduled, and the run staysRUNNINGwith failing Workflow Tasks. I expect the same for a Workflow that caught the run's failure, but I didn't run that case.Runs that never stopped an agent run during a Nexus tool operation replay fine, and wait for their operations if that happens later.
How do you upgrade? Let open runs of the second kind finish on the earlier version, or keep them there with Worker Versioning. Query or reset closed runs of the first kind on that version.
Note: release notes come from commit subjects, so the release draft needs this note added by hand.
What's not covered?
Runner.run_streameddoesn't change: a cancelled streamed run still closes without waiting. Its run loop runs in a separate task, and it's not part of [Bug] openai_agents: cancelling an agent Workflow does not cancel its Nexus tool's operation #225's reproduction.activity_as_toolwithcancellation_type=WAIT_CANCELLATION_COMPLETEDprobably has the same problem (the Workflow closes before the Activity reports its cancellation). I didn't check or change it here.execute_operationcall does: the SDK re-raises a Workflow cancellation during the start.CancelledErrorafter waiting, while a directexecute_operationcall returns the operation'sNexusOperationError.temporalio1.34.x still bundles the old code astemporalio.contrib.openai_agents. No backport here.main.Open questions
Runner.run_streamedand Activity tools in follow-ups?temporalio1.34.x get a backport?Let me know what you think!
Checklist
Closes [Bug] openai_agents: cancelling an agent Workflow does not cancel its Nexus tool's operation #225.
How was this tested:
I added
test_nexus_tool_cancel_workflowtotests/test_openai.py. An agent tool starts an asynchronous operation backed by a Workflow that runs until cancelled. Every case also checks that the Workflow logged no ERROR. There are seven cases:workflow: the test cancels the agent Workflow once the tool waits on the started operation, and checks that the operation's Workflow endedCANCELED. Onmainit fails withassert <WorkflowExecutionStatus.RUNNING: 1> == <WorkflowExecutionStatus.CANCELED: 4>.run_first: the Workflow cancels its run, and the operation holds its cancellation until released. Once the cancel request is delivered, the test cancels the Workflow and checks that it's stillRUNNING. Without the wait on a second cancel, it fails withassert <WorkflowExecutionStatus.CANCELED: 4> == <WorkflowExecutionStatus.RUNNING: 1>.run_during_start: the handler starts the operation's Workflow but holds back the start's acknowledgement, and the Workflow cancels its run. The test checks that the caller is stillRUNNING, then sends the acknowledgement and checks that the operation's Workflow endedCANCELED. Without tracking from the start request, it fails withassert <WorkflowExecutionStatus.FAILED: 3> == <WorkflowExecutionStatus.RUNNING: 1>.workflow_during_start: likerun_during_start, then the test cancels the Workflow while the start is still held back. The Workflow closesCANCELEDand the operation's Workflow is stillRUNNING, as with a direct call. Without passing the second cancel to the tools' tasks, the Workflow waits for the start and times out (isinstance(TimeoutError('Workflow timed out'), CancelledError)).nested: the tool belongs to an agent that runs as a tool, and the test cancels the Workflow. If only the innermost run tracks the operation, the operation's Workflow staysRUNNING(assert <WorkflowExecutionStatus.RUNNING: 1> == <WorkflowExecutionStatus.CANCELED: 4>).tool_fails: a second tool fails once the operation has started. The Workflow fails with that tool's error afterNEXUS_OPERATION_CANCELED, and the operation's Workflow endsCANCELED. Without the wait on a failure, the operation's Workflow staysRUNNING(assert <WorkflowExecutionStatus.RUNNING: 1> == <WorkflowExecutionStatus.CANCELED: 4>).wait_requested: the tool usesWAIT_REQUESTEDand the operation holds its cancellation. The Workflow closesCANCELEDafterNEXUS_OPERATION_CANCEL_REQUEST_COMPLETED, while the operation's Workflow is stillRUNNING. If the option isn't passed tostart_operation, the Workflow waits for the operation to end and times out.Without ending the tool's task as cancelled, the ERROR check fails on Python 3.14 in
workflow,run_first,nestedandtool_fails(NexusOperationError exception in shielded future).tool_failsalso logs the Agents SDK'sBackground function tool task raised during cancellation cleanup after failure propagation.After merging
main,make lintandmake testpass locally (452 tests), and CI is green on Python 3.10 and 3.14.I also ran:
main. With this change it exits 0: the caller recordsNEXUS_OPERATION_CANCEL_REQUEST_COMPLETEDandNEXUS_OPERATION_CANCELED, and the operation's Workflow endsCANCELED, like a direct call.execute_operationcall with the same held-back acknowledgement behaves the same way: the caller staysRUNNINGuntil the acknowledgement, and the operation's Workflow endsCANCELED. Cancelling the Workflow (not the run) during the start closes both the agent run and the direct call right away withCancelledError('Workflow cancelled'), and leaves the operation's Workflow running.main: the five from the gated check below, an open run whose Workflow caught its first run's cancellation and started a second run, a run never cancelled, and a run that failed because a second tool failed while its operation ran (onmainit left the operation's WorkflowRUNNING). All eight replay onmain. On this branch, four fail with[TMPRL1100] Nondeterminism error: No command scheduled for event HistoryEvent(id: 21, ...): the two cancelled runs (WorkflowExecutionCanceled), the open run (ActivityTaskScheduled) and the failed run (WorkflowExecutionFailed). The other four replay. A History recorded on this branch replays on it. As a control, adding a timer before the agent turn fails all five Histories of that Workflow. This is the breaking change above, so these Histories are not intest_replay.kill -9between steps. Five runs were recorded onmain: two that finish (the operation completes; cancelled while the operation runs) and three left open (waiting on the operation; cancelled while the operation holds its cancellation; to be cancelled after a Worker change). Without the gate, the two cancelled Histories fail with[TMPRL1100] ... No command scheduled for event ... WorkflowExecutionCanceled, and the other three replay. The same control timer fails all five. With the gate and a second cancellation, the agent run and the direct call both stayRUNNINGwhile the operation holds its cancellation, then closeCANCELEDwith the operationCANCELED.cancellation_type. The release draft needs the breaking change note added by hand.