Skip to content

Breaking: fail a retried OpenAI Agents stateful MCP session instead of opening an empty one - #373

Merged
campoy merged 21 commits into
mainfrom
fix/openai-agents-stateful-mcp-session-replaced
Nov 3, 2026
Merged

campoy merged 21 commits into
mainfrom
fix/openai-agents-stateful-mcp-session-replaced

Conversation

@campoy

@campoy campoy commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

A retried stateful MCP session Activity of the OpenAI Agents plugin, in Python and TypeScript, no longer connects a new, empty MCP server in the middle of a run. If an earlier attempt connected its server, the retry fails with a non-retryable DedicatedWorkerFailure, as the StatefulMCPServerProvider docs say. Retries in which the server never connected still connect again, except after a lost host or a timed-out attempt (below).

Activity side (python/openai_agents/src/temporalio/openai_agents/_mcp.py, typescript/openai-agents/src/worker/stateful-mcp-provider.ts, heartbeat.ts):

  • Every attempt of the -server-session Activity sends its first heartbeat at once with the details mcp-session-may-be-open. It then reads DescribeWorkflowExecution until the Temporal server shows that heartbeat, and only then calls the factory, connects the server, and sends mcp-session-opened. A describe refused with PERMISSION_DENIED, UNAUTHENTICATED, UNIMPLEMENTED, NOT_FOUND or INVALID_ARGUMENT, or heartbeat details it cannot decode, fails the attempt at once with a non-retryable DedicatedWorkerFailure that names the status; for PERMISSION_DENIED and UNAUTHENTICATED it also says the Worker's client needs permission to describe the Workflow. Other describe errors are retried for up to 30 seconds, and the attempt then fails, retryably, with the last of them as the cause.
  • Heartbeat details carry over between attempts. An attempt that finds either marker fails with DedicatedWorkerFailure, non-retryable, before it calls the factory.
  • Only the Worker writes these details, so cancels, pauses, resets and heartbeat timeouts reach the session Activity as before. The Worker sends the latest details with the attempt's failure, including the failure for a graceful shutdown in Python, so a graceful deploy passes the marker on.
  • The Worker does not let the plugin wait for a heartbeat: it sends the next one when its throttle allows (up to 30 seconds later without a heartbeat timeout). That is why the first heartbeat says a session may be open and the server is not connected until the Temporal server shows it. A retry that finds mcp-session-may-be-open is refused too.
  • An attempt that ends without connecting (a failed factory call or first connect(), a cancel before connecting) clears the marker with one last heartbeat, which the Worker sends with the failure, so those retries connect again. Python encodes each heartbeat in its own task, so the attempt first waits for heartbeats still being encoded, for at most 10 seconds: a codec that never finishes would otherwise keep the attempt from ending. It sends the clear after that limit, or when the wait is interrupted, all the same. The clear has no details, so it skips the codec; a heartbeat that lands after it only makes the retry refuse. TypeScript's Worker sends one Activity's heartbeats in order and flushes the last one before a failure, but drops it before a cancelled result. So a TypeScript attempt that a Worker shutdown cancels before it connected fails with a retryable ApplicationFailure (the cancellation as its cause) instead of ending as cancelled. That includes a shutdown during the read-back, or during a connect() that ignores the cancellation: the attempt checks for it after each and stops instead of serving. Python checks at the same two points, since a cancellation can be lost there too (Python 3.10 and 3.11's asyncio.wait_for can drop one, and a connect() can swallow it).
  • The read-back requires the server's pending attempt to be this attempt, and stops with an error if the server shows another attempt or no such Activity (for example, after the Workflow closed).
  • Python's periodic heartbeat runs every 30 seconds as before, or at half the session's heartbeat timeout if that is shorter: with a heartbeat timeout of 30 seconds or less, every session would otherwise time out and now be refused.
  • TypeScript's periodic heartbeats (only with a heartbeat timeout, as before) now carry the current details. Without a heartbeat timeout, the session Activity now sends its first heartbeat, the marker and the clear; before, it sent none.

Workflow side (_StatefulMCPServerReference in Python, StatefulMCPServerReference in TypeScript):

  • Only the session Activity's Worker serves the per-run queue. An operation with a schedule-to-start timeout (both defaults set one) already fails with DedicatedWorkerFailure once that Worker is gone, and keeps its commands. A Python operation with a schedule_to_close_timeout also keeps its commands: that timeout ends it. An operation with neither (a Python config that sets neither, or TypeScript scheduleToStartTimeout: 0; TypeScript's operation config has no schedule-to-close option) waited there forever.
  • Such an operation now fails with DedicatedWorkerFailure at once if the session Activity has ended, with the session's failure as the cause. An operation in flight is cancelled and fails the same way when the session ends first. The caller awaits the operation itself, as on main, and a callback on the session cancels it, so when operations resolve, a run whose session does not end resumes in the same order as on main. In TypeScript, the operation path adds no async step, with or without a schedule-to-start timeout; a caller's cancellation reaches an operation on this path one step later than on main. Only runs that recorded the patch marker openai-agents-stateful-mcp-session-watch follow the session this way; a run records it at its first operation with neither timeout (Python) or with scheduleToStartTimeout: 0 (TypeScript). Runs recorded before this change have no marker and schedule such operations exactly as before (see Replay).
  • A caller's cancellation still reaches the operation, as with the plain execute_activity / scheduleActivity call. In Python, a cancellation that arrives in the step in which the operation finished is still raised, as before. A caller's cancellation also wins over the session's end: TypeScript does not fail an operation with DedicatedWorkerFailure while the caller's scope is cancelled, and Python does not when the caller's own task gets a cancellation request while the operation runs (Python 3.11 and later; a cancellation the Workflow caught earlier doesn't count; on 3.10, a caller cancelled in the Workflow task in which its session ends gets DedicatedWorkerFailure, and so does a block left in that task; the Python README says so).
  • Python only (TypeScript's operation config has no cancellation type): an operation with cancellation_type=WAIT_CANCELLATION_COMPLETED is not cancelled, because no Worker may be left to acknowledge it and an unacknowledged cancel blocks the Workflow's eviction; it stays on the session's task queue until the run ends. For this type the caller waits for the operation or the session, whichever ends first, so the operation resolves one step after other Activities that resolve in the same Workflow task, and if another branch cancels the caller in the Workflow task that brings the operation's result, the caller gets the cancellation where main returned the result. Only runs with the patch marker do this. A later stateful_mcp_server() block with the same name, which serves the same queue, refuses any operation first scheduled before its own session Activity. It compares the times the server first scheduled each Activity (activity.info().scheduled_time), so custom activity IDs do not affect it.
  • When the block exits after the session Activity failed with DedicatedWorkerFailure, Python's async with raises ApplicationError(type="DedicatedWorkerFailure") and TypeScript's cleanup() throws an ApplicationFailure of that type, each with the session Activity's ActivityError / ActivityFailure as the cause, as the docstrings say. If the block's last timer fired in the Workflow task that brought the session's end, ahead of it, the Python block raises it too, with no cause, whatever the session's error, because the SDK then drops the session's result; before, that block raised a bare CancelledError. A cancellation leaving the Python block wins over this failure (a direct cleanup() call after a Workflow cancel still raises it; its docstring says so), and so, in TypeScript, does a cancelled scope that called cleanup() or connect(), or one around cleanup() but not around connect(), also when cleanup() runs in CancellationScope.nonCancellable(). This conversion is not behind the patch marker (see Replay).

Both READMEs describe the retry behavior, the heartbeat limitation, how operations fail after the session ends, the error the block raises and the migration for code that catches the earlier one, the session's start-to-close timeout as the longest a block can stay open, resets with reset_heartbeat, the upgrade's last empty session, heartbeat encoding time, servers with the same name, and the patch marker with the rollback precaution (below). The TypeScript README also says that a graceful deploy ends the session instead of retrying it.

Breaking change (callers): a factory whose state survives being rebuilt, for example one that reloads it from storage, recovers today when the session Activity is retried. After this change that run gets DedicatedWorkerFailure: after a graceful deploy (Python), a lost host with a heartbeat timeout, the session's start-to-close timeout, or an Activity reset that keeps heartbeat details. It also gets it after a lost host or a timed-out attempt in which the server never connected. Leaving the block then raises ApplicationError(type="DedicatedWorkerFailure") in Python and throws an ApplicationFailure of that type in TypeScript, each caused by the session Activity's ActivityError / ActivityFailure, where earlier versions raised that ActivityError / ActivityFailure itself, so code that catches it around the block must also catch the new type. Before upgrading, such a caller moves to StatelessMCPServerProvider (or Python's temporal_mcp_server()), or catches that failure around the block and opens a new stateful server. The Worker's client also needs permission to call DescribeWorkflowExecution; without it, every stateful session fails at once with a non-retryable DedicatedWorkerFailure that says so.

Replay (the Activity side changes only Activity code):

  • The Workflow-side behavior is behind the patch marker openai-agents-stateful-mcp-session-watch. Histories recorded before this change have no marker, so their operations are scheduled exactly as on main and they replay on this change. That includes runs whose session Activity ended before a later operation, which earlier versions of this PR listed as breaking; runs in which a stateful operation resolved in the same Workflow task as another Activity or a Workflow cancel; a caller's cancellation of operations on two servers (review below); and Python operations with WAIT_CANCELLATION_COMPLETED. Operations with a schedule-to-start timeout (both defaults) or, in Python, a schedule-to-close timeout never reach the marker and schedule as on main. Histories recorded on main replay in both suites (the stateful-mcp-* histories without marker in their names, in python/openai_agents/tests/histories/ and typescript/openai-agents/src/__tests__/histories/).
  • When a run that started earlier continues on this change:
    • In TypeScript, it records the marker at its next such operation: @temporalio/workflow 1.24.0 does not keep a decision made during replay.
    • In Python, it records the marker only if it scheduled no such operation before the upgrade. temporalio 1.34.0 keeps the False that workflow.patched() returned while replaying the earlier operation, so that run never records the marker and keeps scheduling as on main until it ends: an operation scheduled after its session ended waits until the caller cancels it or the run ends. The Python README says so.
  • A rollback fails replay, with [TMPRL1100], for runs that recorded the marker (a patch marker without a matching change), and can fail for any run whose session failed with DedicatedWorkerFailure (a refused retry or a refused describe) and that then went on, and, in Python, for any run that caught the no-cause DedicatedWorkerFailure of the timer race (next item) and went on: the block-exit conversion and the cancellation that wins over it are not behind the marker. Do not roll back while such runs are open. Drain the earlier version's Workers before starting this one: while Workers of both versions run, a run whose session gets a refusal can fail replay when it moves from one to the other. Both READMEs say so.
  • Two Python changes reach histories recorded on an earlier version. The timer race: a block whose last timer fired ahead of its session's end, in one Workflow task, now raises DedicatedWorkerFailure with no cause (above), so a run that hit it and caught the bare CancelledError, or that failed with it although it catches ApplicationError or Exception around the block, schedules different commands on this change. And on Python 3.10, a run that hit one of the cases in which 3.10 now raises DedicatedWorkerFailure in place of a Workflow cancel can too. Let such open runs finish before upgrading, and expect replays of such closed runs (queries, replay tests) to fail. The Python README says so.
  • Also: a reset with reset_heartbeat=True clears the session's heartbeat details, so the next attempt connects a new server, as before.
  • Neither upgrade nor rollback protects the run that crosses it: a session Activity that started on the earlier code recorded no marker, so its retry at the upgrade's own Worker restart still connects a new server, and the earlier code ignores the marker.

Why?

See #372. Nothing told a retry of the session Activity apart from its first attempt, so a graceful Worker shutdown, the one-hour start-to-close timeout, or a heartbeat timeout with a lost host gave the run a new, empty MCP session, and later calls succeeded against it with no error.

Checklist

  1. Closes [Bug] openai_agents (Python and TypeScript): a retried stateful MCP session Activity silently opens a new, empty MCP session #372

  2. How was this tested:

    • Sixth review round (the third review from @DABH), in 891f428, then ab88cae and bf65898, merges of main at 565b4d5 and 9d6f9ff (their conflicts were only in test imports, test workflows and the replay test's history list). On bf65898: Python make format, make lint, make build and make test PYTEST_ARGS='-n 4' on Python 3.14.8 and 3.10.22 (546 and 544 passed); TypeScript make lint (no errors), make test (311 passed) and make build; scripts/ci/check_conventions.py.
      • New cases, each failing with its guard removed: Python test_stateful_mcp_server_empty_block (a block left before its first await keeps main's bare CancelledError, [Bug] openai_agents (Python): a stateful_mcp_server() block left before its first await raises a bare CancelledError #391; without cleanup()'s started guard it raises DedicatedWorkerFailure), signal_with_refusal (without the cancel count it ends through the recovery), shutdown_before_connect_ignored (a connect() that swallows the shutdown's cancellation; without the check after connect() the attempt serves and the Worker's shutdown hangs); TypeScript's scope cancelled between connect() and cleanup() (on a8e897e it fails with DedicatedWorkerFailure), and the NOT_FOUND describe case now throws WorkflowNotFoundError (without the branch for it, the attempt is retried until the deadline).
      • TypeScript's operation path no longer keeps each operation's result alive until the session ends. Docs: the timer race's wording, the replay and rollback notes, Python 3.10's block exits, a direct Python cleanup() after a cancel, a Workflow reset inside an open block, TypeScript's root scope after a caught cancel, and a TypeScript codec whose encode never returns.
    • Follow-ups to the fifth review round, in 375ae12, bf041c0 and a8e897e (a8e897e changes only the Python README and a docstring, to name the block-exit change that is not behind the marker; Python make lint passes):
      • The stateful MCP session tests this change adds to test-openai-agents.ts run one at a time (test.serial). With the TypeScript suite in 2-CPU containers, run side by side, the suite failed 14, 25 and 18 tests on d8f0913, all with "Workflow execution timed out", while main failed none in 3 runs. With this change it failed none in 3 runs (272 tests, 375 to 468 seconds), and main none again (263 to 351 seconds). TypeScript make lint (no errors) and make build.
      • A new Python test, test_stateful_mcp_server_worker_shutdown_while_closing, ported from Breaking: fail a retried Google ADK stateful MCP session instead of opening an empty one #311: every "may be open" heartbeat hangs in encoding, the close() limit is 60 seconds, and a Worker shutdown while the attempt waits in close() must finish within 20 seconds. Without the clear in close()'s finally it fails with a TimeoutError. Python make lint, make build and make test PYTEST_ARGS='-n 4': 482 passed on 3.14.8; on 3.10.22, 481 passed and test_external_trace_to_workflow_spans failed once under load, then passed 3 of 3 alone.
    • Fifth review round (the second review from @DABH), in 9927148 and d8f0913 on 994f490. 9927148 takes two fixes from the third review of Breaking: fail a retried Google ADK stateful MCP session instead of opening an empty one #311 (the Google ADK fix), which this review also raised: the time limit on close()'s wait and the cancel count. Python make format, make lint, make build and make test PYTEST_ARGS='-n 4' on Python 3.14.8 and 3.10.22 (481 passed on each); TypeScript make lint (no errors), make test (272 passed) and make build; scripts/ci/check_conventions.py.
      • On the source before each fix: encode_stalls hits the 90-second test timeout, operation_waiting_after_cancel ends with CancelledError('Workflow cancelled'), timer_first fails the run with a bare CancelledError('Cancelled'), and the TypeScript cleanup() test in a non-cancellable scope ends with DedicatedWorkerFailure. With the operation path's check of the caller's task removed, cancel_with_refusal completes through the recovery code. Giving the permission advice for every refusal code fails the new not_found cases in both languages.
      • The "a caller still cancels a queued operation" tests (TypeScript, and Python's operation_cancelled) let the session connect only once the server shows the call cancelled, instead of racing a 1-second timer against a 3-second connect(). One CI run on 994f490 failed the TypeScript test on macOS that way, and it failed once locally under load.
      • Histories recorded on main for this PR's earlier replay checks replay on this change, as before. None of them hits the timer race (Replay above).
    • Follow-up to the fourth review round, on 5c79dc8: a new TypeScript test, "a Workflow cancellation wins over a refused session in cleanup()", the counterpart of Python's test_stateful_mcp_server_cancelled_after_refusal. With cleanup()'s check of the caller's scope removed, it fails with DedicatedWorkerFailure. TypeScript make lint (no errors), make test (270 passed) and make build; scripts/ci/check_conventions.py. Python is unchanged and was not rerun.
    • Fourth review round (the first review from @DABH), in b861ec6 on 5c79dc8 (a merge of main at 017d88a): Python make lint, make build and make test PYTEST_ARGS='-n 4' on Python 3.14.8 and 3.10.22 (476 passed on each); TypeScript make lint (no errors), make test (269 passed) and make build; scripts/ci/check_conventions.py. CI passed on 5c79dc8.
      • This round's tests on the source from before the round, with main merged: Python's test_stateful_mcp_server_cancelled_after_refusal fails (DID NOT RAISE WorkflowFailureError: the run completed); TypeScript's Workflow cancellation test fails with DedicatedWorkerFailure, and its shutdown test with a connect() that ignores cancellation fails with MCP Stateful Server Worker failed to schedule activity.
      • The review's mutations, one at a time, each fail a test: in TypeScript, periodic heartbeats without details and no recordOpened() call (the host-kill test), no in-flight conversion (the waiting-operation test), and a changed marker value (the shutdown tests' delay count); in Python, no read-back attempt check (other_attempt), no WCC branch that keeps a cancellation arriving with the result (the WCC cancel marker history), and WCC operations awaited directly (operation_waiting_wait_cancellation and both marker histories).
      • Histories recorded with the patch marker (Python: a WCC gather and a WCC cancel; TypeScript: the caller-cancel shape) are now in the replay tests. They replay on this change and fail on main with [TMPRL1100] on the patch marker. The histories recorded on main for this PR's earlier replay checks (27 Python, 18 TypeScript) also replay on 5c79dc8.
      • The review's finding outside the diff, a TypeScript dedicated Worker that ignores the main Worker's data converter, is filed as [Bug] openai-agents (TypeScript): stateful MCP operations ignore the Worker's data converter, so they fail with a payload codec #387. main has the same code.
    • Third review round (the review comment on Python upgrade activation): a README and PR-body correction only, with no code change. The behavior comes from workflow_patch in the temporalio 1.34.0 wheel and patchInternal in @temporalio/workflow 1.24.0, and matches the reviewer's upgrade reproduction and new-run control. I did not rerun that reproduction. scripts/ci/check_conventions.py passes.
    • Second review round (the review comment on mixed operation timeouts), in 9fb99d1: the reported caller-cancellation shape, recorded on main, fails on bfa9af0 with [TMPRL1100] Activity type of scheduled event 'statefulReplayRecoverA' does not match ... and replays on 9fb99d1; a run recorded on 9fb99d1 fails on main with [TMPRL1100] on the patch marker. The Python analog (two servers, one without timeouts, with TRY_CANCEL and with WAIT_CANCELLATION_COMPLETED) replays across builds before and after. Histories recorded on main for the earlier replay checks of this PR all replay on 9fb99d1, including Python's ended-session runs that failed on bfa9af0. Python make lint, make build and make test PYTEST_ARGS='-n 4' on 3.14.8 and 3.10.22 (468 passed each); TypeScript make lint (no errors), make test (260 passed) and make build; scripts/ci/check_conventions.py.
    • First review round (findings from the review of the Google ADK equivalent, Breaking: fail a retried Google ADK stateful MCP session instead of opening an empty one #311), in bfa9af0 on 793ffeb (a merge of main at ea04762): Python make lint, make build and make test PYTEST_ARGS='-n 4' on Python 3.14.8 (467 passed) and 3.10.22 (466 passed; test_openai_tracing.py::test_workflow_only_trace_to_spans[False] failed once and then passed 3 of 3 alone on 3.10, on this change and on main); TypeScript make lint (no errors), make test (260 passed) and make build; scripts/ci/check_conventions.py.
      • Histories recorded on main at ea04762 with the Workflow Worker stopped, so that one Workflow task resolved a stateful call together with other Activities (gather) or with a Workflow cancel: on 793ffeb the gather histories fail with [TMPRL1100] Activity type of scheduled event ... does not match ... in both languages, in TypeScript also with the default config. On this change every main history replays, and histories recorded on this change replay on main. A Python gather with WAIT_CANCELLATION_COMPLETED fails across builds in both directions, with [TMPRL1100] only.
      • This round's tests on 793ffeb's source fail: the gather replays; the block-exit error type (Python's five refusal cases, TypeScript's host-kill case); and the describe tests (Python retried the session three times, calling the factory each time; TypeScript ended with an ActivityFailure at the block exit; a describe() that never returns never failed the attempt). With the SDK function names the Python codec looks for renamed, 793ffeb's delayed-heartbeat tests still pass and this round's fail on the delay count. With from err put back on the session-ended raise, the operation_waiting cause check fails.
        Supplemental local runs in Docker, with the plugins' locks (temporalio 1.34.0, openai-agents 0.22.0, mcp 2.2.0; @temporalio/worker 1.24.0, @openai/agents-core 0.14.3), Node 24.22.0 and Temporal CLI 1.9.1:
    • On c25eeec: Python make sync, make lint and make test PYTEST_ARGS='-n 4' on Python 3.14.8 and 3.10.22 (457 passed on each), and make build; TypeScript make sync, make lint (no errors), make test (255 passed) and make build; scripts/ci/check_conventions.py.
    • On e1a1ecf: Python make sync, make lint and make test PYTEST_ARGS='-n 4' on Python 3.13.16 (458 passed); TypeScript make sync, make lint (no errors), make test (256 passed) and make build; scripts/ci/check_conventions.py.
    • New Python tests, test_stateful_mcp_server_session_retried:
      • worker_replaced (graceful shutdown after the server connected) and session_timed_out (5-second session start-to-close): the retry must be refused, with one factory call. On main both fail with DID NOT RAISE WorkflowFailureError: a new server served the next call.
      • short_heartbeat_timeout (4-second session heartbeat timeout, held 10 seconds): one factory call. On main it fails with two factory calls; with a 30-second heartbeat interval it fails because the retry is refused.
      • first_connect_fails and first_connect_fails_delayed_heartbeats (a codec delays "may be open" heartbeats past the failed connect): the retry must connect. The first passes on main too; on main the delayed case fails its check that the codec delayed a heartbeat, since main sends no "may be open" heartbeat. Without the wait before clearing, the delayed case is refused.
      • shutdown_before_connect_delayed_heartbeats (the first worker shuts down gracefully while the first connect() runs and a "may be open" heartbeat is being encoded): the retry must connect, with two factory calls. Without the wait before clearing, it is refused.
    • New Python tests, test_stateful_mcp_server_operations_after_session_ended (no schedule-to-start timeout; the session on its own host queue, which shuts down gracefully after the server connected):
      • operation_waiting: the waiting list-tools is cancelled and the run fails with the refusal. On main the retry connected a second server.
      • operation_after_refusal: nothing is scheduled after the session ended. On main it times out.
      • next_block (WAIT_CANCELLATION_COMPLETED, then a second block with the same name): the first block's call does not run on the second server. On main, and without the earlier-block check, it does.
      • operation_cancelled (a caller cancels a queued call before the session's Worker polls): the call never runs. It passes on main; without passing the cancellation on, it fails.
      • next_block_custom_ids: next_block with session activity IDs session-1 and session-2; the first block's call does not run on the second server. Without the earlier-block check it does.
      • schedule_to_close (a 3-second schedule_to_close_timeout, nothing else bounding the start): the operation after the session ended is still scheduled and ends by its own timeout, as on main.
      • numeric_session_id (session activity_id="100"): the first list_tools and call_tool, with default IDs 2 and 3, succeed.
      • operation_waiting_after_cancel: operation_waiting after the Workflow caught a cancellation request; the run must still fail with the refusal.
      • operation_waiting_abandon and operation_waiting_wait_cancellation: operation_waiting with ABANDON and with WAIT_CANCELLATION_COMPLETED. In every cancellation mode, the error the operation raises inside the block has the session's refusal as its cause.
    • New Python test test_stateful_mcp_server_cancelled_after_refusal: the session is refused (6-second start-to-close), the Workflow catches the block's failure as the README advises, and the test cancels the run. The run must end cancelled, with one factory call. Before the fourth round it completed.
    • New Python test test_stateful_mcp_server_without_describe_permission: a refused describe (refused) fails the run at once, with the permission advice in the causes; a describe or decoding that never returns (describe_stalls, decode_stalls) fails the attempt at a 2-second deadline; a read-back that shows another attempt (other_attempt) fails the attempt; a describe refused with NOT_FOUND (not_found) fails the run without the permission advice; a "may be open" heartbeat whose encoding never ends (encode_stalls) still lets the attempt fail and be retried. No case calls the factory.
    • New Python test test_stateful_mcp_server_session_end_with_other_events: the Workflow Worker is stopped until the session's refusal and another event are both in history, so one Workflow task brings both. timer_first (the block's last timer fired first): the block must raise DedicatedWorkerFailure and the README's recovery run. cancel_with_refusal (a Workflow cancel, with an operation waiting): the run must end cancelled; on Python 3.10 the README's recovery runs instead, as the README says. signal_with_refusal (a Signal that ends the block, and a Workflow cancel): the same.
    • New TypeScript tests:
      • A Worker in a child process hosts the session (2-second heartbeat timeout) and is killed after put, once describe has shown mcp-session-opened right away and again 3.5 seconds later, after a periodic heartbeat; the retry on the test's Worker must be refused as one that "opened an MCP session", without a factory call. On main the run completed with get=EMPTY session=B.
      • scheduleToStartTimeout: 0 after a graceful shutdown ends the session: the next call fails at once with DedicatedWorkerFailure. On main it times out.
      • A graceful shutdown cancels the first connect() (3-second session heartbeat timeout) while a codec holds a periodic "may be open" heartbeat in encoding for 2 seconds: the retry on the next Worker must connect and the run complete, with two connects, and the codec must have delayed a heartbeat. It runs with a connect() that follows the cancellation and with one that ignores it for 3 seconds. Without the failure in place of the cancelled result, the retry is refused. Before the fourth round, the case that ignores the cancellation connected on the first Worker and the run failed.
      • A describe that is refused fails the session at once, with the permission advice only for PERMISSION_DENIED and UNAUTHENTICATED (the cases are PERMISSION_DENIED and the WorkflowNotFoundError the client throws for NOT_FOUND); a describe or decoding that never returns fails the attempt at the deadline. No case calls the factory.
      • With scheduleToStartTimeout: 0, a call waiting behind another when a graceful shutdown ends the session fails with DedicatedWorkerFailure without running.
      • A Workflow cancellation while a call with scheduleToStartTimeout: 0 runs also ends the session; the Workflow catches the call's cancellation and lists tools, and the run must end cancelled. Before the fourth round it failed with DedicatedWorkerFailure.
      • A session with a 5-second start-to-close times out and its retry is refused while the Workflow waits; the test then cancels the Workflow, whose finally calls cleanup(). The run must end cancelled, with one factory call. It also runs with cleanup() in CancellationScope.nonCancellable(), which needs the check of the scope that connected the server. A third case puts the work in a scope that a Signal cancels after the refusal, with a non-cancellable cleanup() in its finally; the Workflow must get the cancellation, which needs the check of scopes around cleanup() but not around connect().
      • Controls that pass on main too: a retry after a failed first connect connects again; a caller's cancellation of a queued call still stops it.
    • [Bug] openai_agents (Python and TypeScript): a retried stateful MCP session Activity silently opens a new, empty MCP session #372's scripts: on main and Python 1.1.0 they read EMPTY from a new session; on this change the Python run fails with DedicatedWorkerFailure (the refusal for an attempt that may have opened a session: the opened heartbeat was still held by the throttle) and in TypeScript the second Worker never connects and the run fails.
    • Replay, each language: histories recorded on main and on this change (finished, open, a caller's cancellation, a session that ended before an operation with and without a schedule-to-start timeout, a retried session), replayed on both builds with Workers without a cache; open runs carried between the builds in four directions; a renamed-Activity control that fails every history with [TMPRL1100]. Python also replayed open histories of runs that moved on after the session ended (schedule-to-close timeouts and caller deadlines, then a 60-second timer): the schedule-to-close ones replay on this change, the one whose deadline cancelled an operation scheduled after the session ended fails with [TMPRL1100]. Results are listed under Replay above; every cross-build failure is [TMPRL1100].
    • CI's Python and Node matrices, macOS and Windows were not run locally.
  3. Any docs updates needed?
    The Python and TypeScript READMEs now cover the stateful server's retry behavior, the heartbeat limitation, the describe permission, how operations fail after the session ends, and the patch marker with the rollback precaution. The Python README also says when a run that started earlier records the marker. Release notes should name the caller change, the new DescribeWorkflowExecution permission for the Worker's client, the block-exit failure type, and the replay notes above.

Not covered:

Open questions: none.

…f opening an empty one

A retried `-server-session` activity of StatefulMCPServerProvider (Python and
TypeScript) connected a new MCP server and served the run's per-run task queue
again, so later calls succeeded against a new, empty session with no error.

Each attempt now sends its first heartbeat at once with
"mcp-session-may-be-open", reads DescribeWorkflowExecution until the server
shows it, connects, and then sends "mcp-session-opened". An attempt that
inherits either marker in its heartbeat details fails with a non-retryable
ApplicationError/ApplicationFailure of type DedicatedWorkerFailure before it
calls the factory. An attempt that ends without connecting clears the marker,
so a failed factory call or first connect is still retried.
… has ended

Only the session activity's worker serves a stateful server's task queue. An
operation without a schedule-to-start timeout (a Python config that leaves it
out, or TypeScript scheduleToStartTimeout: 0) waited there forever once the
session activity had ended, for example after the retry refusal.

Such an operation now fails with DedicatedWorkerFailure at once if the session
has ended, and an operation in flight is cancelled and fails the same way when
the session ends first. A caller's cancellation still reaches the operation.
In Python, an operation with WAIT_CANCELLATION_COMPLETED is left to its own
timeout, and a later block with the same name refuses operations scheduled
before its own session activity. Operations with a schedule-to-start timeout
keep their commands.
Python only. An operation with a schedule_to_close_timeout keeps its
execute_activity commands, as one with a schedule_to_start_timeout does,
because that timeout also ends it once the session's worker is gone.

The check that refuses an earlier block's operations now compares the
scheduled times of the operation and of the session activity instead of
reading activity IDs as numbers. A session activity_id such as "100" no
longer refuses its own first operations.

The new tests wait with assert_eventually and asyncio.wait_for instead of
asyncio.timeout, which Python 3.10 does not have.
@campoy
campoy marked this pull request as ready for review November 2, 2026 00:43
@campoy
campoy requested a review from a team as a code owner November 2, 2026 00:43
… MCP fix

The first review of the Google ADK equivalent (#311) found problems that this
PR shares, in Python and TypeScript:

- Await a stateful operation itself, as main does, for every cancellation
  type but Python's WAIT_CANCELLATION_COMPLETED, and cancel it from a callback
  on the session. In TypeScript the operation path adds no async step, which
  also restores main's resume order with the default config. Histories
  recorded on main (a stateful call resolved together with other activities,
  or with a workflow cancel) replay in both suites.
- Confirm the first heartbeat before calling the factory, within a 30-second
  deadline that also bounds a describe or a decode that never returns. A
  describe refused for lack of permission, or details that cannot be decoded,
  fail the session with a non-retryable DedicatedWorkerFailure that says so.
- Raise ApplicationError / ApplicationFailure with type DedicatedWorkerFailure
  from the block when the session failed with that type, as the docstrings
  say.
- Clearer refusal and ended-session messages. The session's failure stays the
  cause of an operation that the session's end cancelled.
- Docs: the session's start-to-close timeout caps a block, resets with
  reset_heartbeat, and servers with the same name.
- Count the delays of the Python frame-walking codec.

Copy link
Copy Markdown
Member

[P1] Mixed operation timeouts change caller-cancellation order and break replay

Confirmed on bfa9af0fee384d0e07bddf6530c9523b2b7e8fa6 against base ea04762b4c984257e1161ca5f65a8990af2e7694. The new child scope in executeOperation adds a promise callback to cancellation propagation for operations without a schedule-to-start timeout.

Reproduction:

  1. Connect two stateful server references outside a caller cancellation scope. A has config.scheduleToStartTimeout: 0; B uses the default.
  2. Inside one caller scope, schedule A's callTool, then B's. Each branch catches cancellation and schedules a distinct recovery Activity (recover-A / recover-B) inside CancellationScope.nonCancellable.
  3. Once both calls are queued and both sessions are still open, cancel the caller scope through a Signal.

The base requests cancellation in A → B order and schedules recover-A → recover-B. This PR requests cancellation in B → A order and schedules recover-B → recover-A.

Replaying the base history on the PR fails with:

[TMPRL1100] Nondeterminism error: Activity type of scheduled event 'recover-A' does not match activity type of activity command 'recover-B'

The reverse replay (PR history on base) fails with the corresponding reversed mismatch. Both sessions remain open at caller cancellation, so this is outside the documented intentional breaks after a session ends.

Validation used the actual StatefulMCPServerReference source from each snapshot, SDK 1.24.0, Node 24.22.1, and Temporal Server 1.32.0. Deterministic local Activities held the sessions open; operation queues were deliberately unpolled. No external MCP service or model was involved.

  • All eight histories replay on their recording build.
  • Controls with both default timeouts, both timeouts disabled, and only B's timeout disabled pass cross-version replay in both directions (six successful control replays).
  • A renamed recovery Activity positive control fails replay as expected.

Please preserve the original caller-cancellation ordering, or version this Workflow-side path.

In TypeScript, an operation without a schedule-to-start timeout runs in its
own cancellation scope so that the session's end can cancel it. That scope
delivers a caller's cancellation one step later than earlier versions did,
so a caller that cancels calls to two servers schedules its next commands in
another order, and earlier histories fail replay (reported in review).
Python's WAIT_CANCELLATION_COMPLETED path changes the resume order in a
similar way.

Operations without those timeouts now follow the session only in runs that
recorded the patch marker openai-agents-stateful-mcp-session-watch. Runs
recorded before it schedule them as main does, so their histories replay,
including runs whose session ended. Histories recorded on main with the
reported shape (TypeScript) and with WAIT_CANCELLATION_COMPLETED operations
(Python) replay in the suites.
@campoy

campoy commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @brianstrauch, reproduced on bfa9af0 exactly as you describe: main schedules recover-A → recover-B and bfa9af0 the reverse, with [TMPRL1100] in both directions, while the both-default control replays.

TypeScript has no public way to cancel a single Activity without giving it its own cancellation scope, and that scope always gets the caller's cancel one step later. So I versioned the path, as you suggested, in 9fb99d1. Operations without a schedule-to-start timeout now follow the session only in runs that recorded the patch marker openai-agents-stateful-mcp-session-watch, which a run records at its first such operation. Histories from before have no marker and schedule exactly as on main.

  • Your shape, recorded on main, is now in the TypeScript replay test (stateful-mcp-caller-cancel.json). It fails on bfa9af0 and replays on 9fb99d1. A run recorded on 9fb99d1 fails on main because of the marker, so rolling back is unsafe for runs that have it; both READMEs say so.
  • The Python version of your shape didn't reorder: with TRY_CANCEL and with WAIT_CANCELLATION_COMPLETED, it replays across builds. But Python's WAIT_CANCELLATION_COMPLETED path had a related resume-order break, so it's behind the same marker, with a main-recorded history in test_openai_replay.py.
  • Side effect: the older main histories this PR listed as breaking (a session that ended before a later operation) now replay too. I rewrote the Replay section of the PR body to match.

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First review, at head 0eff9e9, which is bfa9af0 plus two commits: 9fb99d1 puts the Workflow-side operation path behind the openai-agents-stateful-mcp-session-watch patch marker, and 0eff9e9 corrects the Python README. On a worktree at the head, Python make lint is clean and make test gives 468 passed; TypeScript make lint has 0 errors (its 8 warnings are in files this PR does not touch) and make test gives 260 passed; CI is green on every cell. Findings were reproduced with real Workers against a local dev server, origin/main (61fe33a) against this head, and every recorded history was replayed with Replayer or Worker.runReplayHistory on both builds. The head's new tests were also run against main's source and against bfa9af0's Workflow logic, and each load-bearing branch was mutated in turn. The fixes suggested in the first two comments were applied and re-run the same way.

The problem classes found in the Google ADK twin (#311), checked here in both languages:

  • (a) Resume order: no change. 41 TypeScript and about 90 Python histories recorded on main replay on the head. They cover gathers with call_tool/list_tools under every Python cancellation type and schedule-to-close, TypeScript with the default and with scheduleToStartTimeout: 0, filters and caching, the runner with parallel tool calls, sessions that ended before an operation, and brianstrauch's caller-cancel shape. With the gate forced off, the WCC gathers, the ended-session shapes and the caller-cancel shape fail, so the gate is what makes them replay.
  • (b) A cancellation that arrives with an operation's completion is kept. Cancel races end CANCELED on both builds in both languages, and timer races resolve the same way on both builds (TIMEOUT in Python; in TypeScript the completion wins). But the session's end now overrides the caller's cancellation in other ways (first two comments).
  • (c) Heartbeat interval: fixed in both languages. 100 s blocks with session heartbeat timeouts of 1, 4, 10, 20, 45 and 75 s, and none, stayed healthy without patching any constant, with Core's 0.8 x timeout throttle (capped at 60 s) visible on the server.
  • (d) A refused describe fails the session at once, non-retryably, with the permission named and no loop. With the default config the run fails at the first operation's 30 s schedule-to-start timeout, with the refusal in the cause chain.
  • (e) The block exit raises ApplicationError / ApplicationFailure of type DedicatedWorkerFailure, as the docstrings say.
  • (f) Same-name overlap behaves as both READMEs describe. In Python the last call ran on the old server at 29.3 s and the first on the new one at 31.7 s (main: 29.5 s and 31.1 s); in TypeScript the new session is refused as already running. Two cases the READMEs do not cover are in the comments on Python README line 582 and TypeScript README line 520.

Also confirmed:

  • The read-back decodes with exactly the Worker's encode context in both languages: strict context-keyed codecs, a custom TypeScript payload converter, and TypeScript external storage.
  • An empty heartbeat clears the stored details.
  • scheduled_time stays constant across operation and session retries and never refused a legitimate operation.
  • Python's patched() keeps False for a run that scheduled such an operation before the upgrade, and TypeScript records the marker mid-run and replays afterwards, as each README says.
  • A left-pending WCC operation does not block eviction.
  • Marker runs fail on main with 'Non-deprecated patch marker encountered', as disclosed.
  • brianstrauch's caller-cancel reorder is fixed at this head: the main-recorded history replays here and fails on bfa9af0's logic.

Refuted: an ungated command change for histories recorded purely on main (none found). Not verified: a real server-side PERMISSION_DENIED (simulated in the client), ResetActivity or pause during the read-back, a describe served by a lagging replica, and Python 3.10 or Linux and Windows locally (CI covers them).

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 Worker-side protocol (the single heartbeat writer, the read-back, the clear sent after pending heartbeats) and the patch gate hold up, and the suite pins most of the Python side. What is left is how a session's end meets the caller's own cancellation. In Python the block's new DedicatedWorkerFailure replaces a Workflow cancel, and the README's recovery advice then swallows it. In TypeScript the session-watching path throws the session-ended failure although the caller is cancelled, and a Workflow cancel always ends the session too. The rollback precaution lost the runs that took that recovery path. The rest is documentation (a TypeScript claim about shutdowns before connecting, the upgrade's last empty session, the error-type migration, two same-name cases) and TypeScript tests that cannot see several of the new branches.

Requesting changes: in both languages a Workflow cancellation can now end the run FAILED, or with the README's recovery code be lost while the run carries on, which is a correctness defect introduced by this PR; the rollback precaution should be corrected with it.

PR body:

  • 'first_connect_fails and first_connect_fails_delayed_heartbeats ... Both pass on main too' holds only for the first. On main's source the delayed case fails on assert codec.heartbeat_delays and codec.failure_delays (0), since main sends no 'may be open' heartbeat.
  • The refusal text is quoted twice as 'may have opened'. bfa9af0 changed it to 'ended (it lost its worker, timed out, or was reset) without confirming that it opened no MCP session'.
  • The commit 1/2/3 structure, 'The Workflow side can be dropped on its own', and the '457 passed' and '458 passed' labels are out of date (the head gives 468 and 260).
  • 'In TypeScript, the operation path adds no async step ... so a run whose session does not end resumes in the same order as on main' holds for resolutions, but not for a caller's cancellation in marker runs, as the comment at stateful-mcp-client.ts:256-258 says.
  • The test list leaves out operation_waiting_abandon, operation_waiting_wait_cancellation and the three describe tests.

Title: release notes come from the squash subject, which names only the refusal. The new DescribeWorkflowExecution permission (a Worker identity without it fails every stateful session) and the block-exit exception type are operator-facing breaks. The title, or the release notes the body asks for, should name them.

Parity: both OpenAI Agents languages are covered. The remaining differences follow from API or SDK differences: WCC, schedule-to-close and the earlier-block check exist only in Python, endingError only in TypeScript, and the two SDKs decide patched() differently, as each README says. The exceptions are the graceful-deploy difference and the same-name direction in the comments on provider line 325 and README line 520. Google ADK's Python toolset is #311. The TypeScript, Go and Java Google ADK plugins have no stateful session, and Python's temporal_mcp_server() and the python/mcp plugin are sessionless.

Findings on lines outside the diff

  • typescript/openai-agents/src/worker/stateful-mcp-provider.ts:363: Pre-existing, not introduced here (worth its own issue): the dedicated per-run Worker is created without the main Worker's dataConverter, so stateful operations fail for users with an encrypting codec or external storage. With a codec that changes encoding, every operation fails with Failed to parse activity args for activity ...-stateful-call-tool: Unknown encoding; with external storage at threshold 0, it fails with [TMPRL1105] Detected externally stored payload(s) but external storage is not configured. Both happen on main and on the head. The PR's own read-back decodes correctly, and Python is unaffected because its dedicated Worker uses activity.client().

Comment thread python/openai_agents/README.md Resolved
Comment thread python/openai_agents/README.md Resolved
Comment thread typescript/openai-agents/README.md Resolved
- A caller's cancellation wins over the session's end. In Python, a
  cancellation leaving the block wins over the block's
  DedicatedWorkerFailure, and an operation the session's end cancelled is
  not converted while the caller's own task is being cancelled (Python 3.11
  and later). In TypeScript, a cancelled caller scope wins at the
  ended-session check, at the conversion and in cleanup().
- TypeScript: a synchronous throw from scheduleActivity is no longer
  swallowed, and a session cancelled during the read-back, or during a
  connect() that ignores cancellation, stops instead of serving, so a
  Worker shutdown there is retried.
- The read-back gives the permission advice only for PERMISSION_DENIED and
  UNAUTHENTICATED, with the wording of the Google ADK fix.
- Docs: the rollback warning covers runs that caught the block's new error
  type, drain the earlier version's Workers first, the deploy's last empty
  session, the error-type migration, heartbeat encoding time,
  WAIT_CANCELLATION_COMPLETED resume order, TypeScript graceful deploys,
  and the other same-name direction in TypeScript.
- Tests: a Workflow cancellation after a refusal ends the run cancelled; a
  waiting operation fails when its session ends (TypeScript); the host-kill
  test kills after the opened marker and a periodic heartbeat; a shutdown
  with a connect() that ignores cancellation; the read-back's attempt
  check; the codec counts its delays; histories recorded with the patch
  marker replay.
@campoy

campoy commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @DABH for the thorough review. All nine comments are addressed in b861ec6, on a merge of main at 017d88a (head 5c79dc8), with a reply in each thread. CI is green on 5c79dc8.

Checks on 5c79dc8: Python make lint, make build and make test on 3.14.8 and 3.10.22 (476 passed each); TypeScript make lint (no errors), make test (269 passed) and make build; scripts/ci/check_conventions.py. This round's tests fail on the source from before b861ec6 where you found a defect, and each mutation you listed now fails a test. The histories recorded on main for this PR's earlier replay checks (27 Python, 18 TypeScript) replay on 5c79dc8.

@campoy
campoy requested a review from DABH November 3, 2026 05:36
…ilure after a caught cancel

- Python: an attempt that connected no MCP server waits at most 10 seconds
  for heartbeats still being encoded, then clears the marker anyway. A codec
  that never finished kept the attempt, and the Worker's shutdown, waiting
  forever. The clear has no details, so it skips the codec and is the
  heartbeat the Worker waits for before completing; a heartbeat that lands
  later only makes the retry refuse.
- Python: an operation that the session's end cancelled fails with
  DedicatedWorkerFailure unless the caller's task got a new cancellation
  request while it ran. Task.cancelling() stays up after code catches a
  cancellation, so work after a caught Workflow cancel got CancelledError.
- Tests: a heartbeat whose encoding never ends, work after a caught cancel,
  and a describe refused with NOT_FOUND, which gets no permission advice
  (both languages).

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second round, at head 994f490: b861ec6 addresses last round's review, two merges bring in main up to 017d88a, and 994f490 adds one TypeScript test. On a worktree at the head, Python make lint is clean and make test gives 476 passed; TypeScript make lint has 0 errors (its 8 warnings are in files this PR does not touch) and make test gives 270 passed; check_conventions.py passes and CI is green on every cell. Last round's reproductions were rerun with real Workers against a local dev server, on this head, on main (017d88a), and on this head with b861ec6's Workflow-side changes reverted. New findings were reproduced the same way, or with histories recorded on one build and replayed with Replayer or Worker.runReplayHistory on the other, and coverage claims come from mutating each branch. Refuted: an ungated command change for histories recorded on main (last round's 101 Python and 41 TypeScript main histories, the committed ones and this round's main recordings all replay on the head; the only results that changed are runs recorded on 0eff9e9 whose cancel now wins, which is the fix); a name reservation that delays a later same-name block; and a change in what leaves the block for endings main already had. Not verified: a natural trigger of the timer race below without an outage, ResetActivity during the read-back (pause behaves correctly), real server-side describe stalls and codec faults (simulated with a client interceptor and a payload codec), and Linux or Windows locally.

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Previous rounds. Both blocking items are fixed:

  • Python (_mcp.py:610 last round): on Python 3.11 and later all five reproductions end CANCELED on the head, with or without the README's recovery, and no new block is scheduled (recovery shapes: 13 ActivityTaskFailed | 17 WorkflowExecutionCancelRequested | 21 WorkflowExecutionCanceled). That includes the same-activation shape with an operation in flight. test_stateful_mcp_server_cancelled_after_refusal fails with the __aexit__ change reverted. Python 3.10 keeps a gap, partly disclosed (comment on README line 628).
  • TypeScript (stateful-mcp-client.ts:268 last round): the runner shape, the catch-then-listTools() shape, the session's end and the cancel in one Workflow Task, and cleanup() in a finally after a refusal all end CANCELED. With b861ec6's client hunk reverted, each ends FAILED with DedicatedWorkerFailure. Both new tests fail with their checks removed. One variant remains (comment on line 219).

Also addressed, each checked by probe or mutation:

  • A graceful shutdown during the read-back, or during a connect() that ignores cancellation, now fails the attempt retryably and clears the details, and the retry connects on the next Worker.
  • A synchronous scheduleActivity throw now rejects.
  • Each TypeScript mutation the author listed fails the test it names. The abort check after the read-back and the sync-error capture stay untested, as the body says.
  • The describe messages, and the README items from the comments on README lines 582 and 520 (two of the new sentences need tightening, comment on line 628).
  • The TypeScript graceful-deploy note: a shutdown completes the session, cleanup() does not throw, and the next operation fails with DedicatedWorkerFailure.
  • The data converter, filed as #387.

Accepted as decided: the conversion stays ungated, with the README route instead, and the title stays. On the title, release_tool.py builds the notes from commit subjects only (--format=%h%x1f%s), so the body's 'Release notes should name ...' line reaches them only if whoever cuts the release edits the draft. Partly open: the rollback sentence is back, but b861ec6's cancel-wins created another class of run it misses (comment on README line 643).

The Google ADK classes from #311, checked in both languages:

  • (A) The timer-first race at block exit: present in Python (comment on _mcp.py:639), absent in TypeScript.
  • (B) The block-exit type change: only session failures caused by DedicatedWorkerFailure convert, and main never produces one. Main histories that caught the earlier type for other endings replay on the head. In Python these are a non-retryable factory error, a one-attempt shutdown or timeout, and a bounded policy that fails every attempt; in TypeScript, StatefulMCPServerAlreadyRunning. Only mixed-version runs break, and the drain sentence covers them.
  • (C) A reservation: none. Both languages check for a running server after the read-back and register it with no await in between. With the earlier session's describe stalled, or its first heartbeat encode delayed, a later same-name block's first operation came at 1.07 to 1.24 s in Python (main: 1.05 s) and 10 to 110 ms in TypeScript (main: 3 to 7 ms). What is left is close()'s unbounded wait (comment on _mcp.py:546).

Where the problems cluster: the Worker-side protocol and the patch gate still hold, and last round's blocking shapes end CANCELED. What is left sits at the block boundary, where a session's end meets a cancellation in a shape other than the plain finally the tests cover: the SDK's dropped-result race in Python, a nonCancellable cleanup() in TypeScript, and a stale cancel count in compensation code. The rollback text was again keyed on what the code caught rather than on the session's failure. The rest is README wording, the codec wait and tests.

Commenting rather than approving: last round's blocking items are fixed, but three edge-case P2s remain (a timer-first refusal that fails the run with a bare cancellation, a nonCancellable cleanup() that turns a cancel into FAILED, and a rollback rule that misses runs b861ec6 made unsafe), and each has a small fix.

PR body:

  • 'Histories recorded on main replay in both suites (...stateful-mcp-*-workflow-history.json, ...stateful-mcp-*.json)': the globs now also match the three marker histories recorded on this change.
  • 'is killed after put, once describe shows mcp-session-opened and again 3.5 seconds later' reads as two kills; the test checks twice and kills once.

Parity: apart from SDK or API differences and documented ones, Python and TypeScript differ in the three places the comments cover: the timer race (Python), a nonCancellable cleanup() (TypeScript) and operations in compensation code (Python). The Python StatefulMCPServerProvider docstring also did not get TypeScript's new sentence about a retried session.

try:
await self._connect_handle
await session
except Exception as e:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 (non-blocking): when the session's refusal lands in the same workflow task as the block's last timer, timer first, the block raises a bare asyncio.CancelledError instead of the documented DedicatedWorkerFailure, and the run fails with an empty cancellation. This is class (A) from the #311 review, and it reproduces here.

Why: the timer wakes the body before the session handle's task has consumed its failure. session.cancel() (line 636) then makes the SDK drop the result and re-raise the cancellation (_await_temporal_operation, flag RAISE_ON_CANCELLING_COMPLETED_ACTIVITY). asyncio.CancelledError is a BaseException, so it passes this except Exception and __aexit__'s except ApplicationError. With no cancel requested, the SDK fails the workflow with it.

Reproduced by stopping the workflow worker until both events were in history, then restarting it. Default session config; the session's host shut down gracefully after the timer fired, and a second host refused the retry:

  • async with ...: await s.list_tools(); await workflow.sleep(4): 13 TimerFired | 16 ActivityTaskFailed (refusal) | 19 WorkflowExecutionFailed, whose failure is a bare canceledFailureInfo with no message. The worker only logs Future exception was never retrieved ... DedicatedWorkerFailure: An earlier attempt ... opened an MCP session.
  • With the README's recovery (except ApplicationError of type DedicatedWorkerFailure, then a new block): the same, and the recovery never runs.
  • With an except asyncio.CancelledError compensation around the block: the handler runs, though nobody cancelled.
  • A person-wait wait_condition(lambda: approved, timeout=4) that expires: the CancelledError replaces the TimeoutError, so the 'approval timed out' path is skipped too.
  • Control, refusal first in history: DedicatedWorkerFailure <- ActivityError <- DedicatedWorkerFailure, as documented. TypeScript in the timer-first shape throws DedicatedWorkerFailure as documented, because its SDK applies every job before user code runs.

Main reconnects on the same deploy (#372), so it cannot reach this ending. A one-attempt session ended by a shutdown or a timeout races the same way on both builds, so the mechanism predates the PR. The PR makes it reachable with default settings in the deploy it is about, when the workflow worker restarts too and the block's last timer fires during the restart. The code is unchanged since 0eff9e9.

Fix (tested), as in #311: decide before cancelling, and compare the cancel count around the await:

started = inspect.getcoroutinestate(session.get_coro()) != inspect.CORO_CREATED
caller = asyncio.current_task()
counts = caller is not None and hasattr(caller, "cancelling")
cancels = caller.cancelling() if counts else 0
session.cancel()
try:
    await session
except asyncio.CancelledError:
    if not started or not session.cancelled() or (counts and caller.cancelling() > cancels):
        raise
    # The session ended in this workflow task, and the SDK dropped its failure.
    raise ApplicationError(
        "The stateful MCP server session activity has ended, so no worker serves "
        "this server's operations.",
        type="DedicatedWorkerFailure",
    ) from None
except Exception as e:
    ...  # as now

With it:

  • the timer-first runs raise DedicatedWorkerFailure (with no cause, since the SDK has dropped it), and the README's recovery runs;
  • the controls are unchanged;
  • the 86 stateful, MCP and replay tests pass;
  • a test that holds the workflow worker until TimerFired and the refusal are both in history fails on the head and passes with the fix.

A main-recorded run that hit this race with a one-attempt session and caught the CancelledError would take another path with the fix, so gate it with workflow.patched() if that matters.

Pre-existing, from the same except Exception, worth its own issue: a block that exits before its first await (async with stateful_mcp_server(...): pass, or a body that raises first) also leaves with a bare CancelledError on main and the head, replacing the body's error.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, reproduced and fixed in d8f0913 with your change. Before cancelling, cleanup() notes whether the session had started and the caller's cancel count. If the handle then ends cancelled although the session had started and the caller got no new cancel, the block raises DedicatedWorkerFailure, with no cause, since the SDK has dropped it. Blocks whose session never started keep main's behavior.

test_stateful_mcp_server_session_end_with_other_events[timer_first] stops the Workflow Worker until TimerFired and the refusal are both in history. On the source before d8f0913 the run fails with a bare CancelledError('Cancelled'); with the fix, the README's recovery runs.

It isn't gated. The PR body's Replay section now says that a main run with a one-attempt session that hit this race, caught the bare CancelledError and is still open takes another path. The early-exit case is filed as #391.

) {
// A cancellation of the caller wins over the session's failure, as
// when cleanup() runs in a finally after the caller was cancelled.
if (!CancellationScope.current().consideredCancelled) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 (non-blocking): this check reads the scope that cleanup() runs in, so a cleanup() wrapped in CancellationScope.nonCancellable, a common idiom for cleanup in a finally, still lets a refused session turn a Workflow cancel into FAILED. Last round's shapes are fixed, and this is the variant that remains.

Same Workflow code on both builds, finally { await CancellationScope.nonCancellable(() => server.cleanup()); }, a 4 s session start-to-close and a 1 s heartbeat timeout, Workflow cancelled after the session's retry:

  • Head: the retry is refused, cleanup() throws, and the run ends WorkflowExecutionFailed with ApplicationFailure(DedicatedWorkerFailure): ... has ended <- ActivityFailure <- ... opened an MCP session. A catch (isCancellation) compensation never runs.
  • Main: the timed-out attempt's retry connects a new server ([Bug] openai_agents (Python and TypeScript): a retried stateful MCP session Activity silently opens a new, empty MCP session #372), and the run ends WorkflowExecutionCanceled.
  • Without the heartbeat timeout main fails too, with StatefulMCPServerAlreadyRunning, because the timed-out attempt still holds the name on the same Worker. So the regression is for sessions with a heartbeat timeout or a lost host.

Python does not have this, because __aexit__ decides from exc_value, the exception leaving the block.

Fix (tested): let a cancelled enclosing scope win in cleanup() only. For example, remember the scope in connect() (this._connectScope = CancellationScope.current()) and check CancellationScope.current().consideredCancelled || this._connectScope?.consideredCancelled, or walk scope.parent. Either way:

  • the nonCancellable run ends CANCELED and runs its compensation;
  • a timer-first refusal still throws;
  • the Stateful MCP: tests pass;
  • executeOperation keeps its own check, so a nonCancellable caller still gets DedicatedWorkerFailure for an ended session.

Or document the nonCancellable case. Either way, the README (line 518) should say that cleanup() does not throw when the caller's scope is cancelled. Only this class's docstring says so, and the class is not exported: statefulMcpServer() returns StatefulTemporalMCPServer, whose cleanup() has no doc.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d8f0913. cleanup() also checks the scope that connected the server (the session scope's parent), so a cleanup() in CancellationScope.nonCancellable() after a Workflow cancel no longer throws. executeOperation keeps its own check.

The cleanup() test now also runs with nonCancellable(); on the source before d8f0913 that variant ends with DedicatedWorkerFailure. The README and the StatefulTemporalMCPServer.cleanup() doc now say that cleanup() doesn't throw when the scope that called cleanup() or connect() is cancelled.

Comment thread python/openai_agents/README.md Outdated
before until it ends: one scheduled after its session ended waits until the
caller cancels it or the run ends. A run with the marker fails replay on an
earlier version, and so does a run whose session got a refusal and that then
caught the block's `ApplicationError`, so do not roll back while such runs are

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 (non-blocking): the rollback rule is narrower than the set of runs that fail on rollback. Since b861ec6, a run that got a refusal and then caught the Workflow cancellation fails too. And a session that failed for lack of the describe permission is not plainly a 'refusal'. The cause is the ungated cancel-wins return in __aexit__ (_mcp.py:661-667) on top of the ungated conversion, and cleanup()'s scope check in TypeScript.

Setup: default config (no marker), a 6 s session start-to-close so the retry is refused, then a Workflow cancel. The code catches the cancellation around the block and runs a compensation activity.

  • Python: the head schedules the compensation (event 21) while the run is open. Replayed on main: [TMPRL1100] Nondeterminism error: Fail workflow machine does not handle this event: HistoryEvent(id: 21, ActivityTaskScheduled). The variant that also has the README's except ApplicationError fails the same way; that catch never fires, because the cancel wins.
  • TypeScript (cleanup() in a finally, then a nonCancellable compensation in catch (isCancellation)): the same error at id 21.
  • The same shapes recorded with 0eff9e9's logic replay on main, because both builds failed the run. So b861ec6 introduced this.

Refused describe: a Worker client without the new permission fails the session with DedicatedWorkerFailure ('... Give the worker's client permission ...'). A run that recovered as the README says and ran another activity fails on main at HistoryEvent(id: 16, ActivityTaskScheduled), in both languages. An upgrade deployed without that permission breaks every stateful session, which makes it the likeliest reason to roll back.

The body already states the right rule: 'Do not roll back while runs that recorded the marker or got the refusal are open.' Suggested wording, here and in the TypeScript README (line 531): 'A run with the marker fails replay on an earlier version, and so can any run whose session failed with DedicatedWorkerFailure (a refused retry or a refused describe) and that then went on, whether it caught the block's failure or a cancellation, so do not roll back while such runs are open.' Gating the conversion and the cancel-wins with workflow.patched() / patched() would instead make 'runs with the marker' complete again.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, thanks. In d8f0913 both READMEs and the PR body use your wording: a run with the marker fails replay on an earlier version, "and so can any run whose session failed with DedicatedWorkerFailure (a refused retry or a refused describe) and that then went on, whether it caught the block's failure or a cancellation". We're keeping the docs route rather than gating, as decided last round.

if (
cancelled_by_session
and is_cancelled_exception(err)
and not _task_cancelling()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: once a workflow cancel has been caught, Task.cancelling() stays above 0 for the rest of the run. So in compensation code, an operation that the session's end cancels raises a raw ActivityError(CancelledError) instead of DedicatedWorkerFailure, and __aexit__ then also drops the block's failure. Nothing calls uncancel() after the workflow's own CancelledError is caught.

Probe (marker path): the workflow catches its cancel. Compensation then opens a block with neither timeout, whose session times out and is refused with a call in flight.

  • Head: the call raised ActivityError: Activity cancelled <- CancelledError, and the except ApplicationError fallback was skipped.
  • Without the earlier workflow cancel, the same block's call raises DedicatedWorkerFailure. On 3.10, or with this guard removed, so does the compensation's call, and the fallback runs.
  • Introduced in b861ec6.

Fix (tested): read the count when the operation starts (cancels = task.cancelling() before await operation), and skip the conversion here only if task.cancelling() > cancels. The same-activation cancel ([resolve_activity(session failed), cancel_workflow]) still ends CANCELED.

Nothing pins this guard. With it removed, the 86 stateful, MCP and replay tests pass, while last round's same-activation reproduction with the README's recovery goes back to COMPLETED. A test of that shape would pin it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9927148 as you suggested. The count is read before awaiting the operation, and the conversion is skipped only if it rose. test_stateful_mcp_server_operations_after_session_ended[operation_waiting_after_cancel] catches a Workflow cancel first; on the source before 9927148 the run ends with CancelledError('Workflow cancelled').

d8f0913 also pins the guard: test_stateful_mcp_server_session_end_with_other_events[cancel_with_refusal] is your same-activation shape with the README's recovery. It ends cancelled, and with the guard removed it completes. On Python 3.10 it expects the documented outcome, the recovery.

Comment thread python/openai_agents/README.md Outdated
workflow task, and if another branch cancels the caller in the workflow task
that brings the operation's result, the caller gets the cancellation. A
caller's own cancellation still cancels the operation, and a cancellation that
leaves the block wins over the session's failure. On Python 3.10, a caller that

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (docs): three sentences in the new text overstate or stop halfway.

  1. 'a cancellation that leaves the block wins over the session's failure' holds only for DedicatedWorkerFailure. Take a one-attempt session that times out, then a workflow cancel. The block still raises ActivityError <- TimeoutError, which replaces the cancel (FAILED on the head and on main). Code that catches ActivityError, as the migration bullet says this case still raises, loses the cancel and completes. Qualify the sentence rather than broadening __aexit__: a main-recorded history of that shape replays on the head only because __aexit__ catches just ApplicationError.
  2. Lines 599-601, 'running out of a bounded server_session_config retry policy, still makes the block raise ActivityError', hold only if no refusal comes first. With maximum_attempts=2 and a timed-out first attempt, attempt 2 is refused and the block raises ApplicationError(DedicatedWorkerFailure), which an except ActivityError misses (main raised an ActivityError, which it caught). Say 'a one-attempt policy, or a session whose attempts all fail before connecting'.
  3. The Python 3.10 sentence stops halfway: with the README's own recovery code, that caller's workflow cancel is lost. On 3.10.20, last round's same-activation shape ([resolve_activity(session failed), cancel_workflow], a call in flight, neither timeout) ends COMPLETED through the recovery catch.

Also, line 592's 'clears the marker' uses 'marker' for the heartbeat details before the patch marker is introduced under the same word (TypeScript README line 523 too).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d8f0913:

  1. The sentence now says the cancellation wins over the block's DedicatedWorkerFailure, though not over an ActivityError from a session that failed for another reason.
  2. The examples are now "a one-attempt server_session_config retry policy, or one whose attempts all fail before connecting".
  3. The Python 3.10 sentence now says that code that catches the error, as the README advises, loses the cancellation.

"Marker" now means only the patch marker; the heartbeat side says "heartbeat details", in both READMEs.

# encoded would otherwise replace it. If this wait is interrupted,
# the marker stays and the retry is refused.
if self._sending:
await asyncio.wait(set(self._sending))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: this wait has no bound, so a slow or stuck payload codec holds the attempt, and a worker shutdown, until the encode returns. Encoding time also now delays every block's first operation. #311 got the same suggestion.

  • A 20 s first heartbeat encode delayed worker.shutdown() by 18.6 s.
  • With a hung encode, close() kept waiting, and shutdown did not return within 45 s, both after the read-back timed out and during it. Main returns at once: its heartbeats carry no details, so they never reach the codec.
  • Every block now waits for an encode and the read-back before it connects. With 20 s encodes the first operation answered at 21.2 s.
  • With 35 s encodes the read-back gave up, and the run failed at the operation's schedule-to-start with 'MCP Stateful Server Worker failed to schedule activity', with nothing about encoding in the chain.

Fix (tested): asyncio.wait(..., timeout=5), and send the clear in a finally. A late earlier heartbeat can only re-mark the attempt, so its retry is refused, which is the conservative direction the comment above already allows. Shutdown then returned in at most 5 s, and the delayed-heartbeat tests pass. Also extend the README bullet at 602-603: encoding time adds to each block's first operation, and must stay well under the 30 s read-back and the operations' schedule-to-start.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9927148 and d8f0913. close() waits at most 10 seconds, the same limit as #311, then sends the clear; d8f0913 also sends it when the wait is interrupted (in a finally), as you suggested.

The clear has no details, so it skips the codec, and it becomes the last heartbeat the SDK waits for before it completes the Activity (_activity.py, "Do final completion"). Skipping the clear after the limit would leave a hung heartbeat as the last one, and the attempt still wouldn't end.

test_stateful_mcp_server_without_describe_permission[encode_stalls] makes every "may be open" encode hang. On the source before 9927148 it hits the 90-second test timeout; now the attempt fails at the read-back deadline and is retried. The finally has no test of its own. Both READMEs now say that encoding time delays each block's first operation and must stay well under the 30-second read-back and the operations' schedule-to-start timeout.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up in bf041c0: test_stateful_mcp_server_worker_shutdown_while_closing, ported from #311, now pins the finally. Every "may be open" heartbeat hangs in encoding, the close() limit is raised to 60 seconds, and a Worker shutdown while the attempt waits in close() must finish within 20 seconds. Without the finally, it fails with a TimeoutError.



@pytest.mark.timeout(90)
async def test_stateful_mcp_server_cancelled_after_refusal(client: Client):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (tests): a few of this round's branches are unpinned.

  • The non-permission describe wording. Replacing the _DESCRIBE_PERMISSION_ERRORS check with True, which gives every refusal the permission advice, leaves the describe, session and refusal tests green. TypeScript also asserts only 'permission to describe' (test-openai-agents.ts:983). A NOT_FOUND case that asserts 'could not describe this workflow run' and no 'permission' would pin it.
  • The timer-first race (comment on _mcp.py:639) and the _task_cancelling() guard (comment on _mcp.py:720) have no test.

This test does pin __aexit__: with b861ec6's change reverted, it fails with DID NOT RAISE WorkflowFailureError.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. The not_found cases (9927148) assert "could not describe this workflow run" and no "permission", in both languages; with the permission advice given for every code, they fail. The timer race and the guard are pinned by the new test_stateful_mcp_server_session_end_with_other_events (d8f0913).

- Python: a session that ended in the workflow task that ended the block, as
  when the block's last timer fired, makes the block raise
  DedicatedWorkerFailure, with no cause, where it raised a bare CancelledError:
  the SDK drops the session's failure when cleanup() cancels the handle.
  Blocks whose session never started keep their behavior (#391).
- TypeScript: cleanup() doesn't throw the session's DedicatedWorkerFailure
  when the scope that connected the server is cancelled, also when it runs in
  CancellationScope.nonCancellable().
- Python: close() sends the clear also when its wait is interrupted.
- Docs: the rollback warning covers any run whose session failed with
  DedicatedWorkerFailure and went on; the cancellation that wins at block exit,
  the retry-policy example, the Python 3.10 limit and encoding time are
  stated more exactly; heartbeat details are no longer called a marker; the
  Python provider docstring names a retried session.
- Tests: the session's end with the block's last timer or with a workflow
  cancel in one workflow task, cleanup() in a non-cancellable scope, and the
  queued-cancel tests wait for the server's cancel instead of a timer.
@campoy

campoy commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @DABH. All seven threads are answered in 9927148 and d8f0913 (head d8f0913), with a reply in each. 9927148 takes two fixes from the third review of #311, which you also raised here: the time limit on close()'s wait and the cancel count.

  • PR body: the main-history globs now leave out the marker histories, and the host-kill test is described as checking twice and killing once. The body also covers this round's changes.
  • Parity: Python's StatefulMCPServerProvider docstring now has TypeScript's sentence about a retried session. The timer race (Python) and the non-cancellable cleanup() (TypeScript) are fixed, and so is the cancel count after a caught cancel (Python).
  • Release notes: thanks for checking release_tool.py. The title stays, so the body's line reaches the notes only if whoever cuts the release edits the draft.
  • Early exit: filed as [Bug] openai_agents (Python): a stateful_mcp_server() block left before its first await raises a bare CancelledError #391, with a reproduction on main.
  • Tests: the "a caller still cancels a queued operation" tests (TypeScript, and Python's operation_cancelled) now let the session connect only once the server shows the call cancelled, instead of racing a timer. One CI run on 994f490 failed the TypeScript one on macOS.

Checks on d8f0913: Python make lint, make build and make test on 3.14.8 and 3.10.22 (481 passed each); TypeScript make lint (no errors), make test (272 passed) and make build; scripts/ci/check_conventions.py. The histories recorded on main for this PR's earlier replay checks still replay, as do the marker histories.

The session tests this change adds wait on timeouts, Worker shutdowns and
other Workers. Run alongside the rest of the file on 2 CPUs, they made other
tests' Workflows time out: main failed 0 tests in 3 runs, this change 14, 25
and 18, all with "Workflow execution timed out". They now run serially.
…tempt

Ported from the Google ADK fix's test (#311): every "may be open" heartbeat
hangs in encoding, the close() limit is 60 seconds, and a Worker shutdown
while the attempt waits in close() must finish within 20 seconds. Without the
clear in close()'s finally, it fails with a TimeoutError.
@campoy

campoy commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

About the macOS failures in one of the two CI runs on 994f490 and on d8f0913 ("a tool filter that throws while resuming from a RunState fails the run", "Local activity mode uses local activities for model calls"): I measured the TypeScript suite in 2-CPU containers, main (017d88a) and this PR run side by side, three runs each.

Build Failed tests per run Run time
main 0, 0, 0 393–526 s
d8f0913 14, 25, 18 481–565 s
main (again) 0, 0, 0 263–351 s
375ae12 0, 0, 0 375–468 s

Every failure on d8f0913 was "Workflow execution timed out", in stateful tests and in others. The session tests this PR adds wait on timeouts, Worker shutdowns and other Workers, and running them alongside the rest of test-openai-agents.ts starved the CPUs. 375ae12 runs those tests one at a time (test.serial), as google-adk does for its timing-sensitive cancellation tests. bf041c0 adds the close() shutdown test from the thread on _mcp.py:546.

A Python block whose session ended in the workflow task that ended the block
now raises DedicatedWorkerFailure with no cause, where earlier versions raised
a bare CancelledError, and that change is not gated. The README now says so in
the migration bullet and the replay and rollback paragraph, and the cleanup()
docstring says it applies to a session that ended for any reason.

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Third round, at head a8e897e: five commits on 994f490 (9927148 and d8f0913 address last round's review, 375ae12 runs the new TypeScript tests one at a time, bf041c0 adds a shutdown test, a8e897e edits the Python README and a docstring), and main has not moved (017d88a). On a worktree at the head, Python make lint is clean and make test gives 482 passed; TypeScript make lint has 0 errors (its 8 warnings are in files this PR does not touch) and make test gives 272 passed; check_conventions.py passes and CI is green on every cell. The earlier rounds' reproductions were rerun with real Workers against a local dev server, on this head and on main, on Python 3.14.3 and 3.10.20. New findings were reproduced the same way, or with histories recorded on one build and replayed with Replayer or Worker.runReplayHistory on the other, and coverage claims come from reverting each fix or guard. Refuted: an ungated command change for main histories beyond the disclosed race (of 138 Python histories recorded on main, the 4 that stop replaying are all that race, see the comment on README line 649; 59 of 60 TypeScript ones replay, and the exception is the contrived factory that throws a DedicatedWorkerFailure, unchanged since 994f490); a session cancellation_type (TRY_CANCEL, ABANDON or WAIT_CANCELLATION_COMPLETED) that makes an ordinary block exit raise; a Workflow cancel lost when it shares the timer's and the session's task (on 3.14, in all three orders); close()'s finally clearing the details of an attempt that connected; other tasks slipping into beat()'s task diff; cleanup()'s connect scope being anything but the scope connect() ran in (15 scope shapes, and every history self-replays); and a serial TypeScript test that depends on another. Also verified, after last round listed it as not verified: a ResetActivity during the read-back clears the details, and the retry connects. Not verified: Python 3.11 directly, SDK flag 2 (single-batch activations), a natural trigger of the wait_for race in the comment on _mcp.py:980, the author's 2-CPU timings, and Linux or Windows locally.

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Previous rounds. Round 1's blocking items are still fixed at this head:

  • Python (_mcp.py:610 in round 1): on 3.14 the recover-* runs, the three opcancel-* runs and the same-task cancel with the README's recovery all end CANCELED, and no new block is scheduled. On 3.10 they do too, except the same-task shape the README documents (but see the comment on _mcp.py:660).
  • TypeScript (stateful-mcp-client.ts:268 in round 1): the runner shape, the catch-then-listTools() shape, the session's end and the cancel in one Workflow Task, and cleanup() in a finally (default config and scheduleToStartTimeout: 0) all end CANCELED. 0eff9e9's logic still fails each with DedicatedWorkerFailure.

Last round's items, each rerun:

  • The timer-first race (P2): fixed. In all 13 timer-first runs (refused, shutdown and timeout endings; workflow.sleep and wait_condition) the block raises DedicatedWorkerFailure with no cause, the README's recovery runs, and an except asyncio.CancelledError handler no longer runs. A person-wait TimeoutError caught inside the block keeps its path. timer_first fails with the new branch removed. The docs state the condition too broadly (comment on README line 603).
  • The nonCancellable cleanup() (P2): fixed for the Workflow cancel. Last round's shape ends CANCELED, and its compensation runs (13 ActivityTaskFailed | 17 WorkflowExecutionCancelRequested | 21 ActivityTaskScheduled | 27 WorkflowExecutionCanceled), where 994f490's client fails it. A cancelled scope of the user's own around it still loses (comment on stateful-mcp-client.ts:222).
  • The rollback rule (P2): adopted in both READMEs and the body. d8f0913 adds one more way for a TypeScript run to go on (comment on the TypeScript README, line 531).
  • The stale cancel count (P3): fixed. Compensation code gets DedicatedWorkerFailure and runs its fallback, and a variant that lets that error leave the block now ends FAILED, so __aexit__ no longer drops it. operation_waiting_after_cancel pins it.
  • close()'s wait (P3): fixed. A hung first encode with a shutdown during the read-back now returns in 10.0 s (994f490: not within 45 s), a 20 s encode in 10.0 s (was 18.6 s), and a shutdown while already in close() at once. After the limit, the retry connected in all three runs. TypeScript has the same class with no bound and no doc (the same comment on the TypeScript README).
  • The README sentences (P3): the cancel-wins now names DedicatedWorkerFailure, the 3.10 sentence finishes its thought (see the comment on _mcp.py:660 for what it misses), and both READMEs now say 'heartbeat details' for the details and keep 'marker' for the patch marker. The bounded-retry example now uses the wording I suggested, which turns out to be wrong (comment on README line 603).
  • Unpinned branches (P3): the not_found cases and the one-task test pin what I listed. Each of the six Python fixes and the two TypeScript ones fails the test the body names when reverted, and the seven new or changed Python tests passed three serial runs under load. Guards added since then are unpinned (comments on the two test files).

Accepted as decided: the conversion stays ungated with the README route, and the title stays. All seven threads are answered. brianstrauch's caller-cancel shape still replays (the committed histories).

Where the problems cluster: this round's fixes hold, and nothing I found blocks. What is left is mostly precision: the docs describe the new race ending more broadly than it happens, my own bounded-retry wording from last round is wrong, and the upgrade and rollback notes each miss one narrow class of run. Below that are edge cases at the cancellation boundary: a user-cancelled TypeScript scope around a nonCancellable cleanup(), Python 3.10, where the cancel count never rises, and the cancellation checks after the read-back and connect() that TypeScript has and Python lacks. Then a TypeScript codec hang with neither a bound nor a doc, a small TypeScript retention, and a few unpinned guards.

Approving: round 1's blocking items and last round's P2s are fixed at this head, CI is green, and what remains is non-blocking docs, tests and edge cases.

PR body:

  • Line 94, 'Without cleanup()'s check of the caller's scope it fails with DedicatedWorkerFailure', no longer holds since d8f0913 (comment on the TypeScript test). Line 112's list of untested branches should also name Python's started and cancel-count guards in cleanup() and that TypeScript check.
  • Line 54, 'replay on this change, as before': except the race shape of line 35.
  • Line 91: the permission advice is given for UNAUTHENTICATED too, as line 7 says.
  • Line 34's 'that unmarked block-exit failure' has no antecedent until line 35.
  • Line 86: on 3.10, cancel_with_refusal expects the recovery instead (line 20 says why).

Pre-existing, not from this PR (each also on main 017d88a; worth issues):

  • A Workflow cancel that reaches the session while cleanup() waits for it is swallowed, and the run completes (_mcp.py:671-673, if is_cancelled_exception(e): pass). Shapes: a Signal that ends the block in the same Workflow Task as the cancel (it also happened with the Workflow Worker running, the Signal and the cancel sent 0.2 s apart), or any cancel while a WAIT_CANCELLATION_COMPLETED session acknowledges the block's cancel. On 3.11 and later, if _cancel_requests() > cancels: raise asyncio.CancelledError() from e ends both CANCELED and leaves normal exits and the timer race alone (92 MCP and replay tests pass), but it changes replay for open runs that hit this, so it needs workflow.patched().
  • A Workflow reset to a point inside an open block gives the new run a new, empty server with no error (the head returned stored@server#1 | EMPTY@server#2, and main also returned EMPTY). Both READMEs cover Activity resets only; a sentence would help.
  • A WAIT_CANCELLATION_COMPLETED server_session_config plus an eviction while cleanup() waits logs 'Eviction processed, but 2 tasks remain' and keeps the slot (temporalio 1.34.0).

Parity: apart from the documented and SDK-driven differences (Python decides the block exit from the exception leaving it and TypeScript from scopes; the race exists only in Python; TypeScript's scopes stay cancelled), the comments cover what remains: the user-cancelled scope (TypeScript), the cancellation checks after the read-back and connect() (Python), the encode bound (Python only), and a direct cleanup() after a cancel (Python raises, TypeScript doesn't).

Comment thread python/openai_agents/README.md Outdated
`ApplicationError(type="DedicatedWorkerFailure")`, which the block now raises
after a refusal. A session that fails for another reason, such as one with a
one-attempt `server_session_config` retry policy, or one whose attempts all
fail before connecting, still makes the block raise `ActivityError`, unless

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (docs, non-blocking): two clauses of this bullet describe endings that don't happen, and the second recurs at lines 571-572, in the cleanup() docstring and in body line 22.

  1. 'one whose attempts all fail before connecting, still makes the block raise ActivityError' is the wording I suggested last round, and it is wrong for an attempt that times out or loses its host before connecting: that attempt leaves 'may be open', so the next one is refused. With maximum_attempts=2, a 5 s start-to-close and a connect() that takes 12 s, the head raises ApplicationError(DedicatedWorkerFailure) <- ActivityError <- DedicatedWorkerFailure('An earlier attempt ... ended (it lost its worker, timed out, or was reset) without confirming ...'), which an except ActivityError misses. Main raised ActivityError <- 'Cannot connect to an already running server'. Say 'one whose attempts all fail with an error before connecting (a factory call or first connect() that raises)'.
  2. 'unless it ended in the workflow task that ended the block ...: then the block raises DedicatedWorkerFailure with no cause' holds only when the block's last timer fired ahead of the session's end in that task. Same task, session's end first (activation ['resolve_activity(seq=1,failed)', 'fire_timer(seq=1)']): a refused session raises DedicatedWorkerFailure <- ActivityError <- DedicatedWorkerFailure(opened ...), with its cause, and a one-attempt session that timed out raises ActivityError <- TimeoutError(StartToClose), so the README's except ApplicationError recovery does not run and the run fails. A block that a Signal, an Update, an activity result or a child result ends in the session's last task keeps the cause too, whichever comes first in the task (with a one-attempt shutdown it raises ActivityError(WorkerShutdown)), and so does a wait_condition timeout on 3.10.

Suggested, here and at 571-572: 'none if the block's last timer fired in the workflow task that brought the session's end, ahead of it, since the SDK then drops it'. The docstring (_mcp.py:641-643, 'for any reason') and body line 22 need the same narrowing.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed both in 891f428, with your wording. The bullet now says 'fail with an error before connecting (a factory call or first connect() that raises)'. The no-cause case now reads 'the block's last timer fired in the workflow task that brought the session's end, ahead of it' everywhere it appears: lines 571-572, this bullet, the cleanup() docstring and its comment, and body line 22.

Comment thread python/openai_agents/README.md Outdated
`openai-agents-stateful-mcp-session-watch`, which it does at its first
operation whose `config` has neither timeout. Histories recorded on an earlier
version have no marker, so they schedule such operations as before and replay
on this version. One change is not behind the marker: the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (docs, replay, non-blocking): this note names only runs that caught the bare CancelledError, but main runs that hit the race and failed because their handler let it through also stop replaying, and 'One change is not behind the marker' is not true as written.

Recorded on main (017d88a), holding the workflow worker until TimerFired and a one-attempt session's end were both in history, timer first, then replayed on the head:

  • except asyncio.CancelledError around the block, then an activity (the case this note names): [TMPRL1100] Nondeterminism error: Fail workflow machine does not handle this event: HistoryEvent(id: 19, ActivityTaskScheduled), for the open run and the closed one.
  • The README's own except ApplicationError recovery, or except Exception: main failed the run with CancelledError: Cancelled; the head catches the DedicatedWorkerFailure and goes on, so replay fails with Activity machine does not handle this event: HistoryEvent(id: 19, WorkflowExecutionFailed). These runs are closed, so this shows up in queries of those runs and in replay tests over production histories, not in running workflows.
  • No catch: replays, since both builds fail the run.

Of last round's 138 Python histories recorded on main, these four are the only ones that stop replaying, and with d8f0913's except asyncio.CancelledError branch removed they all replay again.

On the wording: the conversion of a refusal and the cancel-wins in __aexit__ are ungated too (lines 659-663 and body lines 22 and 34 say so). The sentence means the one change that reaches earlier histories. Suggested: 'Only one change reaches histories recorded on an earlier version: ... A run that hit this and caught the bare CancelledError, or that failed with it although it catches ApplicationError or Exception around the block, schedules different commands on this version: let open ones finish before upgrading, and expect replays of closed ones (queries, replay tests) to fail.' Body line 35 likewise.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taken in 891f428, close to your text. The paragraph now says earlier histories replay 'with two exceptions'. The first is the timer race: a run that caught the bare CancelledError, or that failed with it although it catches ApplicationError or Exception around the block. The second is the 3.10 cases from your _mcp.py:660 comment. Then: let open runs finish before upgrading, and expect replays of closed ones (queries, replay tests) to fail. I wrote 'two exceptions' rather than 'only one change' because of the 3.10 replay you found. Body line 35 says the same.

``ApplicationError(type="DedicatedWorkerFailure")`` with the session's
``ActivityError`` as its cause. If the session ended, for any reason, in
the workflow task that ended the block, raises it with no cause, since
the SDK dropped the session's result.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (docs, parity, non-blocking): this docstring should also say that a cancellation wins only when it leaves the async with block: cleanup() called directly after a workflow cancel raises the session's DedicatedWorkerFailure over the cancel, where TypeScript's cleanup() lets the cancelled scope win.

Head, connect()/cleanup() in a try/finally (or an explicit server.cleanup()), a refused retry, then a workflow cancel: FAILED with DedicatedWorkerFailure, cause chain intact; with the README's recovery around it, COMPLETED, so the cancel is lost. The same body with async with ends CANCELED. Not new (0eff9e9 already behaves this way) and unlikely, since stateful_mcp_server() returns an AbstractAsyncContextManager, but cleanup() is on the object it yields, and openai-agents documents connect()/cleanup() and MCPServerManager. A cancel-count check at entry would misfire after a caught cancel (last round's stale-count class), so a sentence is the right fix.

The sentence before it, 'If the session ended, for any reason, in the workflow task that ended the block', needs the narrowing from the comment on README line 603.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 891f428: 'A cancellation wins over this failure only when it leaves the async with block: cleanup() called directly after a workflow cancellation raises it.' The sentence before it is narrowed as in the README comment.

if (
not started
or not session.cancelled()
or _cancel_requests() > cancels

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (Python 3.10, non-blocking): this count never rises on 3.10, so when a workflow cancel lands in the workflow task in which the session handle ends cancelled, the block raises DedicatedWorkerFailure in place of the cancel, in shapes that main ended CANCELED on 3.10.

Each in one workflow task (the worker held until the events were in history), head against main, both on 3.10.20:

  • A Signal ends the block, a one-attempt session ends (graceful shutdown) and the workflow is cancelled: head FAILED with DedicatedWorkerFailure: ... has ended, with no cause; main CANCELED.
  • A WAIT_CANCELLATION_COMPLETED session config whose cancellation, from the block's exit, completes in the cancel's task (activation ['resolve_activity(seq=1,cancelled)', 'cancel_workflow']): head FAILED with 'The stateful MCP server session activity has ended, so no worker serves this server's operations.', which also gives the wrong reason, since the block cancelled it; main CANCELED.
  • A Signal, a refusal and a cancel with the README's recovery: COMPLETED, so the cancel is lost.
  • Replay: main 3.10 histories of the first two shapes whose except asyncio.CancelledError ran a compensation activity fail on the head on 3.10 with [TMPRL1100] ... HistoryEvent(id: 19, ActivityTaskScheduled). They replay on the head on 3.14.

On 3.14 all of these end CANCELED. README lines 639-643 cover this only loosely, inside the operations paragraph, and the upgrade note covers only runs that 'caught the bare CancelledError'. I found no clean 3.10 code fix. Extend the 3.10 sentence to block exits (after a Signal or Update, or a WCC session whose cancellation completes in that task), and say that open 3.10 runs that caught such a cancellation and went on fail replay after the upgrade.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented in 891f428, as you suggested. The 3.10 sentence now also covers a block that ends in that task (after a Signal or an Update, or with a WAIT_CANCELLATION_COMPLETED session whose cancellation completes in it). The replay paragraph says such 3.10 runs can fail replay after the upgrade. On 3.10, the new signal_with_refusal case (next thread) expects the recovery.

try:
# No server is built before the Temporal server holds the first
# heartbeat, which says a session may be open.
await heartbeats.wait_until_stored()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (non-blocking): unlike TypeScript (stateful-mcp-provider.ts:338 and :354), the session activity doesn't check for a cancellation after the read-back or after connect(), so a dropped cancellation lets an attempt connect and serve after a worker shutdown, block exit, pause or reset.

Two ways it gets dropped:

  • On Python 3.10 and 3.11, asyncio.wait_for (line 530) returns the inner result and drops a cancellation that lands as the confirming describe returns (3.12 rewrote it). On 3.10, with the SDK's own worker-shutdown cancel issued at that moment: factory called (attempt=1, is_cancelled=True), connect server#1, and the session activity was still running 5 s later, 3 runs of 3. The window is a few loop iterations per session start, so this is rare.
  • A connect() that catches CancelledError, on the head and on main alike: connect ... swallowed CancelledError, then worker.shutdown() still waiting after 20 s, because the dedicated worker serves until the attempt times out (one hour by default). That contradicts README line 575, 'a worker shutdown before the server connected connects again'.

Fix (tested): if activity.is_cancelled(): raise asyncio.CancelledError() after wait_until_stored() and after server.connect(), before record_opened(). With it, the 3.10 race attempt stops before the factory with its details cleared; the swallowing connect() shuts down in 3.3 s with attempt 2 scheduled and details [], so the next worker connects, as the README says; and the 27 stateful_mcp tests pass. It is activity code only, so replay is unaffected.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 891f428, as you tested it: if activity.is_cancelled(): raise asyncio.CancelledError() after wait_until_stored() and after server.connect(), before record_opened(), as in TypeScript. A new case, test_stateful_mcp_server_session_retried[shutdown_before_connect_ignored], has a connect() that swallows the shutdown's cancellation, and the retry must connect on the next worker. Without the check after connect(), the case fails: the worker's shutdown hangs until the test times out. Like TypeScript's, the check after the read-back has no test of its own; the body lists both.


@pytest.mark.timeout(90)
@pytest.mark.parametrize("case", ["timer_first", "cancel_with_refusal"])
async def test_stateful_mcp_server_session_end_with_other_events(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (tests, non-blocking): cleanup()'s new started and cancel-count guards (_mcp.py:658 and :660) are unpinned: with either one removed, the 27 stateful_mcp tests, and the 56 stateful, MCP and replay tests, still pass.

  • Without not started, async with stateful_mcp_server(...): pass, and a body that raises first, leave the block with DedicatedWorkerFailure: ... has ended, so no worker serves ... instead of the bare CancelledError that body line 111 promises (as on main, [Bug] openai_agents (Python): a stateful_mcp_server() block left before its first await raises a bare CancelledError #391). The message is wrong too, since the session never started, and an early-exit history that catches CancelledError would stop replaying.
  • Without the count check, on 3.14, a block that a Signal ends in the task that brings the refusal and a workflow cancel ends FAILED with DedicatedWorkerFailure instead of CANCELED (COMPLETED with the README's recovery), and so does the WCC shape from the comment on _mcp.py:660.

A case here in which a Signal ends the block in the task that brings the refusal and a cancel, expecting CANCELED on 3.11 and later, plus an async with ...: pass case asserting the bare CancelledError, would pin both.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pinned both in 891f428. signal_with_refusal joins test_stateful_mcp_server_session_end_with_other_events: a Signal ends the block in the workflow task that brings the refusal and a cancel. It expects CANCELED on 3.11 and later, and the recovery on 3.10. Without the count check it ends through the recovery on 3.14. test_stateful_mcp_server_empty_block asserts the bare CancelledError from async with ...: pass (#391). Without not started it fails with DedicatedWorkerFailure.

) {
// A cancellation of the caller wins over the session's failure, as
// when cleanup() runs in a finally after the caller was cancelled.
if (!CancellationScope.current().consideredCancelled && !connectScope?.consideredCancelled) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (non-blocking): this check reads the scope that runs cleanup() and the one that called connect(), so a cancelled scope between them still loses to a refused session. An example is a 'stop' scope that a Signal cancels, with finally { await CancellationScope.nonCancellable(() => server.cleanup()) } inside it. This is the narrower remainder of last round's comment on line 219; the Workflow-cancel shape is fixed.

Probe: connect() at the Workflow's top, the work in stop = new CancellationScope() cancelled by a Signal, the nonCancellable cleanup() in its finally, catch (isCancellation) around it; a refused retry, then the stop Signal.

  • Head (and 994f490): stop scope failed: ApplicationFailure(DedicatedWorkerFailure): ...has ended ... <- ActivityFailure, and the stop handler never runs.
  • Main: cleanup returned, stop handled: cancelled(CancelledFailure), then the follow-up.

README line 518 states the rule exactly, so this is a gap rather than a wrong doc. Walking every ancestor of current() would be wrong: the root scope stays cancelled after a caught Workflow cancel, so it would also swallow the refusal of a server that compensation code connects and cleans up in its own nonCancellable scopes, which the head correctly reports. Fix (tested): also count cancelled scopes that enclose cleanup() but not connect():

function cancelledBelow(scope: CancellationScope, connectScope: CancellationScope | undefined): boolean {
  const connectLine = new Set<CancellationScope>();
  for (let s = connectScope; s; s = s.parent) connectLine.add(s);
  for (let s: CancellationScope | undefined = scope; s && !connectLine.has(s); s = s.parent) {
    if (s.consideredCancelled) return true;
  }
  return false;
}

With && !cancelledBelow(CancellationScope.current(), connectScope) added here, the stop shape is handled, the compensation server's refusal still throws, the other scope shapes probed and the timer-first refusal are unchanged, and the 20 Stateful MCP: tests pass.

Separately (docs): because the root scope stays cancelled, after a caught Workflow cancel cleanup() swallows a refusal for the rest of the run, also from nonCancellable and also when the connect scope was a branch the code cancelled. A Workflow that catches the cancel and completes then never sees the refusal: agents-core 0.14.3's default tool error function turns an MCP tool's DedicatedWorkerFailure into tool output for the model (a run with such a tool completed with finalOutput = "done"), so cleanup() is the only place it would surface. Python raises it at block exit in the same shape. Say so at README line 518 and in the mcp-types.ts doc, which also omits that other session failures still throw the ActivityFailure.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taken in 891f428: cancelledBelow() as you wrote it, added to the check. The cleanup() test has a third case with your stop-scope shape: a Signal cancels the work's scope after the refusal, with a non-cancellable cleanup() in its finally, and the Workflow must return 'stopped'. With a8e897e's client it fails with DedicatedWorkerFailure. The docs part is in the README paragraph at line 518 and in mcp-types.ts. After a caught Workflow cancel the root scope stays cancelled, so cleanup() throws no refusal for a server connected outside nonCancellable(). The agent SDK's default tool error handling also turns a failed MCP tool call into tool output, so such a refusal can go unseen. Both docs, and cleanup()'s own, now also say that a session that failed for another reason throws its ActivityFailure.

if (!operation) {
throw scheduled.error;
}
void this._sessionEnded!.then(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (non-blocking): this handler is added to the session's promise once per operation and stays until the session ends. Its closure shares this function's context with scheduled, so every operation's result on this path stays reachable for the session's lifetime. Python removes its callback in a finally (_mcp.py:758-759). In a copy of this closure structure under node --expose-gc, 20 of 20 results survived GC with the handler, against 1 of 20 without it. Only runs with the patch marker (scheduleToStartTimeout: 0) take this path, and the growth is per cached Workflow, but long sessions with large tool results add up. Clearing the shared reference once operation is read (scheduled.operation = undefined) moves no step or command. One listener per session over a set of scopes would also work, but it changes the order of the cancellations' microtasks, so re-run the marker histories if you go that way.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 891f428: scheduled.operation = undefined right after it is read. This moves no step or command, and the marker histories still replay.

Comment thread typescript/openai-agents/README.md Outdated

Only the session Activity's Worker serves the server's operations. With a schedule-to-start timeout (the default `config.scheduleToStartTimeout` is 30 seconds), an operation fails with `DedicatedWorkerFailure` when it expires. With `scheduleToStartTimeout: 0`, an operation fails with `DedicatedWorkerFailure` as soon as the session Activity has ended, for example after a graceful shutdown of its Worker, and an operation still waiting then is cancelled. A caller's own cancellation still cancels the operation, and wins over the session's end.

A run follows its session this way only once it records the patch marker `openai-agents-stateful-mcp-session-watch`, which it does at its first operation with `scheduleToStartTimeout: 0`. Histories recorded on an earlier version have no marker, so they schedule such operations as before and replay on this version; a run that continues on this version records the marker at its next such operation. A run with the marker fails replay on an earlier version, and so can any run whose session failed with `DedicatedWorkerFailure` (a refused retry or a refused describe) and that then went on, whether it caught the failure `cleanup()` throws or a cancellation, so do not roll back while such runs are open. Drain the earlier version's Workers before starting this one: while Workers of both versions run, a run whose session gets a refusal can fail replay when it moves from one to the other.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (docs, non-blocking): the rollback sentence lists two ways a run 'went on', and d8f0913 adds a third; and the codec bullet at line 526 doesn't say that a hung encode keeps the attempt from ending and a Worker shutdown from finishing.

  1. cleanup() now returns silently when the scope that called connect() was cancelled, so a run can go on without catching anything. Recorded on the head: connect() in a branch scope, a refused retry, the branch cancelled after its work (as after a race), cleanup() in the root scope with no try/catch, then a follow-up Activity: COMPLETED. Replayed on main: [TMPRL1100] Nondeterminism error: Fail workflow machine does not handle this event: HistoryEvent(id: 21, ActivityTaskScheduled). The same run on 994f490's client failed at cleanup(), and it replays on main. Ending the clause at 'and that then went on' covers every case (body line 34 too).
  2. Python waits at most 10 s for heartbeat encodes, and its README says so. TypeScript's Worker sends a failed Activity's result only after its last heartbeat flushes (@temporalio/worker 1.24.0, lib/worker.js:821-833), one heartbeat per Activity at a time. So with a codec whose encode never returns for the 'may be open' heartbeat, the attempt's failure is never sent: at 36 s the session's attempt 1 was still STARTED with no lastFailure (its read-back had given up at 30 s), the run failed at the first operation's schedule-to-start timeout with nothing about encoding in the chain, and the Worker's run() had not returned 75 s after shutdown(). Main, and the head without the stall, returned in 4-7 ms; without a heartbeat timeout main sent no heartbeats, so it wasn't exposed. The plugin can't bound this, so add a sentence at line 526 and consider an SDK issue for a bounded flush.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both in 891f428.

  1. The rollback clause now ends at 'and that then went on', in the README and in body line 34.
  2. The codec bullet now says: 'The Worker sends a failed Activity's result only after its last heartbeat, so an encode that never returns keeps the session Activity's attempt from ending and a Worker shutdown from finishing; the plugin can't bound this.' Whether to file an SDK issue for a bounded flush is a question for the user; I'll link it here if we file one.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filed the SDK side as temporalio/sdk-typescript#2648, with a one-file repro without the plugin: the Activity heartbeats once and then throws, and a codec that never finishes encoding that heartbeat keeps the failure from being sent and worker.run() from returning after shutdown().

let factoryCalls = 0;
const describe = async (): Promise<never> => {
if (kase === 'refused' || kase === 'not found') {
const [code, status] = kase === 'refused' ? [7, 'PERMISSION_DENIED'] : [5, 'NOT_FOUND'];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (tests, non-blocking): this case throws a ServiceError with gRPC code 5, a shape the client never produces for NOT_FOUND, so the branch that handles the real one is unpinned; and since d8f0913 cleanup()'s check of its own scope is unpinned too.

  • @temporalio/client 1.24.0 turns NOT_FOUND into WorkflowNotFoundError (rethrowGrpcError in workflow-client.js). With the instanceof WorkflowNotFoundError || NamespaceNotFoundError branch (stateful-mcp-provider.ts:60-62) disabled, both describe tests still pass, and a real NOT_FOUND would then be retried until the 30 s deadline. Throw new WorkflowNotFoundError(...) here, or add it as a case.
  • With CancellationScope.current().consideredCancelled removed from stateful-mcp-client.ts:222, both 'a Workflow cancellation wins over a refused session in cleanup()' variants stay green: connect() runs in the root scope there, so the connect-scope check alone suppresses the throw (hence body line 94). A case that calls cleanup() inside a cancelled child scope, after a refusal and with connect() in the root scope, expecting no throw, would pin it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both in 891f428. The not found case now throws WorkflowNotFoundError, as the client does. With the instanceof branch disabled, it fails: the attempt is retried until the deadline. For cleanup()'s scope check, the new stop-scope case (see the thread on stateful-mcp-client.ts:222) pins the scopes between connect() and cleanup(). With cancelledBelow() in place, the current() check on its own matters only when connect() ran in a non-cancellable scope inside the scope that calls cleanup(), so the body lists it as untested.

Python: the session activity checks for a cancellation after the
read-back and after connect(), as TypeScript does. Tests pin cleanup()'s
started and cancel-count guards, and the check after connect().

TypeScript: cleanup() also lets a cancelled scope between connect() and
cleanup() win over a refused session. The operation path no longer keeps
each result alive until the session ends. The NOT_FOUND describe test
throws the WorkflowNotFoundError the client throws.

Docs: the timer race's wording, the replay and rollback notes, Python
3.10's block exits, a direct Python cleanup() after a cancel, a Workflow
reset inside an open block, TypeScript's root scope after a caught
cancel, and a TypeScript codec whose encode never returns.
# Conflicts:
#	python/openai_agents/tests/test_openai.py
#	python/openai_agents/tests/test_openai_replay.py
#	typescript/openai-agents/src/__tests__/test-openai-agents.ts
#	typescript/openai-agents/src/__tests__/workflows/openai-agents.ts
@campoy

campoy commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the third round. The threads are answered inline; everything is in 891f428, and ab88cae then merges main (no conflicts outside tests). The items in the summary:

PR body. All five are fixed:

  • Line 94 no longer claims the caller's-scope check is pinned. It now describes the new stop-scope case. The untested list (line 112) names the check after the read-back in both languages, and TypeScript's current() check, which on its own matters only when connect() ran in a non-cancellable scope inside the one that calls cleanup(). Python's started and cancel-count guards are pinned now, so they aren't on the list.
  • Line 54 says that none of those histories hits the timer race.
  • Line 91 names UNAUTHENTICATED too.
  • Lines 34 and 35: line 34 names "the no-cause DedicatedWorkerFailure of the timer race (next item)", and line 35 has your replay wording plus the 3.10 case.
  • Line 86 says that on 3.10 cancel_with_refusal, and the new signal_with_refusal, expect the recovery.

Pre-existing.

  • The cancel lost while cleanup() waits: it is filed for Google ADK as [Bug] google_adk: a stateful MCP block can lose a cancellation while it exits #394, which notes this plugin has the same code. The body's "Not covered" list links it, and this PR doesn't change it.
  • A Workflow reset inside an open block: both READMEs now say it gives the new run a new, empty server, with no error.
  • The WAIT_CANCELLATION_COMPLETED session config with an eviction during cleanup(): not changed here. Next I'll try to reproduce it without the plugin, then file it in sdk-python if it reproduces there, or here if it doesn't. I'll link the issue in this PR.

Parity. The comments cover the four gaps: the user-cancelled scope (cancelledBelow()), the checks after the read-back and connect() (now in Python too), the encode bound (TypeScript now documents it), and a direct Python cleanup() after a cancel (docstring).

# Conflicts:
#	python/openai_agents/tests/test_openai.py
@campoy

campoy commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up on the eviction item from my summary reply: a plain workflow without the plugin reproduces it on temporalio 1.34.0 (an activity cancelled with WAIT_CANCELLATION_COMPLETED, then an eviction while the workflow waits: "Eviction processed, but 2 tasks remain", and the next workflow on that worker never runs). It is temporalio/sdk-python#1938, fixed by temporalio/sdk-python#1947 in 1.35.0, where the same script passes. So there is nothing new to file; the body's "Not covered" list links it.

@campoy
campoy merged commit a6081c7 into main Nov 3, 2026
19 checks passed
@campoy
campoy deleted the fix/openai-agents-stateful-mcp-session-replaced branch November 3, 2026 23:04
campoy added a commit that referenced this pull request Nov 16, 2026
#565)

## What was changed

Replay is promised only within a major version now. A history recorded
on a 1.x release must replay on every later 1.x release, and nothing is
promised from 1.x to 2.x. So why does CI still replay 1.x histories on
code that's heading to 2.0? It shouldn't, and this PR stops it.

- Each plugin's committed histories move into a folder per major,
`histories/<major>.x/`.
- Each replay test gets a `REPLAY_MAJOR` constant (`ReplayMajor` in C#)
and loads only that folder. Older majors' folders stay in the repo, but
they don't replay.
- AGENTS.md gets the rule, next to the one about gating history changes.

A plugin's current major is the major of its next release. Here's what I
used:

| Plugin | Latest release | Current major | Replays | Kept, not replayed
|
| --- | --- | --- | --- | --- |
| `python/openai_agents` | 1.1.0, then `Breaking:` commits | 2 | 4
histories in `2.x/` | 12 in `1.x/` |
| `typescript/openai-agents` | 1.24.0 on npm (published from the SDK
repo), then `Breaking:` commits | 2 | 1 in `2.x/` | 4 in `1.x/` |
| `typescript/vercel-ai-sdk` | 1.0.0, then `Breaking:` commits | 2 |
none | 3 in `1.x/` |
| `python/google_genai` | 1.0.0rc1 | 1 | 1 in `1.x/` | 1 in `0.x/` |
| `typescript/strands-agents` | none from this repo (npm has 1.21.0 to
1.24.0 from the SDK repo); 2.0.0 next | 2 | 4 in `2.x/` | 1 in `1.x/` |
| `typescript/google-adk` | 0.1.0; 1.0.0 next | 1 | 2 re-recorded in
`1.x/` | 2 in `0.x/` |
| `python/google_adk` | 0.0.1; 1.0.0 next | 1 | none | 7 in `0.x/` |
| `python/strands_agents` | 0.1.0; 1.0.0 next | 1 | 4 in `1.x/` | 5 in
`0.x/` |
| `python/deepagents` | 0.0.3; 1.0.0 next | 1 | none | 3 in `0.x/` |
| `java/google-adk`, `dotnet/microsoft-agent-framework`,
`python/microsoft_agent_framework` | below 1.0, not 1.0 next | 0 | all,
in `0.x/` | none |

A history recorded on `main` before a breaking fix goes with the release
whose behavior it recorded. So the five OpenAI Agents Python histories
from before #204, #373 and #426, and the four TypeScript ones from
before #373, are 1.x histories. Strands Python's four MCP histories were
recorded after #190 moved its MCP Activities to `temporalio-mcp`, code
that 0.1.0 never had, so they're 1.x histories too. Strands TypeScript's
`hello-agent-before-model-config` was recorded before #158, so it has
1.24.0's behavior and is a 1.x history. Its other four were recorded
after #158, so they're 2.x.

Tests that replayed only older-major histories go: Vercel AI SDK's three
committed-history tests, Google GenAI's `legacy_ascii_files` replay,
Google ADK Python's two replay tests with their workflows, Strands
Python's `test_legacy_history_replay.py` and
`test_model_context_overflow_legacy_replay.py`, Deep Agents'
`test_legacy_cache_replay.py`, and Strands TypeScript's test that its
history from before #158 fails to replay. The OpenAI Agents lists keep
only the current major's files. Google ADK TypeScript's replay test
checks a live run against a checked-in fixture, so I recorded its two
fixtures again into `1.x/` with its own `UPDATE_ADK_HISTORIES=1`.

`go/googleadk` doesn't change: it has no committed histories, and its
replayer tests replay runs the same test just recorded.

## Why?

We decided that replay is promised only within a major. But CI still
replayed 1.x histories, so a fix for 2.0 had to keep 1.x runs replaying
behind a patch, even though we don't promise that. With this PR, the
next one can remove those patches from OpenAI Agents Python before 2.0.0
ships.

## Checklist

1. No issue.

2. How was this tested:
- Python, for each of the six plugins: `make sync`, `make format`, `make
lint`, and the tests that read committed histories (3, 7, 43, 11, 4 and
42 passed).
- TypeScript, for each of the four plugins, in Docker with Node 24:
`make sync`, `make lint`, and the test files that read committed
histories.
- `check_conventions.py` passes, and `detect_changes.py` selects the 12
plugins.
- After moving the 1.0-next plugins to major 1: Google ADK Python `make
format`, `make lint` and `make test` (321 passed, 6 skipped); Google ADK
and Strands TypeScript `make lint` and their replay tests, in Docker
with Node 24.
- After moving Strands Python and Deep Agents to major 1 and merging
`main`: `make lint` and `make test` for both (277 and 261 passed).
- After moving Strands TypeScript to major 2: `make lint` and its two
replay test files, in Docker with Node 24 (8 passed).
- Java and .NET didn't run locally (no JDK or .NET SDK on this machine).
CI runs them.

3. Any docs updates needed? AGENTS.md has the rule. The Microsoft Agent
Framework Python histories README says where recordings go now.
campoy added a commit that referenced this pull request Nov 16, 2026
Replay is promised only within a major, so 2.0 doesn't need the three
patches that only kept runs from before their fixes replaying:
openai_agents.refuse-run-model-provider (#204),
openai-agents-stateful-mcp-session-watch (#373) and
openai_agents.run-caller-agents (#426). Every run now takes the new path:
RunConfig.model_provider is refused, stateful MCP operations without a
timeout watch their session, and runs use your agents, not copies.

_convert_agent and the tests that only covered the agent copies go too.
The three 2.x histories that had patch markers are recorded again without
them, since a marker with no matching patched() call fails replay.
campoy added a commit that referenced this pull request Nov 16, 2026
Replay is promised only within a major, so 2.0 doesn't need the three
patches that only kept runs from before their fixes replaying:
openai_agents.refuse-run-model-provider (#204),
openai-agents-stateful-mcp-session-watch (#373) and
openai_agents.run-caller-agents (#426). Every run now takes the new path:
RunConfig.model_provider is refused, stateful MCP operations without a
timeout watch their session, and runs use your agents, not copies.

_convert_agent and the tests that only covered the agent copies go too.
The three 2.x histories that had patch markers are recorded again without
them, since a marker with no matching patched() call fails replay.
campoy added a commit that referenced this pull request Nov 16, 2026
… watch gate before 2.0

Replay is promised only within a major, and the next OpenAI Agents
TypeScript release is 2.0.0. The openai-agents-stateful-mcp-session-watch
patch (#373) only kept 1.x runs scheduling operations without a
schedule-to-start timeout the old way, so it goes: such operations always
watch their session now.

The 2.x caller-cancel history is recorded again without the marker, since
a marker with no matching patched() call fails replay.
campoy added a commit that referenced this pull request Nov 16, 2026
…watch gate before 2.0 (#587)

## What was changed

The next OpenAI Agents TypeScript release is 2.0.0, so its current major
is 2, and replay is promised only within a major. The
`openai-agents-stateful-mcp-session-watch` patch from #373 only keeps
1.x runs scheduling operations without a schedule-to-start timeout the
old way, so let's remove it before 2.0. Such operations always watch
their session now. #566 removes the same gate from the Python plugin.

The `2.x/` caller-cancel history had the patch marker, so I recorded it
again without it as `stateful-mcp-caller-cancel.json`. Why? A history
with a marker and no matching `patched()` call fails replay with
`[TMPRL1100] Non-deprecated patch marker encountered`.

The README drops the marker note and says which 1.x runs don't replay.

## What will you notice? (Breaking)

Some 1.x runs with stateful MCP operations that had
`scheduleToStartTimeout: 0` don't replay on 2.0. For example, a run
whose caller cancelled operations on two servers, one of them with
`scheduleToStartTimeout: 0`, fails with `[TMPRL1100]` because its
follow-up Activities come in another order. Let such runs finish on 1.x
Workers before you upgrade, or keep them there with Worker Versioning.

A run on a `main` build since #373 that scheduled such an operation
recorded the marker, so it doesn't replay either. No release wrote that
marker.

## Why?

We decided that replay is promised only within a major, and that a gate
that only protects an older major's runs is removed before the next
major ships. OpenAI Agents TypeScript's next release is 2.0.0, so this
gate goes before it.

## Checklist

1. No issue.

2. How was this tested:
- `make lint` and `make test` for `typescript/openai-agents`, in Docker
with Node 24: 335 tests passed. Lint shows the same 8 warnings as on
#565, in files this PR doesn't touch.
- Replay, across builds. I recorded the caller-cancel run on #565 and on
this PR with #373's recorder, which keeps both sessions open and cancels
the caller while both calls are queued. Then I replayed both, the four
committed 1.x histories, the committed `2.x/` marker history and a
history with a renamed Activity on both builds.
- On this PR, only these fail, each with `[TMPRL1100]`: the run from
#565 and the committed marker history (`Non-deprecated patch marker
encountered`), the 1.x caller-cancel history, and the renamed Activity.
The other three 1.x histories replay (a gather with and without
`scheduleToStartTimeout: 0`, and a cancel with it), and so does this
PR's run.
- Rollback to #565: this PR's caller-cancel run fails with
`[TMPRL1100]`, because the old path resumes the follow-ups in the other
order.

3. Any docs updates needed? The README changes are here.
campoy added a commit that referenced this pull request Nov 16, 2026
…replaying (#566)

## What was changed

Three patches on `main` exist only to keep runs from before their fixes
replaying. No release wrote their markers: PyPI has 1.0.0 and 1.1.0, and
both shipped before these fixes. With replay promised only within a
major (#565), 2.0.0 doesn't need them. So let's remove them before it
ships:

- `openai_agents.refuse-run-model-provider` (#204): `Runner.run` always
refuses `RunConfig.model_provider`.
- `openai-agents-stateful-mcp-session-watch` (#373): a stateful MCP
operation with neither a schedule-to-start nor a schedule-to-close
timeout always watches its session.
- `openai_agents.run-caller-agents` (#426): runs always use your agents,
not copies. `_convert_agent` goes, and so do
`test_model_conversion_loops` and the four run-state tests that called
it directly.

The three 2.x histories that had markers are recorded again without
them, as `caller-agent-workflow-history.json`,
`stateful-mcp-cancel-wait-workflow-history.json` and
`stateful-mcp-gather-wait-workflow-history.json`. Why? A history with a
marker and no matching `patched()` call fails replay with `[TMPRL1100]
Non-deprecated patch marker encountered`.

The Python README drops the marker notes and says which 1.x runs don't
replay. The TypeScript README keeps its note on
`openai-agents-stateful-mcp-session-watch`: TypeScript has its own copy
of that gate, and this PR doesn't touch it.

This also takes `workflow.patched()` out of every `Runner.run`. That
call is what exposed the sdk-core bug where a run whose first Update was
rejected fails its own replay.

## What will you notice? (Breaking)

These 1.x runs don't replay on 2.0. Let them finish on 1.x Workers
before you upgrade, or keep them there with Worker Versioning. For the
release notes:

- A run that passed its own `RunConfig.model_provider` (#204). On 1.x it
ran on the Worker's provider. On 2.0 its replay fails with the
`ValueError` that refuses the provider.
- A run in which a stateful MCP operation with
`cancellation_type=WAIT_CANCELLATION_COMPLETED` and neither timeout
finished in the same Workflow Task as another Activity (#373). On 2.0
the operation resolves one step later, so the run schedules its next
Activities in another order (`[TMPRL1100]`).
- A run whose next step depended on getting its own agents back, not
copies, such as asking again for a permanent approval (#426)
(`[TMPRL1100]`).

A run on a `main` build that reached one of these gates recorded its
marker, and it doesn't replay either. No release wrote those markers.

Rolling back to 1.x isn't promised either: histories of 2.0 runs that
hit the last two cases fail on 1.1.0 with `[TMPRL1100]`.

## Why?

We decided that replay is promised only within a major, and that a gate
that only protects an older major's runs is removed before the next
major ships. These three only protect runs from before their fixes, so
they go before 2.0.0.

## Checklist

1. No issue.

2. How was this tested:
- `make format`, `make lint` and `make test` for `python/openai_agents`
on Python 3.12: 618 passed, 2 skipped.
- Replay, across builds. I recorded finished runs on Workers with no
Workflow cache (a hello agent, `CallerAgentWorkflow`, and the four
stateful MCP replay shapes, with and without
`WAIT_CANCELLATION_COMPLETED`), plus a `CallerAgentWorkflow` run still
waiting on its model Activity. I recorded them on `main`, on this PR,
and the stateful MCP ones on 1.1.0 too. Then I replayed each of them,
and the committed histories, on every build.
   - On this PR, only these fail:
- the three 1.x cases above: the committed 1.x `caller-agent`
(`[TMPRL1100]`), `run-model-provider` (the plugin's `ValueError`) and
`stateful-mcp-gather-wait` (`[TMPRL1100]`) histories, and the
`WAIT_CANCELLATION_COMPLETED` gather recorded on 1.1.0 (`[TMPRL1100]`);
- every history with a marker: the three committed on `main` and all
seven recorded on `main` (every `main` agent run records
`openai_agents.run-caller-agents`), each with `[TMPRL1100]
Non-deprecated patch marker encountered`.

The other nine committed 1.x histories replay, and so do the 1.1.0
cancel runs, with and without `WAIT_CANCELLATION_COMPLETED`, and the
1.1.0 gather run without it. Everything recorded on this PR replays on
it.
- Rollback: this PR's histories on `main` and on 1.1.0. The caller-agent
and `WAIT_CANCELLATION_COMPLETED` gather histories fail with
`[TMPRL1100]`; the rest replay, including the waiting run. I didn't
carry a live run from one build to another.
- Control: a history with a renamed Activity fails with `[TMPRL1100]` on
every build.

3. Any docs updates needed? The README changes are here. The 2.0.0
release notes should list the replay cases above.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] openai_agents (Python and TypeScript): a retried stateful MCP session Activity silently opens a new, empty MCP session

3 participants