Repository navigation
Breaking: fail a retried OpenAI Agents stateful MCP session instead of opening an empty one - #373
Conversation
…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.
… 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.
|
[P1] Mixed operation timeouts change caller-cancellation order and break replay Confirmed on Reproduction:
The base requests cancellation in A → B order and schedules Replaying the base history on the PR fails with: 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
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.
|
Thanks @brianstrauch, reproduced on 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
|
DABH
left a comment
There was a problem hiding this comment.
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_toolsunder every Python cancellation type and schedule-to-close, TypeScript with the default and withscheduleToStartTimeout: 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/ApplicationFailureof typeDedicatedWorkerFailure, 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_timestays constant across operation and session retries and never refused a legitimate operation.- Python's
patched()keepsFalsefor 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
asyncstep ... so a run whose session does not end resumes in the same order as onmain' holds for resolutions, but not for a caller's cancellation in marker runs, as the comment atstateful-mcp-client.ts:256-258says. - The test list leaves out
operation_waiting_abandon,operation_waiting_wait_cancellationand 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'sdataConverter, so stateful operations fail for users with an encrypting codec or external storage. With a codec that changes encoding, every operation fails withFailed 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 usesactivity.client().
- 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.
|
Thanks @DABH for the thorough review. All nine comments are addressed in b861ec6, on a merge of
Checks on 5c79dc8: Python |
…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
left a comment
There was a problem hiding this comment.
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:610last 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_refusalfails with the__aexit__change reverted. Python 3.10 keeps a gap, partly disclosed (comment on README line 628). - TypeScript (
stateful-mcp-client.ts:268last round): the runner shape, the catch-then-listTools()shape, the session's end and the cancel in one Workflow Task, andcleanup()in afinallyafter a refusal all end CANCELED. With b861ec6's client hunk reverted, each ends FAILED withDedicatedWorkerFailure. 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
scheduleActivitythrow 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 withDedicatedWorkerFailure. - 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
DedicatedWorkerFailureconvert, 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
mainreplay 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 showsmcp-session-openedand 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: |
There was a problem hiding this comment.
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 barecanceledFailureInfowith no message. The worker only logsFuture exception was never retrieved ... DedicatedWorkerFailure: An earlier attempt ... opened an MCP session.- With the README's recovery (
except ApplicationErrorof typeDedicatedWorkerFailure, then a new block): the same, and the recovery never runs. - With an
except asyncio.CancelledErrorcompensation around the block: the handler runs, though nobody cancelled. - A person-wait
wait_condition(lambda: approved, timeout=4)that expires: theCancelledErrorreplaces theTimeoutError, 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 throwsDedicatedWorkerFailureas 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 nowWith 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
TimerFiredand 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.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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 endsWorkflowExecutionFailedwithApplicationFailure(DedicatedWorkerFailure): ... has ended <- ActivityFailure <- ... opened an MCP session. Acatch (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; executeOperationkeeps its own check, so a nonCancellable caller still getsDedicatedWorkerFailurefor 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.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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'sexcept ApplicationErrorfails the same way; that catch never fires, because the cancel wins. - TypeScript (
cleanup()in afinally, then a nonCancellable compensation incatch (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.
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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 theexcept ApplicationErrorfallback 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.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
P3 (docs): three sentences in the new text overstate or stop halfway.
- '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 raisesActivityError <- TimeoutError, which replaces the cancel (FAILED on the head and on main). Code that catchesActivityError, 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 justApplicationError. - Lines 599-601, 'running out of a bounded
server_session_configretry policy, still makes the block raiseActivityError', hold only if no refusal comes first. Withmaximum_attempts=2and a timed-out first attempt, attempt 2 is refused and the block raisesApplicationError(DedicatedWorkerFailure), which anexcept ActivityErrormisses (main raised anActivityError, which it caught). Say 'a one-attempt policy, or a session whose attempts all fail before connecting'. - 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).
There was a problem hiding this comment.
Fixed in d8f0913:
- The sentence now says the cancellation wins over the block's
DedicatedWorkerFailure, though not over anActivityErrorfrom a session that failed for another reason. - The examples are now "a one-attempt
server_session_configretry policy, or one whose attempts all fail before connecting". - 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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
P3 (tests): a few of this round's branches are unpinned.
- The non-permission describe wording. Replacing the
_DESCRIBE_PERMISSION_ERRORScheck withTrue, 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). ANOT_FOUNDcase 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.
There was a problem hiding this comment.
- 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.
|
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
Checks on d8f0913: Python |
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.
|
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,
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 |
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
left a comment
There was a problem hiding this comment.
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:610in round 1): on 3.14 therecover-*runs, the threeopcancel-*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:268in round 1): the runner shape, the catch-then-listTools()shape, the session's end and the cancel in one Workflow Task, andcleanup()in afinally(default config andscheduleToStartTimeout: 0) all end CANCELED. 0eff9e9's logic still fails each withDedicatedWorkerFailure.
Last round's items, each rerun:
- The timer-first race (P2): fixed. In all 13 timer-first runs (refused, shutdown and timeout endings;
workflow.sleepandwait_condition) the block raisesDedicatedWorkerFailurewith no cause, the README's recovery runs, and anexcept asyncio.CancelledErrorhandler no longer runs. A person-waitTimeoutErrorcaught inside the block keeps its path.timer_firstfails 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 onstateful-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
DedicatedWorkerFailureand 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_cancelpins 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 inclose()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:660for 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_foundcases 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 withDedicatedWorkerFailure', no longer holds since d8f0913 (comment on the TypeScript test). Line 112's list of untested branches should also name Python'sstartedand cancel-count guards incleanup()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
UNAUTHENTICATEDtoo, 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_refusalexpects 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 aWAIT_CANCELLATION_COMPLETEDsession acknowledges the block's cancel. On 3.11 and later,if _cancel_requests() > cancels: raise asyncio.CancelledError() from eends 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 needsworkflow.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_COMPLETEDserver_session_configplus an eviction whilecleanup()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).
| `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 |
There was a problem hiding this comment.
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.
- '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. Withmaximum_attempts=2, a 5 s start-to-close and aconnect()that takes 12 s, the head raisesApplicationError(DedicatedWorkerFailure) <- ActivityError <- DedicatedWorkerFailure('An earlier attempt ... ended (it lost its worker, timed out, or was reset) without confirming ...'), which anexcept ActivityErrormisses. Main raisedActivityError <- 'Cannot connect to an already running server'. Say 'one whose attempts all fail with an error before connecting (a factory call or firstconnect()that raises)'. - 'unless it ended in the workflow task that ended the block ...: then the block raises
DedicatedWorkerFailurewith 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 raisesDedicatedWorkerFailure <- ActivityError <- DedicatedWorkerFailure(opened ...), with its cause, and a one-attempt session that timed out raisesActivityError <- TimeoutError(StartToClose), so the README'sexcept ApplicationErrorrecovery 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 raisesActivityError(WorkerShutdown)), and so does await_conditiontimeout 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.
There was a problem hiding this comment.
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.
| `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 |
There was a problem hiding this comment.
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.CancelledErroraround 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 ApplicationErrorrecovery, orexcept Exception: main failed the run withCancelledError: Cancelled; the head catches theDedicatedWorkerFailureand goes on, so replay fails withActivity 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.
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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_COMPLETEDsession 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.CancelledErrorran 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.
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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 catchesCancelledError, on the head and on main alike:connect ... swallowed CancelledError, thenworker.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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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 withDedicatedWorkerFailure: ... has ended, so no worker serves ...instead of the bareCancelledErrorthat 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 catchesCancelledErrorwould 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
DedicatedWorkerFailureinstead 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.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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(() => { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Fixed in 891f428: scheduled.operation = undefined right after it is read. This moves no step or command, and the marker histories still replay.
|
|
||
| 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. |
There was a problem hiding this comment.
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.
cleanup()now returns silently when the scope that calledconnect()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 atcleanup(), and it replays on main. Ending the clause at 'and that then went on' covers every case (body line 34 too).- 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/worker1.24.0,lib/worker.js:821-833), one heartbeat per Activity at a time. So with a codec whoseencodenever 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 nolastFailure(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'srun()had not returned 75 s aftershutdown(). 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.
There was a problem hiding this comment.
Both in 891f428.
- The rollback clause now ends at 'and that then went on', in the README and in body line 34.
- The codec bullet now says: 'The Worker sends a failed Activity's result only after its last heartbeat, so an
encodethat 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.
There was a problem hiding this comment.
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']; |
There was a problem hiding this comment.
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/client1.24.0 turns NOT_FOUND intoWorkflowNotFoundError(rethrowGrpcErrorinworkflow-client.js). With theinstanceof WorkflowNotFoundError || NamespaceNotFoundErrorbranch (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. Thrownew WorkflowNotFoundError(...)here, or add it as a case.- With
CancellationScope.current().consideredCancelledremoved fromstateful-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 callscleanup()inside a cancelled child scope, after a refusal and withconnect()in the root scope, expecting no throw, would pin it.
There was a problem hiding this comment.
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
|
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:
Pre-existing.
Parity. The comments cover the four gaps: the user-cancelled scope ( |
# Conflicts: # python/openai_agents/tests/test_openai.py
|
Follow-up on the eviction item from my summary reply: a plain workflow without the plugin reproduces it on |
#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.
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.
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.
… 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.
…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.
…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.
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 theStatefulMCPServerProviderdocs 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):-server-sessionActivity sends its first heartbeat at once with the detailsmcp-session-may-be-open. It then readsDescribeWorkflowExecutionuntil the Temporal server shows that heartbeat, and only then calls the factory, connects the server, and sendsmcp-session-opened. A describe refused withPERMISSION_DENIED,UNAUTHENTICATED,UNIMPLEMENTED,NOT_FOUNDorINVALID_ARGUMENT, or heartbeat details it cannot decode, fails the attempt at once with a non-retryableDedicatedWorkerFailurethat names the status; forPERMISSION_DENIEDandUNAUTHENTICATEDit 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.DedicatedWorkerFailure, non-retryable, before it calls the factory.mcp-session-may-be-openis refused too.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 retryableApplicationFailure(the cancellation as its cause) instead of ending as cancelled. That includes a shutdown during the read-back, or during aconnect()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'sasyncio.wait_forcan drop one, and aconnect()can swallow it).Workflow side (
_StatefulMCPServerReferencein Python,StatefulMCPServerReferencein TypeScript):DedicatedWorkerFailureonce that Worker is gone, and keeps its commands. A Python operation with aschedule_to_close_timeoutalso keeps its commands: that timeout ends it. An operation with neither (a Pythonconfigthat sets neither, or TypeScriptscheduleToStartTimeout: 0; TypeScript's operationconfighas no schedule-to-close option) waited there forever.DedicatedWorkerFailureat 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 onmain, 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 onmain. In TypeScript, the operation path adds noasyncstep, with or without a schedule-to-start timeout; a caller's cancellation reaches an operation on this path one step later than onmain. Only runs that recorded the patch markeropenai-agents-stateful-mcp-session-watchfollow the session this way; a run records it at its first operation with neither timeout (Python) or withscheduleToStartTimeout: 0(TypeScript). Runs recorded before this change have no marker and schedule such operations exactly as before (see Replay).execute_activity/scheduleActivitycall. 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 withDedicatedWorkerFailurewhile 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 getsDedicatedWorkerFailure, and so does a block left in that task; the Python README says so).cancellation_type=WAIT_CANCELLATION_COMPLETEDis 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 wheremainreturned the result. Only runs with the patch marker do this. A laterstateful_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.DedicatedWorkerFailure, Python'sasync withraisesApplicationError(type="DedicatedWorkerFailure")and TypeScript'scleanup()throws anApplicationFailureof that type, each with the session Activity'sActivityError/ActivityFailureas 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 bareCancelledError. A cancellation leaving the Python block wins over this failure (a directcleanup()call after a Workflow cancel still raises it; its docstring says so), and so, in TypeScript, does a cancelled scope that calledcleanup()orconnect(), or one aroundcleanup()but not aroundconnect(), also whencleanup()runs inCancellationScope.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 raisesApplicationError(type="DedicatedWorkerFailure")in Python and throws anApplicationFailureof that type in TypeScript, each caused by the session Activity'sActivityError/ActivityFailure, where earlier versions raised thatActivityError/ActivityFailureitself, so code that catches it around the block must also catch the new type. Before upgrading, such a caller moves toStatelessMCPServerProvider(or Python'stemporal_mcp_server()), or catches that failure around the block and opens a new stateful server. The Worker's client also needs permission to callDescribeWorkflowExecution; without it, every stateful session fails at once with a non-retryableDedicatedWorkerFailurethat says so.Replay (the Activity side changes only Activity code):
openai-agents-stateful-mcp-session-watch. Histories recorded before this change have no marker, so their operations are scheduled exactly as onmainand 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 withWAIT_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 onmain. Histories recorded onmainreplay in both suites (thestateful-mcp-*histories withoutmarkerin their names, inpython/openai_agents/tests/histories/andtypescript/openai-agents/src/__tests__/histories/).@temporalio/workflow1.24.0 does not keep a decision made during replay.temporalio1.34.0 keeps theFalsethatworkflow.patched()returned while replaying the earlier operation, so that run never records the marker and keeps scheduling as onmainuntil it ends: an operation scheduled after its session ended waits until the caller cancels it or the run ends. The Python README says so.[TMPRL1100], for runs that recorded the marker (a patch marker without a matching change), and can fail for any run whose session failed withDedicatedWorkerFailure(a refused retry or a refused describe) and that then went on, and, in Python, for any run that caught the no-causeDedicatedWorkerFailureof 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.DedicatedWorkerFailurewith no cause (above), so a run that hit it and caught the bareCancelledError, or that failed with it although it catchesApplicationErrororExceptionaround 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 raisesDedicatedWorkerFailurein 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.reset_heartbeat=Trueclears the session's heartbeat details, so the next attempt connects a new server, as before.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
Closes [Bug] openai_agents (Python and TypeScript): a retried stateful MCP session Activity silently opens a new, empty MCP session #372
How was this tested:
891f428, thenab88caeandbf65898, merges ofmainat565b4d5and9d6f9ff(their conflicts were only in test imports, test workflows and the replay test's history list). Onbf65898: Pythonmake format,make lint,make buildandmake test PYTEST_ARGS='-n 4'on Python 3.14.8 and 3.10.22 (546 and 544 passed); TypeScriptmake lint(no errors),make test(311 passed) andmake build;scripts/ci/check_conventions.py.test_stateful_mcp_server_empty_block(a block left before its first await keepsmain's bareCancelledError, [Bug] openai_agents (Python): a stateful_mcp_server() block left before its first await raises a bare CancelledError #391; withoutcleanup()'sstartedguard it raisesDedicatedWorkerFailure),signal_with_refusal(without the cancel count it ends through the recovery),shutdown_before_connect_ignored(aconnect()that swallows the shutdown's cancellation; without the check afterconnect()the attempt serves and the Worker's shutdown hangs); TypeScript's scope cancelled betweenconnect()andcleanup()(ona8e897eit fails withDedicatedWorkerFailure), and theNOT_FOUNDdescribe case now throwsWorkflowNotFoundError(without the branch for it, the attempt is retried until the deadline).cleanup()after a cancel, a Workflow reset inside an open block, TypeScript's root scope after a caught cancel, and a TypeScript codec whoseencodenever returns.375ae12,bf041c0anda8e897e(a8e897echanges only the Python README and a docstring, to name the block-exit change that is not behind the marker; Pythonmake lintpasses):test-openai-agents.tsrun 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 ond8f0913, all with "Workflow execution timed out", whilemainfailed none in 3 runs. With this change it failed none in 3 runs (272 tests, 375 to 468 seconds), andmainnone again (263 to 351 seconds). TypeScriptmake lint(no errors) andmake build.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, theclose()limit is 60 seconds, and a Worker shutdown while the attempt waits inclose()must finish within 20 seconds. Without the clear inclose()'sfinallyit fails with aTimeoutError. Pythonmake lint,make buildandmake test PYTEST_ARGS='-n 4': 482 passed on 3.14.8; on 3.10.22, 481 passed andtest_external_trace_to_workflow_spansfailed once under load, then passed 3 of 3 alone.9927148andd8f0913on994f490.9927148takes 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 onclose()'s wait and the cancel count. Pythonmake format,make lint,make buildandmake test PYTEST_ARGS='-n 4'on Python 3.14.8 and 3.10.22 (481 passed on each); TypeScriptmake lint(no errors),make test(272 passed) andmake build;scripts/ci/check_conventions.py.encode_stallshits the 90-second test timeout,operation_waiting_after_cancelends withCancelledError('Workflow cancelled'),timer_firstfails the run with a bareCancelledError('Cancelled'), and the TypeScriptcleanup()test in a non-cancellable scope ends withDedicatedWorkerFailure. With the operation path's check of the caller's task removed,cancel_with_refusalcompletes through the recovery code. Giving the permission advice for every refusal code fails the newnot_foundcases in both languages.operation_cancelled) let the session connect only once the server shows the call cancelled, instead of racing a 1-second timer against a 3-secondconnect(). One CI run on994f490failed the TypeScript test on macOS that way, and it failed once locally under load.mainfor this PR's earlier replay checks replay on this change, as before. None of them hits the timer race (Replay above).5c79dc8: a new TypeScript test, "a Workflow cancellation wins over a refused session incleanup()", the counterpart of Python'stest_stateful_mcp_server_cancelled_after_refusal. Withcleanup()'s check of the caller's scope removed, it fails withDedicatedWorkerFailure. TypeScriptmake lint(no errors),make test(270 passed) andmake build;scripts/ci/check_conventions.py. Python is unchanged and was not rerun.b861ec6on5c79dc8(a merge ofmainat017d88a): Pythonmake lint,make buildandmake test PYTEST_ARGS='-n 4'on Python 3.14.8 and 3.10.22 (476 passed on each); TypeScriptmake lint(no errors),make test(269 passed) andmake build;scripts/ci/check_conventions.py. CI passed on5c79dc8.mainmerged: Python'stest_stateful_mcp_server_cancelled_after_refusalfails (DID NOT RAISE WorkflowFailureError: the run completed); TypeScript's Workflow cancellation test fails withDedicatedWorkerFailure, and its shutdown test with aconnect()that ignores cancellation fails withMCP Stateful Server Worker failed to schedule activity.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_cancellationand both marker histories).mainwith[TMPRL1100]on the patch marker. The histories recorded onmainfor this PR's earlier replay checks (27 Python, 18 TypeScript) also replay on5c79dc8.mainhas the same code.workflow_patchin thetemporalio1.34.0 wheel andpatchInternalin@temporalio/workflow1.24.0, and matches the reviewer's upgrade reproduction and new-run control. I did not rerun that reproduction.scripts/ci/check_conventions.pypasses.9fb99d1: the reported caller-cancellation shape, recorded onmain, fails onbfa9af0with[TMPRL1100] Activity type of scheduled event 'statefulReplayRecoverA' does not match ...and replays on9fb99d1; a run recorded on9fb99d1fails onmainwith[TMPRL1100]on the patch marker. The Python analog (two servers, one without timeouts, withTRY_CANCELand withWAIT_CANCELLATION_COMPLETED) replays across builds before and after. Histories recorded onmainfor the earlier replay checks of this PR all replay on9fb99d1, including Python's ended-session runs that failed onbfa9af0. Pythonmake lint,make buildandmake test PYTEST_ARGS='-n 4'on 3.14.8 and 3.10.22 (468 passed each); TypeScriptmake lint(no errors),make test(260 passed) andmake build;scripts/ci/check_conventions.py.bfa9af0on793ffeb(a merge ofmainatea04762): Pythonmake lint,make buildandmake 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 onmain); TypeScriptmake lint(no errors),make test(260 passed) andmake build;scripts/ci/check_conventions.py.mainatea04762with the Workflow Worker stopped, so that one Workflow task resolved a stateful call together with other Activities (gather) or with a Workflow cancel: on793ffebthe 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 everymainhistory replays, and histories recorded on this change replay onmain. A Python gather withWAIT_CANCELLATION_COMPLETEDfails across builds in both directions, with[TMPRL1100]only.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 anActivityFailureat the block exit; adescribe()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. Withfrom errput back on the session-ended raise, theoperation_waitingcause check fails.Supplemental local runs in Docker, with the plugins' locks (
temporalio1.34.0,openai-agents0.22.0,mcp2.2.0;@temporalio/worker1.24.0,@openai/agents-core0.14.3), Node 24.22.0 and Temporal CLI 1.9.1:c25eeec: Pythonmake sync,make lintandmake test PYTEST_ARGS='-n 4'on Python 3.14.8 and 3.10.22 (457 passed on each), andmake build; TypeScriptmake sync,make lint(no errors),make test(255 passed) andmake build;scripts/ci/check_conventions.py.e1a1ecf: Pythonmake sync,make lintandmake test PYTEST_ARGS='-n 4'on Python 3.13.16 (458 passed); TypeScriptmake sync,make lint(no errors),make test(256 passed) andmake build;scripts/ci/check_conventions.py.test_stateful_mcp_server_session_retried:worker_replaced(graceful shutdown after the server connected) andsession_timed_out(5-second session start-to-close): the retry must be refused, with one factory call. Onmainboth fail withDID NOT RAISE WorkflowFailureError: a new server served the next call.short_heartbeat_timeout(4-second session heartbeat timeout, held 10 seconds): one factory call. Onmainit fails with two factory calls; with a 30-second heartbeat interval it fails because the retry is refused.first_connect_failsandfirst_connect_fails_delayed_heartbeats(a codec delays "may be open" heartbeats past the failed connect): the retry must connect. The first passes onmaintoo; onmainthe delayed case fails its check that the codec delayed a heartbeat, sincemainsends 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 firstconnect()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.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 waitinglist-toolsis cancelled and the run fails with the refusal. Onmainthe retry connected a second server.operation_after_refusal: nothing is scheduled after the session ended. Onmainit 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. Onmain, 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 onmain; without passing the cancellation on, it fails.next_block_custom_ids:next_blockwith session activity IDssession-1andsession-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-secondschedule_to_close_timeout, nothing else bounding the start): the operation after the session ended is still scheduled and ends by its own timeout, as onmain.numeric_session_id(sessionactivity_id="100"): the firstlist_toolsandcall_tool, with default IDs2and3, succeed.operation_waiting_after_cancel:operation_waitingafter the Workflow caught a cancellation request; the run must still fail with the refusal.operation_waiting_abandonandoperation_waiting_wait_cancellation:operation_waitingwithABANDONand withWAIT_CANCELLATION_COMPLETED. In every cancellation mode, the error the operation raises inside the block has the session's refusal as its cause.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.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 withNOT_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.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 raiseDedicatedWorkerFailureand 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.put, once describe has shownmcp-session-openedright 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. Onmainthe run completed withget=EMPTY session=B.scheduleToStartTimeout: 0after a graceful shutdown ends the session: the next call fails at once withDedicatedWorkerFailure. Onmainit times out.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 aconnect()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.PERMISSION_DENIEDandUNAUTHENTICATED(the cases arePERMISSION_DENIEDand theWorkflowNotFoundErrorthe client throws forNOT_FOUND); a describe or decoding that never returns fails the attempt at the deadline. No case calls the factory.scheduleToStartTimeout: 0, a call waiting behind another when a graceful shutdown ends the session fails withDedicatedWorkerFailurewithout running.scheduleToStartTimeout: 0runs 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 withDedicatedWorkerFailure.finallycallscleanup(). The run must end cancelled, with one factory call. It also runs withcleanup()inCancellationScope.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-cancellablecleanup()in itsfinally; the Workflow must get the cancellation, which needs the check of scopes aroundcleanup()but not aroundconnect().maintoo: a retry after a failed first connect connects again; a caller's cancellation of a queued call still stops it.mainand Python 1.1.0 they readEMPTYfrom a new session; on this change the Python run fails withDedicatedWorkerFailure(the refusal for an attempt that may have opened a session: theopenedheartbeat was still held by the throttle) and in TypeScript the second Worker never connects and the run fails.mainand 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].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
DescribeWorkflowExecutionpermission for the Worker's client, the block-exit failure type, and the replay notes above.Not covered:
main. An attempt that timed out but is still running serves the queue the same way until its Worker cancels it. Both READMEs document this, and it is tracked in [Bug] openai_agents (Python and TypeScript): a second stateful MCP server with the same name reaches the first one's MCP session #385 (for Google ADK, [Bug] google_adk: a second stateful MCP block with the same name reaches the first block's MCP session #380). A task queue or token per block would close it, but changes the queue or headers of every operation. In TypeScript the other direction happens too: an earlier server's call still queued atcleanup()can run with a new server of the same name, unless itsscheduleToStartTimeoutis 0 (the README says so; added to [Bug] openai_agents (Python and TypeScript): a second stateful MCP server with the same name reaches the first one's MCP session #385).cleanup()doesn't throw and only the later operations fail; Python refuses the retry and the block raises. Both READMEs say so.main's scheduling until it ends. Covering it would require reading the replay state in Workflow code, which is not deterministic.CancelledErrorin place of its own outcome, as onmain([Bug] openai_agents (Python): a stateful_mcp_server() block left before its first await raises a bare CancelledError #391).scheduleActivityerror, and the check of the caller's own scope in TypeScript'scleanup(), which alone matters only whenconnect()ran in a non-cancellable scope inside the one that callscleanup().cleanup()waits for it is lost, as onmain. [Bug] google_adk: a stateful MCP block can lose a cancellation while it exits #394 tracks it for Google ADK and notes that this plugin has the same code.WAIT_CANCELLATION_COMPLETEDserver_session_config, an eviction whilecleanup()waits for the session's cancel never completes and keeps the Worker's cache slot, withtemporalio1.33.0 and 1.34.0, as onmain. This is Workflow eviction never completes when an already-cancelled activity handle is cancelled again during eviction (regression in 1.33.0) sdk-python#1938, fixed in 1.35.0.Open questions: none.