Repository navigation
Breaking: fail a retried Google ADK stateful MCP session instead of opening an empty one - #311
Conversation
…pening an empty one A retry of the stateful toolset's -server-session Activity built a new toolset, and the next tool call opened a new, empty MCP session. Later calls in the run succeeded against it with no error. The session Activity now records a marker in its heartbeat details when its toolset opens an MCP session, before ADK sends a request on it. A later attempt that finds the marker fails with a non-retryable DedicatedWorkerFailure, as the provider docstring says. Retries in which no session was opened still build the toolset. All of the Activity's heartbeats go through one awaited client call, so a buffered heartbeat cannot erase the marker. A factory whose state survives being rebuilt recovered from these retries before; it now gets DedicatedWorkerFailure.
The session Activity sent its heartbeats as awaited client calls, and with a heartbeat timeout also as Worker heartbeats. Two writers meant a Worker heartbeat sent before the session opened could reach the server after the marker, and without a heartbeat timeout the Worker never saw cancels, pauses or resets in its own heartbeat responses. Now only activity.heartbeat() writes the details. The Worker sends one attempt's heartbeats in order and sends its latest details with the attempt's failure, so a graceful shutdown passes the marker on. With a heartbeat timeout, every heartbeat says a session may be open until one opens, and an attempt that ends without a session clears that, so only a lost or timed-out attempt is refused without a session. Workflow code goes back to main's: a list or call after a refused retry fails when its schedule-to-start timeout expires. The host-kill test now reads the ready line on Windows too.
…-stateful-mcp-session-replaced
…eset and host-kill tests
…t session Without a heartbeat timeout, the session Activity sent no details until a session opened, and the Worker could hold that marker heartbeat for up to 30 seconds. A host lost in that window was retried with empty details, so the retry rebuilt the toolset and the run read empty state. Now every attempt sends its first heartbeat at once with mcp-session-may-be-open, in every configuration, and before the first session opens it reads DescribeWorkflowExecution until the server shows that heartbeat. A lost or timed-out attempt is refused even when no session opened; a clean exit without a session still clears the marker. The Worker's client needs permission to describe the Workflow.
In the call_waiting case the run fails as soon as the refused session ends, so the resume signal could reach a finished run and fail the test with "workflow execution already completed".
DABH
left a comment
There was a problem hiding this comment.
First review, at head de1a1c1. On a worktree at the head make lint is clean and make test gives 199 passed, 5 skipped. tests/test_stateful_mcp.py passed three more times with -n 4 and in isolated reruns of its timing-heavy tests; with the three marker constants added to base, 16 of its 22 tests fail there, and the 6 that pass are the pre-existing tests and checks of behaviour that must not change (retries after a failed first connection, a workflow reset). Every finding below was reproduced against a local dev server, base 88745dc against this head, with probe scripts, or traced to file:line; the replay findings were recorded on both builds and replayed with Replayer in both directions, and the fixes suggested for the first two were checked the same way. The worker-side marker protocol held in every path I tried: a factory that raises, a first connection that fails, graceful shutdown before and after a session opened, a killed host, start-to-close and heartbeat timeouts, ResetActivity and pause/unpause with and without reset_heartbeat, parallel first operations, and a context-sensitive payload codec. Refuted: a reset changing scheduled_time (it does not, so a reset does not make the same block's operations look stale); eviction hangs or unretrieved exceptions from left-pending WAIT_CANCELLATION_COMPLETED operations; sandbox import problems; changes to activity names, task queues, inputs or timeouts (a healthy session costs one more DescribeWorkflowExecution call and one more heartbeat, with unchanged first-list latency). The body's claims that ADK runs the turn without the failed toolset and that cleanup() re-raises the session's ActivityError are accurate, and the workflow code is indeed unchanged since bb9b322. Not verified: google-adk 2.13, the HTTP and SSE transports, real Temporal Cloud or custom-authorizer permissions (PERMISSION_DENIED was simulated with a client interceptor), and Linux or Windows locally (CI is green on all four cells).
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 design (one heartbeat writer, the clear sent after pending heartbeats, the read-back, the scheduled-time refusal) holds up, and the suite pins most of it. The problems are around it. The workflow-side wrapper that watches the session awaits workflow.wait instead of the activity handle, which changes resume order in activations with two resolutions and swallows a cancellation that arrives with the operation's completion; both are introduced here, both break replay against main, and there is no version gate. Two configurations now end in failing or stuck runs: a heartbeat timeout under the fixed 30 s interval (the tests mask this by patching the interval), and a worker client that may not describe the Workflow. And the block contract the docs imply does not hold: the exception at the block boundary is an ActivityError, same-name blocks are not isolated from the previous session, and the one-hour default is now a hard cap.
Requesting changes: the replay break in healthy concurrent runs (including silently swapped ParallelAgent responses) and the dropped cancellation are correctness defects introduced by this PR, and the heartbeat-interval and describe-loop failures should be fixed with them.
PR body: 'Draft while the caller change is reviewed' is stale (the PR is not a draft). The Replay section needs the two breaks in the first two comments; also, a base history in which a WAIT_CANCELLATION_COMPLETED operation was waiting when the session ended does replay on the head, so 'in either direction' overstates that one case. The listed base failure modes come from 679d134's tests; against the current tests base fails mostly with TimeoutError at the refusal waits, and the tests also need _SESSION_MAY_BE_OPEN. 'If ADK renames them, the toolset falls back' holds only for _mcp_session_manager (see the comment on line 583). Parity: TypeScript, Go and Java Google ADK have no stateful session, so nothing is left inconsistent across the Google ADK languages. The same retry gap exists in Python OpenAI Agents' deprecated StatefulMCPServerProvider (python/openai_agents/src/temporalio/openai_agents/_mcp.py:530-571, which the body mentions) and in the TypeScript OpenAI Agents StatefulMCPServerProvider (typescript/openai-agents/src/worker/stateful-mcp-provider.ts:91-159), which the GA plugin's README lists as supported and the body does not mention; both deserve follow-up issues.
| raise _session_ended_failure(session) | ||
| operation = workflow.start_activity(activity, *args, **kwargs) | ||
| try: | ||
| await workflow.wait([operation, session], return_when=asyncio.FIRST_COMPLETED) |
There was a problem hiding this comment.
P2 (blocking): awaiting workflow.wait([operation, session]) instead of the activity handle changes the order in which coroutines resume, so a healthy run in which a stateful operation and another activity complete in the same workflow task does not replay across this upgrade (or a rollback), and an ADK ParallelAgent replay can hand each branch the other branch's model response. workflow.wait puts its own waiter future, one more ready-queue hop, between the handle finishing and the caller resuming. When a stateful operation and another activity resolve in the same activation, the stateful one first, the other branch now resumes first and their follow-up commands swap sequence numbers. Reproduced with real Workers on a dev server, with the workflow worker stopped while both activities completed, recorded on 88745dc and on this head and replayed both ways. (1) asyncio.gather(a, b) in one block, where a is a stateful call-tool followed by activity noop_a and b is a plain activity followed by activity noop_b: for the activation [resolve_activity(seq=3), resolve_activity(seq=4)] base schedules noop_a_activity (seq 5) then noop_b_activity (seq 6) and the head the reverse; the base history fails on the head with [TMPRL1100] Activity type of scheduled event 'noop_a_activity' does not match activity type of activity command 'noop_b_activity', and the head history fails on base the same way. (2) A ParallelAgent with branch_mcp (tools=[TemporalStatefulMcpToolSet(...)]) and branch_other (an activity_as_tool): both follow-ups are invoke_model, so Core accepts the commands and resolves them by sequence number; replaying the base history on the head gave ['branch_other:fr:other_activity', 'branch_mcp:fr:block', 'branch_other:done-a', 'branch_mcp:done-b'], while the recorded answers were done-a for branch_mcp and done-b for branch_other. With equal answers the replay reports success while swapping them. After a deploy every open run replays its history on the new Workers, so a run with such an activation either fails its workflow task with TMPRL1100 until rollback or carries on with the branches' responses exchanged. A single agent with parallel tool calls is not affected (ADK gathers the calls before issuing commands), and each build replays its own histories. This makes the body's 'Histories without a session that ended while the run used the toolset replay on both builds' untrue, and that is the stated reason for having no version gate. Fix, either (a) if not workflow.patched("<id>"): return await workflow.execute_activity(activity, *args, **kwargs) at the top of this function: with that gate all 21 base histories I recorded replay on the head, including the session-ended ones the body lists as breaking, and the stateful tests pass, at the usual cost that a rollback fails for runs that recorded the marker; or (b) for every cancellation type except WAIT_CANCELLATION_COMPLETED, return await operation as main does, with a done-callback on session that cancels the operation and a handler that raises _session_ended_failure(session) when the resulting ActivityError is a cancellation and session.done(); that keeps main's resume order for the default cancellation type, and only WAIT_CANCELLATION_COMPLETED keeps the extra hop and needs the gate or a disclosure. Either way, commit a main-recorded history of this shape under tests/histories/ and correct the Replay section of the body.
There was a problem hiding this comment.
Thanks, reproduced and fixed in 3059bfa, with option (b) rather than a gate (we're not adding version gates to these fixes for now). For every cancellation type except WAIT_CANCELLATION_COMPLETED, _execute_operation now awaits the operation itself, as main does. A done callback on the session cancels it, and a cancel raised that way becomes the DedicatedWorkerFailure.
tests/histories/stateful_mcp_gather.json was recorded on 88745dc with the workflow worker stopped, so one activation resolves a stateful call and then a plain activity, each followed by another activity (tests/helpers/stateful_replay.py). test_stateful_mcp_histories_from_main_replay replays it. On de1a1c1 it fails with [TMPRL1100] Activity type of scheduled event 'follow_up_a' does not match activity type of activity command ...; on this head it passes. The same shape recorded on this head also replays on 88745dc.
WAIT_CANCELLATION_COMPLETED keeps the workflow.wait hop, so a gather of that shape still replays differently across the upgrade. The body's Replay section now says so.
| # The operation is not awaited directly, so pass the cancellation on | ||
| # and wait for it as its cancellation type says. | ||
| operation.cancel() | ||
| return await operation |
There was a problem hiding this comment.
P2 (blocking): a cancellation that reaches this coroutine in the same activation as the operation's completion is dropped: operation.cancel() is a no-op on the finished handle and return await operation returns the result. Reproduced by stopping the workflow worker, letting a stateful call-tool complete, and calling handle.cancel() before restarting the worker, so one activation carried ['resolve_activity(seq=3,completed)', 'cancel_workflow']. Base records the SDK's RAISE_ON_CANCELLING_COMPLETED_ACTIVITY flag and the run ends WORKFLOW_EXECUTION_CANCELED; the head records no flag and the run ends WORKFLOW_EXECUTION_COMPLETED with the tool's result, so the user's cancel is silently ignored. The same happens when the operation is get_tools, and with an asyncio.timeout whose timer fires in the activation that completes the operation base raises TimeoutError while the head returns the result. Base histories of the cancel case fail on the head with [TMPRL1100] Complete workflow machine does not handle this event: HistoryEvent(id: 20, WorkflowExecutionCanceled). This is the pattern the SDK guards against in _await_temporal_operation ('Retrying the shield after both futures become ready would return the result and erase the task cancellation'), reintroduced one layer up because the caller no longer awaits the handle. On ADK 2.12's agent route it is masked, because canonical_tools (llm_agent.py:888) and tool batches run under asyncio.gather, which re-raises the cancel; it shows whenever workflow code awaits get_tools() or run_async() directly, as this PR's tests do. Fix: if operation.done(): raise before operation.cancel(); with that line the three cases end CANCELED, CANCELED and TIMEOUT, and the base histories replay. Option (b) in the comment on line 398 also restores the SDK's own handling for the default cancellation type.
There was a problem hiding this comment.
Fixed in 3059bfa. The default path awaits the operation, so the SDK's own handling applies. The WAIT_CANCELLATION_COMPLETED path re-raises the cancellation when the operation is already done.
tests/histories/stateful_mcp_cancel.json was recorded on 88745dc: a stateful call completes, the workflow is cancelled, and one activation carries both. The run ends CANCELED. It replays on this head; on de1a1c1 it fails with Fatal error in workflow machines: ActivityMachine in state ScheduleCommandCreated says the transition is invalid ....
|
|
||
|
|
||
| # Seconds between heartbeats of the ``-server-session`` activity. | ||
| _HEARTBEAT_INTERVAL = 30.0 |
There was a problem hiding this comment.
P2: the session heartbeats every fixed 30 s whatever server_session_config sets, so a heartbeat_timeout that is not comfortably above 30 s now fails any block that stays open past the first gap between heartbeats, on a healthy worker: the attempt times out and its retry is refused. Probe with a worker that never stops (put, sleep, get): heartbeat_timeout=10s with a 45 s block fails 19 s in with ActivityError <- ApplicationError: DedicatedWorkerFailure: An earlier attempt of this stateful MCP session activity opened an MCP session, and Temporal cannot recreate its state.; base completes, but its factory ran three times (the silent rebuild of #310). heartbeat_timeout=20s survives a 45 s block and fails a 90 s one about 53 s in; 35 s survives 90 s. The fixed interval predates this PR, but the hard failure is new, and nothing documents the floor. The tests hide it: every case that sets a heartbeat timeout also monkeypatches the private _HEARTBEAT_INTERVAL to 1 s (tests:375, 685, and the host script at 806), while #310 names a heartbeat timeout as the way to detect a lost host. Fix: derive the interval from activity.info().heartbeat_timeout, for example min(_HEARTBEAT_INTERVAL, heartbeat_timeout.total_seconds() / 3) (anything below Core's 0.8 x timeout throttle works; the OpenAI Agents plugin's auto_heartbeater uses half the timeout), and add one heartbeat-timeout test that does not patch the interval.
There was a problem hiding this comment.
Fixed in 3059bfa. The session now heartbeats every min(30 s, heartbeat_timeout / 2), the same rule the OpenAI Agents fix (#373) uses. test_stateful_session_heartbeats_within_heartbeat_timeout keeps a block open for 15 s with a 5 s heartbeat timeout and patches nothing. On de1a1c1 the run fails (the attempt times out and its retry is refused); now it completes with one factory call.
| handle = self._client.get_workflow_handle( | ||
| self._workflow_id, run_id=self._run_id | ||
| ) | ||
| description = await handle.describe() |
There was a problem hiding this comment.
P2: wait_until_stored has no deadline and lets every describe or decode error escape as a retryable failure, so a worker client that may not call DescribeWorkflowExecution leaves the first get_tools retrying forever and the run open with no workflow-visible failure. Probe with a client interceptor that answers describe_workflow with RPCError(PERMISSION_DENIED), the default config and server_session_config, and a real stdio server: the head is still RUNNING after 80 s with -list-tools at attempt 8, last_failure 'Request unauthorized.', and the session healthy at attempt 1; base completes in 5.7 s with ['echo']. Each attempt calls describe twice because ADK's retry_on_errors retries McpToolset.get_tools once. The default config has no schedule-to-close timeout or attempt limit, so nothing ends it; under a 60 s execution timeout the run failed with an ActivityError (retry state TIMEOUT) caused by the RPCError, which does not say what to fix. The README discloses the permission but not this failure mode, and any persistent decode error loops the same way. Fix: turn non-transient statuses (PERMISSION_DENIED, UNAUTHENTICATED, UNIMPLEMENTED, NOT_FOUND, INVALID_ARGUMENT) and decode errors into a non-retryable ApplicationError(type="DedicatedWorkerFailure") whose message names the permission, and bound the loop. Doing the read-back once in connect, right after the first heartbeat, would fail the session activity instead, and _execute_operation already fails every waiting or later operation at once when that happens.
There was a problem hiding this comment.
Fixed in 3059bfa, as you suggested. The read-back now runs once in the session activity, right after its first heartbeat and before the factory, as #373 does. These make it fail with a non-retryable DedicatedWorkerFailure whose message names the permission: PERMISSION_DENIED, UNAUTHENTICATED, UNIMPLEMENTED, NOT_FOUND, INVALID_ARGUMENT, and a decode error. Other describe errors are retried until a 30 s deadline. The read-back also stops when the pending activity is gone or is another attempt. Every waiting or later operation then fails at once through _execute_operation.
test_stateful_session_without_describe_permission refuses describe_workflow with a client interceptor on the worker's client. The run fails within seconds with that error, and the factory never runs. On de1a1c1 the run is still open when the test's 20 s wait ends.
There was a problem hiding this comment.
Follow-up in e9b0dbc: in 3059bfa the 30 s deadline was only checked between describes, and describe() had no rpc_timeout. A stalled describe, or a codec that never finished decoding, could keep the session waiting past it. The whole read-back now runs under one asyncio.timeout_at, and each describe gets the time left as its rpc_timeout. test_stateful_session_without_describe_permission now also covers a describe and a decode that never return: the attempt fails at the deadline with no factory call. On 3059bfa both cases time out. e9b0dbc also keeps the session's failure as the cause of a cancelled waiting operation in every cancellation mode (3b17169 started that). The operations test checks the error chain for TRY_CANCEL, ABANDON and WAIT_CANCELLATION_COMPLETED.
|
|
||
| **Do not pass secrets, credentials, or API keys through `factory_argument`.** It is an activity argument, so it is recorded in workflow history and, without a payload codec, visible in the web UI. Resolve credentials worker-side inside the toolset factory instead. | ||
|
|
||
| **Stateful MCP toolsets:** `TemporalStatefulMcpToolSet` and `TemporalStatefulMcpToolSetProvider` keep one `McpToolset` open for an `async with` block, in a `-server-session` activity. Temporal cannot recreate that toolset's state on another worker. If the session activity is retried after its toolset opened an MCP session, for example after a graceful worker shutdown or a lost host, the retry fails with a non-retryable `ApplicationError(type="DedicatedWorkerFailure")` instead of opening a new, empty session. Once the session activity has ended, `get_tools` and tool calls on the toolset, including any already waiting, fail with the same error type without waiting for a timeout, and the run fails when the `async with` block exits. An operation still pending when the session ends is cancelled, except with `cancellation_type=WAIT_CANCELLATION_COMPLETED`: no worker may be left to acknowledge that cancellation, so the operation is left to its own timeout while the caller fails at once. A later `async with` block with the same name in the same run does not run such an operation, whatever activity IDs `config` or `server_session_config` set: its session refuses any operation the server scheduled before it, with the same error type. A retry in which no session was opened builds the toolset again. |
There was a problem hiding this comment.
P2 (non-blocking): what leaves the async with block after a refused retry is an ActivityError whose cause is the DedicatedWorkerFailure, not the ApplicationError(type="DedicatedWorkerFailure") that both class docstrings tell callers to handle (_mcp.py:651-652, 856-858), so recovery code written to those docstrings does not run. cleanup() (_mcp.py:914-924, unchanged) awaits the failed session handle and re-raises its ActivityError, and when the block body had already raised the plugin's own ApplicationError from get_tools, the exception from __aexit__ replaces it. Probe: except ApplicationError as e: with a DedicatedWorkerFailure type check around the block misses it, and the run fails with WorkflowFailureError <- ActivityError <- ApplicationError(DedicatedWorkerFailure, non_retryable). On main the usual dedicated-worker failure (schedule-to-start, through _handle_worker_failure) left the block as an ApplicationError, because the still-retrying session's cancel was swallowed; this PR makes the ActivityError shape the normal one. The body states it correctly, and the test catches (ActivityError, ApplicationError) with the comment 'as the README suggests', but this paragraph never describes the catch-and-reopen recovery. Fix: have cleanup() raise a new ApplicationError(type="DedicatedWorkerFailure") with the ActivityError as its cause when the session failed with that type (as _session_ended_failure does), or document catching ActivityError and checking .cause; either way, add the body's recovery advice here.
There was a problem hiding this comment.
Fixed in 3059bfa. When the session failed with DedicatedWorkerFailure, cleanup() now raises ApplicationError(type="DedicatedWorkerFailure") from the session's ActivityError. _assert_refused checks that type at the top, and the reopen test now catches only ApplicationError. Both fail on de1a1c1. The README describes the catch-and-reopen recovery.
| session_scheduled_time: datetime | ||
|
|
||
| async def get(self) -> McpToolset: | ||
| if activity.info().scheduled_time < self.session_scheduled_time: |
There was a problem hiding this comment.
P2 (non-blocking, partly pre-existing): same-name blocks are isolated in one direction only: this check refuses an older block's operations at a newer session, but a newer block's operations are served by the older session until it notices its cancellation, up to about 30 s, so the new block reads and writes the old MCP session. cleanup() cancels the session with the default TRY_CANCEL and returns at once; the session learns of the cancel only from a heartbeat response, its nested worker keeps polling the shared name@run_id queue meanwhile, and the next session's attempts fail with 'Cannot connect to an already running toolset' until the old toolset closes. Healthy probe with a stateful stdio server and nothing failing: block 1 put(A) and exits; in block 2, get returns A from the old MCP process, put(B) lands there too, and the same get 45 s later returns EMPTY from a new process, so B is lost. Base behaves identically. With two host processes, gets one second apart alternate between EMPTY and B. What is new is the recovery the body recommends: after a session start-to-close timeout on a live host, the refused block was caught and a new block opened at once; its get returned A and its put(B) went to the timed-out attempt, which kept running for about five seconds after its timeout, and 40 s later get returned EMPTY from the new session. The README's 'keep one McpToolset open for an async with block' and the body's catch-and-reopen advice both imply isolation. At minimum, document that a same-name block is not isolated until the previous session has stopped (up to about 30 s). A code fix needs the new block to tell the old session that it has been superseded, for example a per-block token from workflow.uuid4() in a header on the session and its operations, so an older session stops and fails newer-token operations as retryable, or a bounded wait in cleanup() for the session to stop. A test with two healthy consecutive blocks would pin either.
There was a problem hiding this comment.
Agreed. It's pre-existing, and the catch-and-reopen advice walks into it. 3059bfa documents it in the README: a later block with the same name can reach the earlier block's session until that session notices its cancellation, which can take one heartbeat interval. The code fix is tracked in #380, with a one-file reproduction on 88745dc (the second block's first get returns the first block's value, and its put is lost).
|
|
||
| **Stateful MCP toolsets:** `TemporalStatefulMcpToolSet` and `TemporalStatefulMcpToolSetProvider` keep one `McpToolset` open for an `async with` block, in a `-server-session` activity. Temporal cannot recreate that toolset's state on another worker. If the session activity is retried after its toolset opened an MCP session, for example after a graceful worker shutdown or a lost host, the retry fails with a non-retryable `ApplicationError(type="DedicatedWorkerFailure")` instead of opening a new, empty session. Once the session activity has ended, `get_tools` and tool calls on the toolset, including any already waiting, fail with the same error type without waiting for a timeout, and the run fails when the `async with` block exits. An operation still pending when the session ends is cancelled, except with `cancellation_type=WAIT_CANCELLATION_COMPLETED`: no worker may be left to acknowledge that cancellation, so the operation is left to its own timeout while the caller fails at once. A later `async with` block with the same name in the same run does not run such an operation, whatever activity IDs `config` or `server_session_config` set: its session refuses any operation the server scheduled before it, with the same error type. A retry in which no session was opened builds the toolset again. | ||
|
|
||
| A retry after a lost host or a timed-out attempt also fails with `DedicatedWorkerFailure`, even when no session was opened: the worker sends heartbeats later, and the plugin cannot wait for one, so every heartbeat says a session may be open until the attempt ends without one. A retry after a failed factory or first connection, or after a graceful shutdown before any session opened, still builds the toolset. Before its first MCP session opens, the session activity reads its Workflow's description (`DescribeWorkflowExecution`) until the server shows that first heartbeat, so the worker's client needs permission to describe the Workflow. This is temporary. It will be replaced once the Python SDK offers a worker heartbeat the plugin can wait for. |
There was a problem hiding this comment.
P3 (docs, non-blocking): several user-visible consequences are missing from this section and from the class docstrings. (1) The default server_session_config start-to-close of one hour (_mcp.py:896-898) is now a hard cap on how long a block can stay open, even one that never listed tools, since the first heartbeat already says a session may be open: with a 6 s start-to-close and a 14 s block the head fails with DedicatedWorkerFailure in all three variants (no list, list, list and call), while base completes with two factory calls. Human-in-the-loop waits inside a block are the typical way to reach the hour. Say so here and in the server_session_config docstring, suggest raising the timeout, and consider raising the default now that a timeout is fatal. (2) ResetActivity or UnpauseActivity with reset_heartbeat=True clears the marker, so the run silently gets a new, empty MCP session and the in-flight operation is retried on it (probe: attempt 2 sees details [], builds, and the run completes); the body mentions this for resets only. (3) On the agent route ADK catches the toolset failure and keeps running turns without the tools until the block exits (google/adk/agents/llm_agent.py:220-244 logs 'will run without the tools from toolset ... which failed to load'); in a probe, turn 2 answered without tools before the run failed at block exit. (4) The provider docstring (_mcp.py:631-655) still says one toolset per workflow run and that the session activity runs on the run-scoped queue (both pre-existing: it is one toolset per block, and only the nested worker polls name@run_id), and neither class docstring mentions the refusal on deploys and graceful shutdowns, the heartbeat-interval floor, or the DescribeWorkflowExecution permission.
There was a problem hiding this comment.
Done in 3059bfa, in the README and the docstrings:
- The one-hour start-to-close is documented as the longest a block can stay open, with advice to raise it for long blocks and set a heartbeat timeout. We kept the default: without a heartbeat timeout, a longer one would delay noticing a lost host.
- Reset or unpause with
reset_heartbeat=Trueis documented. - The README describes the agent route.
- The provider docstring now says one toolset per block and that the nested worker serves
name@run_id. It also covers the refusal on deploys and shutdowns and the describe permission.
The heartbeat-interval floor is gone with the fix on line 426.
| if _SESSION_OPENED in details: | ||
| reason = "opened an MCP session" | ||
| elif _SESSION_MAY_BE_OPEN in details: | ||
| reason = "was lost after its first heartbeat and may have opened an MCP session" |
There was a problem hiding this comment.
P3 (non-blocking): this refusal says the earlier attempt 'was lost after its first heartbeat' also when it timed out on a live worker, often after it had opened a session whose marker Core was still holding back. Seen after a start-to-close timeout and after the heartbeat timeouts in the comment on line 426, both on a running host. Similarly, a tool kept from a block that has already exited gets 'The stateful MCP session activity has ended, so no worker serves this toolset's operations' with cause 'Activity cancelled': the block's own exit ended the session, which is a caller error, and with a later block open the queue is served. Suggest 'ended (it lost its worker, timed out, or was reset) without confirming that it opened no MCP session' here, and, for a session the workflow itself cancelled, a message saying the tool belongs to a block that has exited and the toolset must be listed again.
There was a problem hiding this comment.
Done in 3059bfa. The refusal now says the earlier attempt "ended (it lost its worker, timed out, or was reset) without confirming that it opened no MCP session". An operation on a session that the block's own exit cancelled says the session was cancelled, as when its block exits, and to list the tools again inside an open block.
| manager = getattr(toolset, "_mcp_session_manager", None) | ||
| if manager is None: | ||
| return False | ||
| create_session = manager.create_session |
There was a problem hiding this comment.
P3 (non-blocking): the fallback the body describes ('If ADK renames them, the toolset falls back to recording the marker before its first operation') covers only a missing _mcp_session_manager; a renamed create_session raises AttributeError here, inside the try whose finally deletes the registry entry. _RunningToolset(...) is built as the right-hand side of self._toolsets[server_id] = ... at line 756, so the assignment never happens, del self._toolsets[server_id] at line 775 raises KeyError and masks the AttributeError, toolset.close() is skipped, and every attempt fails the same way (probe with a manager that has no create_session). Use getattr(manager, "create_session", None) and return False when it is missing, and compute _record_opened_sessions(...) before the try (or pop(server_id, None) in the finally).
There was a problem hiding this comment.
Fixed in 3059bfa. _record_opened_sessions uses getattr(manager, "create_session", None) and falls back to recording before the first operation when either name is missing. The finally uses pop(server_id, None). No new test for this one. The body's fallback sentence is now true for both names.
| return frame is not None | ||
|
|
||
|
|
||
| class _DelayMayBeOpenCodec(PayloadCodec): |
There was a problem hiding this comment.
P3 (tests, non-blocking): two load-bearing branches are not pinned, and the frame-walking codecs can silently stop delaying. Mutations on the head, full file each: deleting await heartbeats.wait_until_stored() (_mcp.py:586, or 586 and 619) leaves 22/22 green, and so does deleting the early if session.done(): raise (_mcp.py:394-395). A test whose host codec takes 3 s per heartbeat and whose host is then killed passes on the head and fails 2 of 2 without the read-back (assert 1 == 0: the replacement host built a toolset), and parametrizing operation_after_refusal with WAIT_CANCELLATION_COMPLETED catches the early-raise removal (assert 2 == 1 list-tools scheduled). This codec and _DelayWorkerMarkerCodec find the SDK's _heartbeat_async, _handle_start_activity_task and encode_failure by walking frames; with those names changed, first_connection_fails_delayed_heartbeats still passes and no longer catches removal of the close() wait, and marker_kept_by_worker_heartbeats passes with no delay at all. Count the delays in each codec and assert that at least one heartbeat delay and one failure delay happened.
There was a problem hiding this comment.
Done in 3059bfa:
test_stateful_session_after_host_killed[heartbeat_timeout_slow_heartbeats]: the host's codec takes 3 s per heartbeat, and the host is then killed. It fails without the read-back (the retried session on the next host is not refused) and passes with it.test_stateful_operations_fail_after_session_refused[operation_after_refusal_wait_cancellation]fails withassert 2 == 1without the earlysession.done()raise.- Both frame-walking codecs count their delays. The tests assert at least one heartbeat delay and one failure delay, or one marker delay.
- Await a stateful operation itself, as main does, for every cancellation type but WAIT_CANCELLATION_COMPLETED, and cancel it from a callback on the session. Healthy runs keep main's resume order, and a cancellation that arrives with the operation's result is kept. Histories recorded on main with both shapes replay in test_stateful_mcp. - Heartbeat every half heartbeat_timeout when that is under 60 s. - Confirm the first heartbeat once in the session activity, before the factory, with a deadline; a describe refused for lack of permission fails the session with a non-retryable DedicatedWorkerFailure. - Raise ApplicationError(type="DedicatedWorkerFailure") from the block when the session failed with that type. - Fall back when MCPSessionManager.create_session is missing, clearer refusal and ended-session messages, and docs for the one-hour cap, resets, the agent route and same-name blocks (#380). - Pin the read-back and the early refusal with tests, and count the delays the frame-walking codecs add.
…ttps://github.com/temporalio/ai-integrations into fix/google-adk-python-stateful-mcp-session-replaced
…tion raise ... from err replaced the cause _session_ended_failure sets, so an operation the session's end cancelled was caused by its own cancellation and the session's refusal left the chain. The operations test now checks the error's causes.
…ses in every cancellation mode 3059bfa compared the time with the read-back's 30-second deadline only after describe() returned, and describe() had no rpc_timeout, so a stalled describe or a codec that never finished decoding kept the session activity waiting past it. The whole read-back now runs under one asyncio.timeout_at, and each describe gets the time left as its rpc_timeout. The operations test now records the error chain get_tools() raised inside the block for TRY_CANCEL, ABANDON and WAIT_CANCELLATION_COMPLETED, and the describe test covers a describe and a decode that never return.
… 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.
DABH
left a comment
There was a problem hiding this comment.
Second round, at head e9b0dbc: 3059bfa, 3b17169 and e9b0dbc since de1a1c1, plus merges of main that touch nothing under python/google_adk/src. make lint is clean. make test on a heavily loaded machine gave 208 passed, 5 skipped and one failure of test_stateful_session_marker_kept_by_worker_heartbeats, which passed 3 of 3 on its own (see the comment on its 6 s window); CI is green on all four cells with 209 passed. I reran the first round's reproductions against this head: the 21 histories recorded on main last round, the cancellation and timer races, the heartbeat-timeout, describe-permission, block-exit and missing-create_session probes, and pause and ResetActivity with and without reset_heartbeat. New findings were reproduced with real Workers on a local dev server, comparing main (61fe33a) with this head, or with histories recorded on one build and replayed on the other with Replayer; the coverage claims come from mutating each branch and running the whole stateful test file. Refuted: a change in commands or resume order on the default path in healthy runs (none, in either direction); a session that ends in the same workflow task as an operation's completion (the caller still gets the result, as on main); ResetActivity during the read-back and a retry while the previous attempt is still in it (both build exactly once, which is right since no session was opened); a cost or correctness problem in beat()'s two asyncio.all_tasks() scans (0.5 ms per beat at 10k live tasks and 27 ms at 100k, once per heartbeat interval, and they captured exactly the heartbeat task every time); an eviction hang with a WAIT_CANCELLATION_COMPLETED server_session_config (identical on main). Not verified: google-adk 2.13, the HTTP and SSE transports, real Temporal Cloud authorization (describe errors were simulated with a client interceptor), the SDK's single-batch activation flag (off in 1.34), 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. Resume order: for every cancellation type except WAIT_CANCELLATION_COMPLETED, _execute_operation awaits the handle again; 19 of the 21 main-recorded histories from last round replay on this head, the two that fail are the session-ended shapes the body lists ([TMPRL1100] and an ActivityMachine error), the ParallelAgent history now replays with each branch's own answer, and histories of the same shapes recorded on this head replay on main. Dropped cancellation: a workflow cancel or an asyncio.timeout that lands with the operation's completion now ends CANCELED or TIMEOUT on both paths, and the twelve race histories recorded on main replay here. Also fixed and rechecked: the heartbeat interval (10 s with a 45 s block, 20 s with 90 s, and 1, 3 and 61 s all complete with one factory call); the describe permission (the session fails in about 20 ms, non-retryably, naming the permission, and the factory never runs; transient errors recover, persistent ones end at the deadline and the retry builds); the block-exit type after a refused retry (except ApplicationError catches it); the missing-create_session fallback; the docs (one-hour cap, reset_heartbeat=True, what ADK does with a failed get_tools, the provider docstring); the messages; and the test gaps (without the read-back heartbeat_timeout_slow_heartbeats fails, without the early raise operation_after_refusal_wait_cancellation fails with assert 2 == 1, and both codecs assert their delays). Accepted as decided: no version gate, with WAIT_CANCELLATION_COMPLETED keeping the workflow.wait hop and the break disclosed; same-name isolation documented and tracked in #380; the one-hour default kept. Every thread has a reply. Still open: the disclosure of the WAIT_CANCELLATION_COMPLETED break understates one case (comment on line 433).
Where the problems cluster: the first round's fixes hold, and the marker protocol held in every new path I tried (resets during the read-back, transient describe errors, heartbeat timeouts from 1 s to 61 s). The new defect comes from where 3059bfa put the read-back: between the duplicate-connect guard and the registration, which reopens a race that main's synchronous check-and-register did not have and turns a misuse that main reported ('Use a distinct name') into a hang. The rest is disclosure and coverage: the Replay section describes the WAIT_CANCELLATION_COMPLETED case as a loud failure when it can be a silent swap and misses a few rollback shapes, three branches added in this round are unpinned, one test's window is shorter than its worst case, and what leaves the block still varies with how the session ended.
Requesting changes for the duplicate-connect race (comment on line 864): it is introduced by this PR, leaves runs retrying KeyError for up to the session's start-to-close, and has a small fix that I tested.
PR body: the Replay section also misses these shapes, each recorded on one build and replayed on the other. (a) An operation with ActivityCancellationType.ABANDON waiting when the session ended breaks in both directions ([TMPRL1100] No command scheduled for event ... WorkflowExecutionFailed one way, an ActivityMachine error the other); the bullet says 'with the default cancellation type'. (b) A WAIT_CANCELLATION_COMPLETED operation waiting when the session ended, recorded on this change, fails on main with the same TMPRL1100; only the main-to-change direction replays. (c) A run that used the README's recovery (it caught the block's DedicatedWorkerFailure and opened a new block), recorded on this change, fails on main with [TMPRL1100] Fail workflow machine does not handle this event: HistoryEvent(id: 21, ActivityTaskScheduled), because main's cleanup raises the ActivityError that except ApplicationError misses; 'Such runs are already failing' does not hold for a run that recovered. (d) A WAIT_CANCELLATION_COMPLETED operation that completes in the same workflow task as a workflow cancel or an asyncio.timeout, recorded on this change, does not replay on main: line 438 re-raises without the SDK recording its RAISE_ON_CANCELLING_COMPLETED_ACTIVITY flag, so main replays it on the legacy path, with TMPRL1100 for the cancel, and for the timer a replay without error that returns the tool result where the run recorded TIMEOUT. These matter for a rollback; a sentence each is enough. Parity: TypeScript, Go and Java Google ADK still have no per-run stateful session (Go's NewMCPToolset caches one toolset per name on the Worker), so nothing is left inconsistent across the Google ADK languages; OpenAI Agents is covered by #372 and #373.
| try: | ||
| # No MCP session opens before the server holds the first | ||
| # heartbeat, which says a session may be open. | ||
| await heartbeats.wait_until_stored() |
There was a problem hiding this comment.
P2 (blocking): the read-back now runs between the duplicate-connect check (line 843) and the registration (line 867), so two same-name sessions in one worker process can both pass the check; the loser's finally then removes the winner's entry, and the surviving block's lists and calls fail with KeyError until the earlier session stops, or for the session's whole start-to-close.
Mechanism: the read-back takes about 100 ms locally (the first describe misses the heartbeat, then a 0.1 s sleep). A second session with the same name@run_id that starts in that window passes server_id in self._toolsets. Whichever registers second overwrites the entry; its nested Worker(...) then fails with Core's Registration of multiple workers with overlapping worker task types on the same namespace, task queue, and deployment build ID not allowed; and its finally (line 886) pops the entry while the first session's nested worker keeps polling with nothing behind it, so self._toolsets[_server_id()] (lines 793 and 808) raises KeyError on every attempt. Reproduced with one worker process, the default config and a real stdio server:
- Two concurrent same-name blocks (
asyncio.gatherof twoasync with TemporalStatefulMcpToolSet("race")coroutines): both sessions passed the check 1 ms apart, both blocks' firstlist-toolsfailed withKeyError: 'race-stateful@<run_id>'on every attempt, and the second session kept retrying with the registration error, never with the guard's 'Use a distinct name' message. The run failed after about a minute with the rawKeyErroronly because its execution timeout capped the operation's retries. Main fails the second session with 'Cannot connect to an already running toolset. Use a distinct name...' and completes. - Consecutive same-name blocks, where block 1 awaits one fast activity and exits and block 2 opens at once: 4 of 6 runs raced with no timing lever. In 3, block 2's operations failed with
KeyErrorfor 31 to 34 s, until block 1's session saw its cancellation at its next heartbeat. In 1, block 2's session had registered first and stayed healthy, and every attempt failed withKeyErroruntil the run's execution timeout. Forcing that ordering with a 40 s session start-to-close and no run timeout, the run stayed stuck until that start-to-close, when the retry was refused and the run failed with 'An earlier attempt ... opened an MCP session', although no worker had failed. With the defaultserver_session_configthat is an hour, and longer for callers who follow the README's advice to raise it. The README's catch-and-reopen shape after a fast failure in block 1 stalled for 32 s. Main: 5 of 5 complete with noKeyError(block 2's session retries with 'Cannot connect', the [Bug] google_adk: a second stateful MCP block with the same name reaches the first block's MCP session #380 behaviour).
Introduced in 3059bfa: at de1a1c1 and on main there is no await between the check and the registration. Reopening after a refused retry does not reach it (the refused attempt fails at line 840 first), and retries of one session cannot race each other (the marker refuses the successor). Fix: reserve the name before the first await and remove only this attempt's entry, for example a self._starting: set[str] checked together with self._toolsets at line 843, added before _SessionHeartbeats() and discarded in the outer finally, and if self._toolsets.get(server_id) is running: del self._toolsets[server_id] in place of the pop. With that change the six consecutive runs, a forced reverse ordering and the concurrent case all completed as on main, with only 'Cannot connect' retries. Re-checking the guard right after wait_until_stored() also closes it, at the cost of the losing session's read-back. A test with two same-name blocks on one worker, the first exiting after a quick activity and a client interceptor delaying only the first describe_workflow, would pin it; a concurrent variant can assert the guard's message.
There was a problem hiding this comment.
Thanks, fixed in bc76fd3 as you suggested. The session activity holds its run-scoped name in self._sessions for its whole attempt: from right after the duplicate check (nothing awaits in between) until its outer finally. The check now uses that set. A second same-name session fails with 'Cannot connect to an already running toolset' and retries, as on main.
test_stateful_sessions_with_one_name_in_one_worker: block 1 exits while its session is still in a read-back, which a client interceptor slows by 3 s. Block 2 opens with the same name and lists its tools once that read-back is over. Without the reservation the run fails with KeyError: 'stateful_server-stateful@<run_id>'; with it the run completes.
| finally: | ||
| session.remove_done_callback(cancel_operation) | ||
| try: | ||
| await workflow.wait([operation, session], return_when=asyncio.FIRST_COMPLETED) |
There was a problem hiding this comment.
P2: with WAIT_CANCELLATION_COMPLETED, a history in which the stateful operation and another activity resolve in one workflow task, the stateful one first, replays across this upgrade without any error when the two follow-up commands are the same activity type, and hands each branch the other's result; the body's 'such a history does not replay across builds' describes only the distinct-type case.
Recorded on main and replayed on this head with Replayer, and the reverse, with WAIT_CANCELLATION_COMPLETED in the operations' config: with distinct follow-up types (noop_a_activity, noop_b_activity) replay fails with [TMPRL1100] Activity type of scheduled event 'noop_a_activity' does not match activity type of activity command 'noop_b_activity'. With the same follow-up type, replay succeeds and returns ['{"released": "hold-a"}/noop:B', 'other:hold-b/noop:A'] for a run that recorded noop:A and noop:B. An ADK ParallelAgent whose branches are a stateful toolset and an activity_as_tool (both follow-ups are invoke_model) replays without error with branch_mcp answering done-b and branch_other done-a, the reverse of what was recorded. Core compares activity types, not inputs, so a run that crosses the deploy, in either direction, carries on with exchanged model responses. It happens only when the stateful operation resolves first; the reverse order schedules the same commands on both builds, and the default-type versions of all three shapes replay correctly both ways. Since there is no gate, state the silent case in the body and, as users never see the body, in one README sentence, for example: 'a gather whose branches next run the same activity type, as the model calls of an ADK ParallelAgent do, replays without an error and hands each branch the other's result; let such runs finish before deploying'. A workflow.patched check around this branch would remove the case.
There was a problem hiding this comment.
Agreed. bc76fd3 adds the silent case to the README's list of consequences: if the branches next run the same activity type, as the model calls of an ADK ParallelAgent do, a run that crosses an upgrade or a rollback replays without an error and hands each branch the other's result, so let such runs finish before deploying. The body's Replay section says the same. No gate, as decided.
| try: | ||
| await workflow.wait([operation, session], return_when=asyncio.FIRST_COMPLETED) | ||
| except asyncio.CancelledError: | ||
| if operation.done(): |
There was a problem hiding this comment.
P3 (tests): three branches added in this round are not pinned by any test. Mutations on this head, each run against the whole tests/test_stateful_mcp.py (32 cases): removing this if operation.done(): raise (the first round's dropped-cancellation fix on the WAIT_CANCELLATION_COMPLETED path) leaves all 32 green; so does dropping the pending.attempt != self._attempt comparison at line 591; and so does treating every describe RPCError as a refusal at line 570, under which a transient UNAVAILABLE would fail the session non-retryably. The other mutations I tried are caught: the cancelled_by_session handling, the done-callback, the cleanup() re-wrap, the heartbeat interval, the refusal set, the deadline conversion and the wait in close(); and the mutation results the body cites for the read-back, the early raise and 3059bfa's _mcp.py hold. Suggested tests: a WAIT_CANCELLATION_COMPLETED call that completes in the same workflow task as a workflow cancel (stop the workflow worker, let the call finish, cancel, restart the worker) must end CANCELED; and a describe interceptor that raises UNAVAILABLE once and then delegates must build the toolset exactly once.
There was a problem hiding this comment.
Done in bc76fd3:
tests/histories/stateful_mcp_cancel_wait.jsonwas recorded on 88745dc: aWAIT_CANCELLATION_COMPLETEDcall completes in the same workflow task as a workflow cancel, and the run endsCANCELED.test_stateful_mcp_histories_from_main_replayreplays it. With theoperation.done()raise removed, it fails with an ActivityMachine error; it also failed on de1a1c1.test_stateful_session_without_describe_permission[other_attempt_once]: an interceptor raises the pending attempt in the first describe. The session must reach attempt 2 and build once. With the comparison dropped, it fails withassert 1 == 2.[unavailable_once]:UNAVAILABLEonce, then the real describe. The session stays on attempt 1 and builds once. When everyRPCErrorcounts as a refusal, the session fails and the run with it.
| StatefulMcpWorkerReplacedWorkflow.wait_listed | ||
| ) == ["echo"] | ||
| # Watch the worker's delayed heartbeats arrive. | ||
| await asyncio.sleep(6) |
There was a problem hiding this comment.
P3 (tests): this 6 s window is shorter than the worst case for the marker to reach the server, so the test can fail on a correct implementation when the session opens late. The marker heartbeat takes 3.5 s to encode, and Core then sends it at its next throttle boundary, every 4 s with this 5 s heartbeat timeout. Measured on this head: the session opens about 3.3 s after the first heartbeat, the marker lands at the 8 s boundary and the window closes at about 9.4 s, a margin of 1.0 to 2.7 s. With the MCP server starting in 5 s instead of 2.5 s, the marker landed at the 12 s boundary after the window had closed in 4 of 5 runs. Here one full run under load failed with assert True in observed (every observation False), and the test passed 3 of 3 on its own. Wait for the first True with a deadline (say 15 s after wait_listed), then keep observing a few seconds to check that the marker stays.
There was a problem hiding this comment.
Fixed in bc76fd3. The test now waits up to 15 s after wait_listed for the first True, then keeps observing for 3 s to check that the marker stays.
| raise | ||
| if is_cancelled_exception(e): | ||
| return | ||
| if ( |
There was a problem hiding this comment.
P3: what leaves the block still depends on how the session ended, and in two cases differs from what the calls inside it raised. (1) Only a session that failed with DedicatedWorkerFailure is re-wrapped here, while _session_ended_failure wraps every ending for the calls inside the block. With a session retry policy of one attempt, a graceful shutdown or a start-to-close timeout leaves the block as ActivityError <- ApplicationError(WorkerShutdown) or ActivityError <- TimeoutError(START_TO_CLOSE), and a factory error as ActivityError <- ApplicationError(<factory's type>), although get_tools inside the block raised DedicatedWorkerFailure in each case; the class docstring (lines 967 to 971) says that error leaves the block. Either re-wrap every non-cancellation ActivityError here, keeping it as the cause, or say in the docstring and README that only a refused retry does. (2) A tool kept from an earlier block now fails in a later block; on main its call ran, served by the earlier block's session. When that call is the later block's first await, this block's session has not started yet, so await session raises asyncio.CancelledError, which except Exception does not catch, and the run fails with a bare CancelledError: Cancelled instead of the new 'List the toolset's tools again' message. The masking predates this PR (async with ts: raise ValueError() fails the same way on main), but this PR adds a synchronous raise that reaches it. Treat a session cancelled before it started as cleaned up (except asyncio.CancelledError: if session.cancelled(): return; raise), and add 'list the tools again inside each block' to the body's breaking-change paragraph.
There was a problem hiding this comment.
Both fixed in bc76fd3:
cleanup()now re-wraps every non-cancellationActivityErrorfrom the session, keeping it as the cause. So the block raisesDedicatedWorkerFailurewhatever ended the session, as the calls inside it do, and the docstring says so.cleanup()treats a session cancelled before it started as cleaned up. It still re-raises when its own task is being cancelled, so a workflow cancel isn't swallowed.
test_stateful_block_exit_error[factory_fails] (a one-attempt session whose factory raises) and [tool_from_earlier_block] pin them. With the earlier re-wrap rule, [factory_fails] fails. Without the CancelledError handling, [tool_from_earlier_block] fails with a bare CancelledError('Cancelled'). The README and the body's breaking-change paragraph now say to list the tools again inside each block.
| "The stateful MCP session activity confirms its " | ||
| "first heartbeat with DescribeWorkflowExecution, " | ||
| "and the server refused it " | ||
| f"({err.status.name}: {err.message}). Give the " |
There was a problem hiding this comment.
P3: the refusal message gives the permission advice for every status in _DESCRIBE_REFUSALS, including NOT_FOUND, UNIMPLEMENTED and INVALID_ARGUMENT, where permission is not the cause. With describe_workflow answering NOT_FOUND (simulated with a client interceptor), the session fails with '... and the server refused it (NOT_FOUND: ...). Give the worker's client permission to describe workflows in this namespace.' Failing fast is right; only the advice is wrong. Keep it for PERMISSION_DENIED and UNAUTHENTICATED, and otherwise say that the server could not describe this workflow run.
- Hold a session's run-scoped name for its whole attempt, from the duplicate-connect check on: the read-back awaits, and a second session with the same name could pass the check meanwhile, after which one session's cleanup removed the other's toolset (KeyError on every call). - Raise DedicatedWorkerFailure from the block whatever ended the session, and treat a session cancelled before it started as cleaned up. - Give the describe permission advice only for PERMISSION_DENIED and UNAUTHENTICATED. - README: the silent WAIT_CANCELLATION_COMPLETED reordering across an upgrade, and listing the tools again inside each block. - Tests: same-name sessions in one worker, a main-recorded WAIT_CANCELLATION_COMPLETED cancel history, a transient describe error, a describe that shows another attempt, the block-exit error for a failed factory and for a tool from an earlier block, and a marker window that waits for the marker.
|
Thanks for the second round. All six threads are answered in bc76fd3, with a reply in each:
The body's Replay section now covers your shapes (a) to (d): |
DABH
left a comment
There was a problem hiding this comment.
Third round, at head bc76fd3, one commit since e9b0dbc. Main has moved to 017d88a without touching _mcp.py, and the PR still merges cleanly. make lint is clean, make test gives 215 passed, 5 skipped, the stateful file passed four more times (three with -n 4, one with -n auto), make build, check_wheel.py and check_conventions.py pass, and CI is green on all four cells. I reran last round's duplicate-connect reproduction against this head (below). New findings were reproduced with real Workers on a local dev server, comparing main (017d88a) with this head, and with e9b0dbc where attribution mattered, or with histories recorded on one build and replayed on the other with Replayer. Coverage claims come from mutating each branch and running the whole stateful file. Refuted: a change to healthy-run commands at bc76fd3 (the 31 workflow and 10 block-exit histories recorded on e9b0dbc last round all replay here, and the main-recorded ones give last round's results; the one e9b0dbc history that no longer replays is the raise-first block in the comment on line 1076); a leaked name or _sessions/_toolsets disagreement on any exit path, including a cancel that lands inside close(); a 'Cannot connect' attempt clearing or reviving a marker; a fast-failing attempt losing its retry to its own reservation (the name is released before the failure is reported); and the cancelling() guard misfiring under asyncio.timeout or in ADK's close task. Not verified: google-adk 2.13, the HTTP and SSE transports, real describe stalls and codec faults (simulated with a client interceptor and a payload codec), the SDK's single-batch activation flag, a live Workflow worker swap (cross-build results come from Replayer), 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. The blocking race is fixed. With the name reserved before the read-back, these runs of last round's reproduction on this head all completed with only 'Cannot connect to an already running toolset' retries, and no KeyError, Core registration error or overwritten entry, as on main: six consecutive same-name runs, the concurrent case, the forced reverse ordering (with the default session timeout, and with a 40 s start-to-close and no run timeout), and the README's catch-and-reopen shape. test_stateful_sessions_with_one_name_in_one_worker fails with that KeyError without the reservation. Also addressed:
- The silent
WAIT_CANCELLATION_COMPLETEDswap is in the README and the body. - The previously unpinned branches are pinned: each of the six mutants the body lists fails exactly the test it names.
- The marker test waits for the marker. It appeared 5.2 s after
wait_listed(6.7 s with a 5 s MCP start), leaving at least 8 s of the window. - The block raises
DedicatedWorkerFailurewhatever ended the session, and a tool from an earlier block gets the 'List the toolset's tools again' message. Both have side effects (comments on lines 1070 and 1076). - By probe,
NOT_FOUNDandUNIMPLEMENTEDnow say the server could not describe the run, whilePERMISSION_DENIEDandUNAUTHENTICATEDkeep the permission advice. - The Replay section covers last round's (a) to (d), which behave as listed when re-recorded on this head.
Every thread has a reply. Accepted as decided: no version gate, same-name isolation tracked in #380, the one-hour default. Still open from earlier rounds: none.
Where the problems cluster: the worker-side protocol and the race fix hold. The new items come from the two changes in bc76fd3 that I suggested last round, and neither suggestion was quite right. The 'cancelled before it started' test in cleanup() also matches a session that ended on its own in the block's last workflow task. The re-wrap changes what main's callers catch, and what replays, without a word in the breaking-change or Replay sections. The reservation holds the name while the earlier session serves nothing. The rest is tests and stale body text.
Commenting rather than approving: nothing blocking remains, but the two P2s, the swallowed session end at block exit and the undisclosed change in what leaves the block (which breaks replay for runs recorded on main that caught the ActivityError), are small and worth settling before merge.
PR body and README (P3):
- 'Workflow code in this change is the same as
bb9b322's; replay was not rerun this round' is no longer true:_execute_operation,_session_ended_failureandcleanup()have changed since. The two-block replay result it carries forward is unverified at this head. - 'On this change (on top of
c68bb8a)' describes an older build. - In the third Replay bullet, the timer finding came from the second review. For the PR's own workflow, the cancel history fails on main with an ActivityMachine error. For a workflow that completes after the call it fails with
[TMPRL1100] Complete workflow machine does not handle this event ... WorkflowExecutionCanceled, so 'a nondeterminism error' covers both. - In the README, the
WAIT_CANCELLATION_COMPLETEDbullet applies only when the stateful list or call resolves first, and 'clears the marker' uses a term the README never defines. - Pre-existing, but the body and README now promise the failure at block exit: on the agent route,
await runner.close()inside the block runstoolset.close()in ADK's own task, which logsError closing toolset TemporalStatefulMcpToolSet: ...and drops the error. The block then exits cleanly and the run completes, on main too. Either keep the failure for__aexit__, or say so.
Parity: unchanged. TypeScript, Go and Java Google ADK have no per-run stateful session (Go's NewMCPToolset is stateless), and OpenAI Agents is tracked by #372 and #373.
| # A session cancelled before it started ends without an | ||
| # ActivityError. Keep a cancellation of this coroutine itself. | ||
| current = asyncio.current_task() | ||
| if session.cancelled() and not (current and current.cancelling()): |
There was a problem hiding this comment.
P2 (non-blocking): session.cancelled() is also true for a session that ended on its own in the same workflow task as the block's exit, so this branch returns and the block exits without the DedicatedWorkerFailure that the docstrings and README promise.
This is the check I suggested last round, and it is not precise enough. If the session's failure is already in its handle but the handle's task has not stepped yet, session.cancel() makes the SDK drop the result and re-raise the cancellation (_await_temporal_operation, flag RAISE_ON_CANCELLING_COMPLETED_ACTIVITY). The handle then ends cancelled, with no ActivityError. A body woken by a timer runs before the session's task, so this happens when the block's last await is workflow.sleep() or a wait_condition(..., timeout=...) and the timer and the session's end land in one workflow task, timer first. A wake by an activity resumes after the session's task, so the failure is consumed first.
Reproduced by stopping the workflow worker until both events were in history, then restarting it:
- Default session retry policy;
async with ...: await ts.get_tools(); await workflow.sleep(4); the session host shut down gracefully after the timer fired, and a second host refused the retry (13 TimerFired,16 ActivityTaskFailed'An earlier attempt of this stateful MCP session activity opened an MCP session...'). The run completed with 'block exited normally', and the worker only loggedFuture exception was never retrieved | ActivityError. That is the deploy this PR is about, with a workflow worker that restarts too. - A one-attempt session ended by a graceful shutdown, a one-attempt start-to-close timeout, and a person-wait
wait_condition(lambda: approved, timeout=4): all three complete on this head. Main fails them with a bareCancelledError: Cancelled, as e9b0dbc would (it let theCancelledErrorthrough). - Control, with the session's end first in history:
DedicatedWorkerFailure <- ActivityError <- WorkerShutdown, as documented.
The timer-first histories do not replay across builds: one way fails with [TMPRL1100] Complete workflow machine does not handle this event: HistoryEvent(id: 19, WorkflowExecutionFailed), the other with Fail workflow machine ... WorkflowExecutionCompleted. The block's operations had all finished, so nothing ran on a lost session; what is lost is the error.
Separately, the cancelling() guard has no test: removing it leaves all 38 stateful tests green. After a caught workflow cancel, cancelling() stays 1, so in compensation code a block whose body fails before its first await still leaves as a bare CancelledError, as on main.
Fix (tested): decide "never started" before cancelling, and compare the cancel count around the await:
started = inspect.getcoroutinestate(session.get_coro()) != inspect.CORO_CREATED
current = asyncio.current_task()
cancels = current.cancelling() if current else 0
session.cancel()
try:
await session
except asyncio.CancelledError:
if not session.cancelled() or (current and current.cancelling() > cancels):
raise
if not started:
return
# The session ended in this workflow task, and the SDK dropped its failure.
raise ApplicationError(
"The stateful MCP session activity has ended, so no worker serves "
"this toolset's operations.",
type="DedicatedWorkerFailure",
) from NoneWith it:
- every timer-first shape fails with
DedicatedWorkerFailure, with no cause because the SDK has already dropped it; - the empty and raise-first blocks keep this head's outcomes;
- the compensation cases surface the body's error;
- the one-attempt timer-first history recorded on main replays with the fix, and the reverse, since both builds then end in a failure;
- the 38 stateful tests pass.
A test that stops the workflow worker until TimerFired and the session's end are both in history would pin it.
There was a problem hiding this comment.
Thanks, fixed in 4e8708b with your change. cleanup() decides before cancelling whether the session's task ever ran (inspect.getcoroutinestate(session.get_coro()) == CORO_CREATED). It compares current_task().cancelling() before and after the await, instead of testing it for truth. A session that ended in the block's last workflow task, whose failure the SDK dropped, now raises DedicatedWorkerFailure with no cause.
test_stateful_session_ends_with_the_blocks_last_timer stops the workflow worker until TimerFired and the one-attempt session's ActivityTaskFailed (graceful shutdown) are both in history, then expects DedicatedWorkerFailure. With bc76fd3's branch it fails with DID NOT RAISE (the block exited cleanly). test_stateful_block_exit_error[compensation_raise_first] covers the cancel count: after a caught workflow cancel, a block whose body raises before its first await leaves with the body's error. With the cancel count tested for truth, it ends cancelled instead.
| raise | ||
| if is_cancelled_exception(e): | ||
| return | ||
| if isinstance(e, ActivityError): |
There was a problem hiding this comment.
P2 (non-blocking): this re-wrap, which I asked for last round, also changes what leaves the block for endings main already had, so code that catches ActivityError around the block stops catching it and runs recorded on main that caught it and continued fail replay here, and neither the body nor the README says so.
On main, a session that ends on its own leaves the block as its ActivityError. A probe with except ActivityError around the block tried three endings: a factory that raises ApplicationError(..., non_retryable=True) under the default retry policy, a one-attempt factory error, and a one-attempt start-to-close timeout. Main catches all three. On this head all three miss, and only except ApplicationError catches them, with type DedicatedWorkerFailure and the ActivityError as its cause.
Replay:
- A main history in which the workflow caught the
ActivityErrorand ran a fallback activity fails here with[TMPRL1100] Fail workflow machine does not handle this event: HistoryEvent(id: 16, ActivityTaskScheduled). It replays at e9b0dbc. - The same shape recorded on this head fails on main.
- Without a catch, both builds fail the run and replay in both directions.
So such a run that is still open at the upgrade gets stuck on its workflow task.
The new CancelledError branch changes two more main outcomes:
- An empty block now completes, where main failed it with
CancelledError('Cancelled'). - A body that raises before its first await now leaves with its own exception. A non-Temporal one fails the workflow task, as anywhere else in workflow code.
The empty and caught shapes do not replay across builds, and last round's reuse_raise_first history no longer replays here. These are improvements, but they are breaking.
Fix:
- In "Breaking change (callers)" and the README, say that a session that ends on its own for any reason now leaves the block as
ApplicationError(type="DedicatedWorkerFailure")with theActivityErroras its cause, where main raised theActivityError. Callers should catchApplicationError(orFailureError). - In the Replay section, add that two kinds of run do not replay across builds: a run that caught the block's error after its session ended on its own, and a run with a block left before its first await.
There was a problem hiding this comment.
Agreed, disclosed in 4e8708b:
- The README and the body's breaking-change paragraph say that a session that ends on its own, for any reason, now leaves the block as
ApplicationError(type="DedicatedWorkerFailure")with theActivityErroras its cause, where main raised theActivityError, and to catchApplicationError(orFailureError). - The Replay section adds that a run that caught the block's error after its session ended on its own, and a run with a block left before its first await, do not replay across builds.
| # Hold the name until this attempt ends: the read-back below awaits, | ||
| # and another session with this name must not pass the check above | ||
| # meanwhile. Nothing since the check has awaited. | ||
| self._sessions.add(server_id) |
There was a problem hiding this comment.
P3: the reservation holds the name for the whole attempt, including the read-back (up to 30 s) and heartbeats.close() (no time limit) while the earlier session serves nothing, so a later same-name block can now fail where main and e9b0dbc served it.
This is the shape I suggested last round. The later block's session retries 'Cannot connect' at about +0, 1, 3, 7 and 15 s, so a hold longer than 15 s outlasts the operations' 30 s schedule-to-start in the default config. Setup: one worker, a block that exits after 1 s, and a same-name block that lists at once. Describe stalls and slow encodes were simulated with a client interceptor and a payload codec.
- First describe never answered: block 2's list fails at 31 s with
DedicatedWorkerFailure: MCP Stateful Server Worker failed to schedule activity. e9b0dbc and main list in about 0.27 s. - First heartbeat encode takes 20 s: the same failure. e9b0dbc lists in 0.36 s.
- First heartbeat encode hangs: blocks 2, 3 and 4 (the README's catch-and-reopen) fail at 31, 61 and 91 s, and only the worker's shutdown releases the name. A shutdown that arrives while the session is still in its read-back hangs in that same wait in
close()instead. That part predates bc76fd3:worker.shutdown()did not return within 45 s, while main returns at once. - A timed-out attempt still in
close()makes its own retry fail with '... Use a distinct name if running multiple stateful toolsets in one workflow'. Withmaximum_attempts=2, that ends the session, although the run has one name.
With no faults, the timings equal main's.
Fix (verified): drop the reservation, and check self._toolsets again right after wait_until_stored(), with no await before the registration. That is the alternative from last round. With it:
- the stalled and hung cases list in about 1.4 s;
- the concurrent and consecutive races end with only 'Cannot connect' retries;
test_stateful_sessions_with_one_name_in_one_workerpasses.
Also bound the wait in close(): asyncio.wait(..., timeout=...), skipping the clear if anything is still pending. The retry is then refused, as the comment there already allows.
There was a problem hiding this comment.
Fixed in 4e8708b with the alternative. The reservation is gone. The session checks self._toolsets again right after wait_until_stored(), with no await before the registration, and its cleanup removes the entry only if it is still its own. A session that stalls in its read-back no longer holds the name, and a timed-out attempt still in close() no longer refuses its own retry.
The wait in close() is bounded by _CLOSE_TIMEOUT (10 s), with one change from your suggestion: after the limit it sends the clear anyway instead of skipping it. The SDK sends the attempt's completion only after its last heartbeat task (_activity.py, 'Do final completion'), so skipping the clear leaves a hung encode as that last task, and the attempt still never completes. The clear has no details to encode, so its task finishes at once. It is still safe: close() only clears when no session opened, so a slower heartbeat that lands later only makes the retry refuse. test_stateful_session_without_describe_permission[heartbeat_encode_stalls] makes every 'may be open' encode hang. The attempt must still end at the read-back deadline and be retried. With close() skipping the clear, or waiting with no limit, it hangs until the pytest timeout. Without the second check, test_stateful_sessions_with_one_name_in_one_worker fails.
There was a problem hiding this comment.
Follow-up to round 3, thread on close(): dbc434f sends the clear in a finally, so it also goes out when a worker shutdown interrupts the bounded wait. In 4e8708b an interrupted wait still left a hung encode as the attempt's last heartbeat task, so the shutdown hung. That's the case you described, and the 10 s limit alone didn't cover it. The clear has no details to encode, and it is only sent when no session opened, so a slower heartbeat that lands later can only make the retry refuse. test_stateful_session_worker_shutdown_while_closing makes every "may be open" encode hang and shuts the worker down while the attempt waits in close(); the shutdown must finish within 20 s. With 4e8708b's close(), it times out. The 43 stateful tests and make lint pass. #373 made the same change at your request there.
|
|
||
|
|
||
| @pytest.mark.timeout(90) | ||
| async def test_stateful_sessions_with_one_name_in_one_worker(client: Client): |
There was a problem hiding this comment.
P3 (tests): one round-2 fix is unpinned, and this test would stop pinning the race without notice.
- Nothing checks the new wording for
NOT_FOUND,UNIMPLEMENTEDandINVALID_ARGUMENT: giving the permission advice for every refusal leaves all 38 stateful tests green. A[not_found]case asserting 'could not describe this workflow run', and no 'permission', would pin it. - This test passes on this head only because block 1's cancelled session serves block 2's list ([Bug] google_adk: a second stateful MCP block with the same name reaches the first block's MCP session #380). Block 2's session reaches the check about 1 s into the 3 s read-back, gets 'Cannot connect' three times and never builds. With block 2's session starting more than 2 s later under load, the test would also pass on the no-reservation mutant.
The concurrent variant suggested last round reproduces the race without an interceptor and can assert the guard's message: an asyncio.gather of two same-name blocks gives KeyError 3 of 3 times on the mutant, and [['echo'], ['echo']] with 'Cannot connect' retries on this head.
There was a problem hiding this comment.
Both done in 4e8708b:
test_stateful_session_without_describe_permission[not_found]checks for 'could not describe this workflow run' and that no message mentions permission. With the permission advice for every refusal, it fails.- The race test no longer depends on timing. The first session's first describe is held until the second session has registered; the test sees the entry in the provider's toolsets, and only the second session can have made it. The first session must then be refused, and the second block is served by its own session with one factory call. I tried your concurrent variant first. With the re-check, whichever session finishes its read-back first registers. When that is the later-scheduled one, it refuses the other block's list as 'belongs to an earlier stateful MCP session' (3 of 5 runs). Concurrent same-name blocks are the misuse the guard names, so I kept the consecutive shape.
- cleanup(): decide before cancelling whether the session's task ran, and compare the cancel count around the await. A session that ended on its own in the block's last workflow task, whose failure the SDK drops on cancel, now raises DedicatedWorkerFailure instead of letting the block exit cleanly. - Replace the name reservation with a second duplicate check right after the read-back, before the registration, so a stalled session no longer holds the name. Remove the toolset entry only if it is still this session's. - close(): wait at most _CLOSE_TIMEOUT for earlier heartbeats, then clear anyway, since the worker reports the attempt only after its last heartbeat task. - README: what leaves the block compared with earlier versions, runner.close(), and two corrections. - Tests: the block's last timer and the session's end in one workflow task, a caught workflow cancel before a block, NOT_FOUND wording, a hung heartbeat encode, and a race test that holds the first session until the second has registered.
|
Thanks for the third round. All four threads are answered in 4e8708b, with a reply in each, and CI passes there:
The body and README now say what leaves the block compared with |
A worker shutdown that interrupted close()'s wait for earlier heartbeats left a hung heartbeat encode as the attempt's last heartbeat task, so the worker never reported the attempt and its shutdown hung. Send the clear in a finally: it has no details to encode, and a slower heartbeat that lands later only makes the retry refuse.
…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.
DABH
left a comment
There was a problem hiding this comment.
Fourth round, at head dbc434f (4e8708b and dbc434f since bc76fd3). Main is still at 017d88a, which doesn't touch _mcp.py, and the PR merges cleanly. make lint is clean, make test gives 220 passed, 5 skipped, and the stateful file (43 tests) passed four more times (three with -n 4, one with -n auto) at load averages up to 44. make build, check_wheel.py and check_conventions.py pass, and CI is green on all four cells. I reran last round's reproductions and round 2's duplicate-connect race against this head (below). New findings were reproduced with real Workers on a local dev server. I compared main (017d88a) with this head, used bc76fd3 where attribution mattered, and recorded histories on one build to replay on the other with Replayer. The 142 stored histories from earlier rounds were replayed on this head and on bc76fd3. Coverage claims come from mutating each branch and running the whole stateful file, and each fix suggested below passes make lint and all 43 stateful tests. Refuted:
- A retry that builds a toolset after an earlier attempt opened an MCP session, under any ordering I tried of the bounded wait, the clear, late heartbeats, cancels, resets and pauses. The clear is sent only while
_openedis False,record_openedrefuses once the attempt is closing, and Core drops a heartbeat that arrives after the completion. - An attempt that never completes behind a hung encode.
- The second check deleting or overwriting another session's entry. The identity-checked delete is now an equivalent mutant, and so is computing
startedaftercancel(). get_coro()returning anything but the coroutine for this handle, on CPython 3.11 to 3.14.- The cancel count misreading ADK's close task.
- A session activity that completes successfully: it is not reachable.
- The 'belongs to an earlier session' refusal with consecutive blocks or a single block.
Not verified: google-adk 2.13, the HTTP and SSE transports, real slow codecs and describe stalls (simulated with a payload codec and a client interceptor), the SDK's single-batch activation flag, a live Workflow worker swap, Python 3.11 with the real SDK, 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. Every item from last round is addressed, and round 2's race stays fixed without the reservation:
-
Duplicate-connect race. Round 2's reproduction now completes with only 'Cannot connect' retries, and with no
KeyErroror Core registration error, in each of these runs:- six consecutive same-name runs;
- the forced reverse ordering, with the default session timeout and with a 40 s start-to-close and no run timeout;
- the catch-and-reopen shape.
Without the second check,
test_stateful_sessions_with_one_name_in_one_workerfails with thatKeyError. Concurrent blocks are covered in the comment on line 742. -
Timer-first swallow. Last round's three timer-first shapes, including the deploy shape, now fail with
DedicatedWorkerFailure, and their histories replay against main in both directions. The new timer test fails with bc76fd3's branch, withstarted = False, and withreturnin place of the raise.[compensation_raise_first]fails with the count tested for truth. -
Re-wrap. The README, the breaking-change paragraph and the Replay section now describe it.
-
Reservation. A stalled first describe, a 20 s first heartbeat encode and a hung one no longer hold the name: the later block lists in about 1.45 s (main: 1.39 s). A timed-out attempt's own retry builds. With a hung encode,
worker.shutdown()returns after the 10 s bound, where bc76fd3 hung. dbc434f'sfinallysends the clear when a shutdown interrupts the wait: the server shows the next attempt with empty details, and that attempt builds. -
Tests.
[not_found]pins the wording. The one-name test now holds the first describe, and the first session was refused in every run. Each mutant the body lists fails the test it names: 4e8708b'sclose()times out the shutdown test, and skipping the clear or waiting without a limit hangs[heartbeat_encode_stalls]. -
PR body and README. Last round's stale lines are fixed, and the
runner.close()case is documented.
Every thread has a reply. Accepted as decided:
- no version gate;
- #380;
- the one-hour default;
- the consecutive shape for the race test, since concurrent same-name blocks are the misuse the guard names.
Still open from earlier rounds: none.
Where the problems cluster: the worker-side protocol held everywhere I pushed it, and the race and swallow fixes work. Once again, the new problems sit at the edges of last round's suggestions:
- The cancel-count comparison I suggested also catches a workflow cancel or an
asyncio.timeoutthat is already leaving the block. When the session ends in that same workflow task, the run now fails instead of being cancelled, and nothing discloses it (line 1090). - Without the reservation, the first read-back to finish wins. One of two concurrent same-name blocks can then fail with a message saying the other session has ended (line 742).
- Bounding the wait in
close()lets a heartbeat that encodes for more than 10 s land after the clear (line 664).
The rest is documentation that still describes bc76fd3, and test design.
Approving: every earlier blocking item is fixed, verified by rerunning its reproduction, and CI is green. What remains is one P2 in a narrow same-workflow-task race, which a small tested change or a disclosure settles, plus P3s. None of it is blocking.
PR body and README (P3):
- 'A session's run-scoped name is held for its whole attempt' describes the reservation that 4e8708b removed. The name is now checked before and right after the read-back, and held from registration until
toolset.close()returns. Of two same-name sessions in one worker, the one that finishes its read-back second fails with 'Cannot connect'. In the one-name test, that is the earlier block's session. - 'The attempt therefore waits for any heartbeat still being sent before it sends the clear' no longer holds. The attempt now waits at most 10 s and clears anyway, also when the wait is interrupted (comment on line 664). The internals list could add the SDK behaviour this relies on: the completion waits only for the last heartbeat task, and empty details skip the codec (
temporalio/worker/_activity.py, 'Do final completion' and_heartbeat_async). - 'A describe refused for lack of permission, or details it cannot decode, fail the session Activity with a non-retryable
DedicatedWorkerFailure' is incomplete.NOT_FOUND,UNIMPLEMENTEDandINVALID_ARGUMENTfail it non-retryably too, with the 'could not describe this workflow run' wording. - Release notes are generated from commit subjects, and the title names only the refused retry. Three other breaking changes reach users only if someone edits the release draft, as the body asks, or if the title is widened:
- the error type that leaves the block;
- the new describe permission;
- tools from an earlier block failing.
- The test module docstring (
test_stateful_mcp.py:19) says the tests run 'mostly against an in-memory fakeMcpToolset', but 5 of the 43 cases use it now. The comment on line 786 says the stalled heartbeat 'is still the attempt's last heartbeat task'. At this head the clear's task is the last one; the stalled one would be last without it. - Pre-existing, not introduced here:
cleanup()returns on a cancelledActivityErroreven when its own task was cancelled while it waited (_mcp.py:1103-1105, main 651-653). So a TaskGroup sibling failure during that wait lets the branch run its post-block code, on both builds. This head compares the cancel count only in theCancelledErrorbranch. Aligning the two would change commands relative to main and need a Replay line, so it can be a follow-up.
Parity: unchanged. TypeScript, Go and Java Google ADK have no per-run stateful session, and OpenAI Agents is tracked by #372 and #373.
| await session | ||
| except asyncio.CancelledError: | ||
| if not session.cancelled() or ( | ||
| current and current.cancelling() > cancels |
There was a problem hiding this comment.
P2 (non-blocking): comparing the cancel count also catches a workflow cancel or an asyncio.timeout that is already leaving the block. So when the session ends on its own in the same workflow task, cancellation first, the block raises a DedicatedWorkerFailure with no cause, and the run fails instead of being cancelled.
This comes from the change I suggested last round. The mechanism:
- A workflow cancel reaches the primary task one ready-queue hop after its job (
_apply_cancel_workflowusescall_soon(primary_task.cancel)), and anasyncio.timeouttimer does the same. - The session's resolution needs two hops to reach its handle task.
- So the body's
CancelledErrorreachescleanup()withcancelling()already at 1, andcancelscaptures that. session.cancel()makes the SDK drop the session's failure, and the count does not rise, so this branch raises.
bc76fd3 tested the count for truth and re-raised; main let the CancelledError escape.
Reproduced by stopping the workflow worker until both events were in history (session start-to-close 9 s, one attempt, unless noted):
- Timer body.
get_tools(), thenworkflow.sleep(300); a cancel request, then the session's timeout (13 WorkflowExecutionCancelRequested,16 ActivityTaskTimedOut, one workflow task). Main and bc76fd3 end CANCELED. This head ends FAILED withDedicatedWorkerFailureand no cause. A body waiting inwait_condition(lambda: False)behaves the same. - Deploy shape. Default retries; the cancel, then a graceful host shutdown and the refused retry. bc76fd3 ends CANCELED, this head FAILED.
- Compensation.
except asyncio.CancelledError:around the block. Main and bc76fd3 complete through the handler. On this head the handler never runs and the run fails. - Timeout.
asyncio.timeout(4)around the block, with theTimeoutErrorcaught. Main completes through the handler; this head fails. - Controls. With the session's end first in history, both builds fail (main with the
ActivityError). With a healthy session, a workflow cancel ends CANCELED on both.
Replay breaks in both directions with [TMPRL1100]:
- Recorded here, replayed on main:
Cancel workflow machine does not handle this event: HistoryEvent(id: 20, WorkflowExecutionFailed). - Recorded on main, replayed here:
Fail workflow machine does not handle this event: HistoryEvent(id: 20, WorkflowExecutionCanceled). - The
asyncio.timeouthistory recorded on main last round fails here withFail workflow machine does not handle this event: HistoryEvent(id: 19, WorkflowExecutionCompleted). Of the 142 stored histories I replayed, it is the only main-recorded one whose result changed without disclosure.
A main run of a catching shape that is still open at the upgrade would be stuck on its workflow task. The README, the docstrings, and the Breaking change and Replay sections don't mention any of this.
It does follow 'whatever ended the session', and it removes main's dependence on event order, so disclosing it is a valid resolution. But it turns a requested cancellation into a failure and skips compensation, so I'd keep the cancellation when the block is already leaving with one.
Fix (tested): have __aexit__ say whether it is leaving with a cancellation, and in that case return after the not started check:
async def cleanup(self) -> None:
await self._cleanup(keep_cancellation=False)
async def _cleanup(self, keep_cancellation: bool) -> None:
...
if not started:
return
if keep_cancellation:
# A workflow cancel or an asyncio.timeout reached the block
# before the session's failure: keep it, as earlier versions did.
return
...
async def __aexit__(self, exc_type, exc_value, traceback) -> None:
await self._cleanup(
keep_cancellation=exc_type is not None
and issubclass(exc_type, asyncio.CancelledError)
)With it:
- The cancel-first shapes end as on main and bc76fd3: CANCELED, completed through the handler, or
TimeoutError. - Last round's timer-first shapes still fail with
DedicatedWorkerFailure. - The empty, raise-first and
compensation_raise_firstblocks keep this head's outcomes. Keying onexc_typerather thancancels > 0keeps the new rule for a compensation block that exits normally after a caught cancel. - Every probe history recorded with the fix replays on main, and every main-recorded one replays with it, apart from the breaks the body already lists.
- It adds no commands, and cancellation propagates unchanged. The session's failure is dropped only when a cancellation got there first, as on main, and it stays in history as the session's failed or timed-out event.
make lintis clean and all 43 stateful tests pass.
A copy of test_stateful_session_ends_with_the_blocks_last_timer with a workflow cancel in place of the timer would pin it. If you keep the behaviour instead, say in the README and the Breaking change section that this error replaces a cancellation or timeout that reaches the block in the workflow task in which the session ends. Then add the shape to the Replay section.
There was a problem hiding this comment.
Thanks, agreed: a cancellation already leaving the block should stay a cancellation. Fixed in 83745c9, close to your suggestion:
__aexit__passes whether it is leaving with a cancellation to a private_cleanup(), which then returns after thenot startedcheck.cleanup()(also ADK'sclose()route) passesFalse.- I used the SDK's
is_cancelled_exception(exc_value)rather thanissubclass(exc_type, asyncio.CancelledError), so a body that leaves with anActivityErrorcaused by the workflow cancel also stays a cancellation. A compensation block that exits normally after a caught cancel keeps this head's error, as you suggested. test_stateful_session_ends_with_the_blocks_last_timeris now..._last_task, withtimer_first,cancel_first(your cancel-then-session-end shape, with the workflow worker stopped) andcancel_healthy.cancel_firstfails on dbc434f withDedicatedWorkerFailureand passes now; withcancellingalwaysFalseit fails again.- The README and the
cleanup()docstring say a workflow cancel or anasyncio.timeoutleaving the block in that workflow task stays a cancellation.
I didn't rerun your replay probes; the change adds no commands.
| "The stateful MCP session activity has ended, so no worker " | ||
| "serves this toolset's operations.", | ||
| type="DedicatedWorkerFailure", | ||
| ) from None |
There was a problem hiding this comment.
P3: on the path above, the block's DedicatedWorkerFailure has no cause. README line 205, the cleanup() docstring, and the body's Workflow side and Breaking change paragraphs say its cause is the session's ActivityError, and that earlier versions raised that ActivityError.
- In 4 of 4 runs of a probe built on the new timer test, the failure's cause chain held only the
ApplicationError. - On this path main never raised the
ActivityError. It raised a bareCancelledError, or, in the shapes of the comment above, cancelled the run or let aTimeoutErrorout. - The body's 'What callers see' paragraph does say 'or with no cause', so the body also contradicts itself.
Either say so wherever the cause is promised ('... or with no cause when the session ended in the workflow task in which the block exited; match on type'), or keep the promise. The dropped ActivityError is still in the handle's result future. Raising from it gave DedicatedWorkerFailure <- ActivityError <- ApplicationError(WorkerShutdown), and all 43 stateful tests pass:
fut = getattr(session, "_result_fut", None)
dropped = fut.exception() if fut is not None and fut.done() and not fut.cancelled() else None
raise ApplicationError(...) from droppedThat adds one more SDK private to the body's internals list. Retrieving the exception also silences the worker's 'Future exception was never retrieved' log.
Either way, have test_stateful_session_ends_with_the_blocks_last_timer assert the cause: err.value.cause.__cause__ is None, or the ActivityError. Today it would also pass on the ordinary from e path, so it doesn't pin this one.
There was a problem hiding this comment.
Thanks. I kept the disclosure rather than adding another SDK private. In 83745c9:
- README line 205 and the
cleanup()docstring say the error has no cause when the session ended in the workflow task that runs the cleanup. - The PR body's Workflow side, "What callers see" and Breaking change paragraphs now say the same, and that
mainraised aCancelledErroron that path. test_stateful_session_ends_with_the_blocks_last_task[timer_first]assertserr.value.cause.cause is None, so it no longer passes on the ordinaryfrom epath.
| # earlier block, which has ended, and must not run against this | ||
| # toolset. A retry keeps its first scheduled time. | ||
| raise ApplicationError( | ||
| "This operation belongs to an earlier stateful MCP session of " |
There was a problem hiding this comment.
P3: with the reservation gone, two same-name blocks open at the same time now fail about half the time. The failure message also tells the caller that a session which is still open 'has ended'.
Whichever session finishes its read-back first registers. Take an asyncio.gather of two async with TemporalStatefulMcpToolSet("race") blocks:
- The server schedules session A, A's list, session B and B's list in one workflow task, with increasing times.
- When B's session wins, A's list is older than it (
17:50:33.751180 < .751185), and this check refuses it non-retryably:WORKFLOW FAILED: ... DedicatedWorkerFailure: This operation belongs to an earlier stateful MCP session of this workflow run, which has ended. - That happened in 8 of 16 runs here; you saw 3 of 5. Main and bc76fd3 completed every run, with both blocks served by the first session.
- Consecutive blocks and single blocks can't reach it. A later session registers only while an earlier block is still open, or after it exited, when its operations really are leftovers.
This is the misuse the 'Cannot connect' message names, so I'm not asking you to support it. But the README never says so, and this message points the wrong way.
Fix, message and docs only (no code reads the text, so replay is unaffected):
- Reword the message, for example: 'This operation was scheduled before the stateful MCP session activity that now serves this toolset name in this workflow run, so it belongs to an earlier block with the same name, or to one open at the same time. Use a distinct name for each stateful toolset open at the same time.'
- Add to the README's same-name bullet that two blocks with the same name must not be open at the same time. One block's operations can then fail with
DedicatedWorkerFailure, or both blocks share one MCP session.
There was a problem hiding this comment.
Agreed, the message pointed the wrong way. In 83745c9:
- The refusal now says: "This operation was scheduled before the stateful MCP session activity that now serves this toolset name in this workflow run, so it belongs to an earlier block with the same name, or to one open at the same time. Use a distinct name for each stateful toolset open at the same time."
- The README's same-name bullet adds: "Don't open two blocks with the same name at the same time: one block's operations can then fail with
DedicatedWorkerFailure, or both blocks share one MCP session." - The PR body's "Later blocks" bullet says the same.
| # refuse. | ||
| try: | ||
| if self._sending: | ||
| await asyncio.wait(set(self._sending), timeout=_CLOSE_TIMEOUT) |
There was a problem hiding this comment.
P3: if a 'may be open' heartbeat is still encoding after the 10 s wait and lands before the attempt completes, the retry is refused even though the attempt opened no session. The refusal is non-retryable, and its message blames a lost worker, a timeout or a reset.
Probe setup: the factory raises once, a periodic 'may be open' encode takes 12 s, and the failure's encoded attributes take 4 s.
close()sends the clear at 11.52 s, and the late heartbeat is recorded at 13.01 s.- Core keeps the last details until the completion, so attempt 2 sees
['mcp-session-may-be-open']and is refused. The run fails. - bc76fd3 waited for the encode and built the toolset.
- A late heartbeat after the completion is harmless: Core drops it, and the retry builds.
So this needs a codec slower than 10 s whose failure encoding is slow too, for example with DefaultFailureConverterWithEncodedAttributes. It is never unsafe, but README line 207 ('A retry after a failed factory or first connection ... still builds the toolset') doesn't hold then.
Fix (tested): cancel the heartbeat tasks still pending before sending the clear:
finally:
# A heartbeat still being encoded must not land after the clear.
for task in list(self._sending):
task.cancel()
self._may_be_open = False
self.beat()Why it is safe:
- Only 'may be open' tasks can be pending here, because
record_openedsets_openedbefore its beat. - The SDK's
_heartbeat_asynccatches onlyException, so the cancel is neither swallowed nor reported as a heartbeat error. - The clear's task stays the last heartbeat task, which the completion awaits.
- A task cancelled before it started leaves its value queued, and the clear's task drains the queue and keeps the clear.
With it, the probe builds, the hung-encode shutdown still returns after the bound, and all 43 stateful tests pass. A codec that ignores cancellation falls back to today's refusal. If you'd rather not, say in the README and the body that the attempt waits at most 10 s, and that a slower heartbeat can make the retry refuse.
There was a problem hiding this comment.
Thanks, took your fix in 83745c9: in the finally, close() cancels the heartbeat tasks still pending before it sends the clear.
New case test_stateful_session_after_worker_replaced[first_connection_fails_close_wait_ends_delayed_heartbeats]: the same delayed-heartbeat setup as first_connection_fails_delayed_heartbeats (1.5 s heartbeat encode, 3 s failure encode), with _CLOSE_TIMEOUT at 0.5 s. The retry builds the toolset; without the cancel it is refused. The PR body now says the attempt waits up to 10 s, then cancels and clears, and the internals list names the SDK details this relies on.
| execution_timeout=timedelta(seconds=60), | ||
| ) | ||
| # Past the 2-second deadline, the attempt waits in close(). | ||
| await asyncio.sleep(5) |
There was a problem hiding this comment.
P3 (tests): this test reaches close() only because of the fixed 5 s sleep, and it asserts only that the shutdown returns. It can pass without exercising the interrupted wait, or fail when the session starts late.
Measured with a wrapper around _SessionHeartbeats.close, at load 10 to 18:
close()was entered about 2.05 s afterstart_workflow, so the margin is about 3 s.- With the sleep at 0, the shutdown landed before the session started,
close()never ran, and the test passed. - With the sleep at 1, the read-back consumed the shutdown's cancel.
close()then waited the full patched 60 s, and the test failed its 20 s bound. With the production 10 s, that shutdown takes 10 s.
Fix:
- Set an
asyncio.Eventfrom a monkeypatched wrapper around_SessionHeartbeats.close, and wait for it instead of sleeping. Nothing inclose()awaits before its wait, so the event means it is parked there. - After the shutdown, poll until the session activity shows attempt 2, and assert its heartbeat details are empty. That is what the probe saw every time.
- Run the worker in
async withortry/finally, so a failed step doesn't leak it.
There was a problem hiding this comment.
Thanks, reworked in 83745c9:
- A wrapper around
_SessionHeartbeats.closesets anasyncio.Event, and the test waits for it instead of sleeping. - The worker runs in
async with, and the test callsworker.shutdown()inside it. - After the shutdown, it polls until the session activity shows attempt 2 and asserts its heartbeat details are empty.
- With your setup no "may be open" heartbeat ever reached the server, so empty details would hold even without the clear. The codec now lets the first "may be open" heartbeat through and hangs the later ones, the read-back hangs on describe, and the heartbeat interval is 0.5 s. So the clear must replace a stored marker: with the clear removed from the
finally, the test fails on that assertion, and with 4e8708b'sclose()the shutdown times out.
| return description | ||
|
|
||
|
|
||
| class _StallMayBeOpenEncodeCodec(PayloadCodec): |
There was a problem hiding this comment.
P3 (tests): this codec leaves one heartbeat task pending forever in each test that uses it. The garbage collector later logs it as ERROR Task was destroyed but it is pending! inside an unrelated test's output.
Every run of the stateful file here had exactly two, one for each test that uses this codec ([heartbeat_encode_stalls] and the shutdown test). They showed up under tests such as test_stateful_session_after_workflow_reset and [unavailable_once].
Fix: record the stalled tasks (asyncio.current_task()) in the codec and cancel them once the worker has shut down. Don't release them instead: _heartbeat_async would then record a heartbeat on a finished activity and log an exception.
There was a problem hiding this comment.
Thanks. With the change from the line-664 thread, close() cancels the stalled heartbeat tasks before it sends the clear, so the codec no longer leaves a task pending. Two runs of the stateful file at 83745c9 logged no Task was destroyed but it is pending!; a control run at dbc434f logged two, as you saw.
- A cancellation already leaving the block (a workflow cancel or an asyncio.timeout) stays a cancellation when the session ended in the same workflow task; the README and cleanup() say the error then has no cause. - close() cancels heartbeats still being encoded before it sends the clear, so a late one cannot make the retry refuse. - The earlier-block refusal names same-name blocks open at the same time, and the README says not to open them. - The shutdown test waits for close() instead of sleeping, runs the worker in async with, and checks that the retry sees the clear over a stored marker. A new case covers a heartbeat that outlasts the close() wait.
|
Thanks for the fourth round. The changes are in 83745c9, and each thread has a reply. On the review summary:
|
What was changed
A retried stateful MCP session Activity no longer opens a new, empty MCP session in the middle of a run. If an earlier attempt opened a session, the retry fails with a non-retryable
ApplicationError(type="DedicatedWorkerFailure"), as theTemporalStatefulMcpToolSetProviderdocstring says. Retries in which no session was opened still build the toolset, except after a lost host or a timed-out attempt (below).-server-sessionActivity wrapscreate_session()on the toolset'sMCPSessionManager, which ADK'sMcpToolsetandMcpToolcall before every request. After ADK returns a session, and before ADK sends a request on it, the wrapper recordsmcp-session-openedin the Activity's heartbeat details withactivity.heartbeat(). A toolset with no session manager (such as a test fake) records it before its first list or call.DedicatedWorkerFailure,non_retryable=True, before it calls the factory.mcp-session-may-be-open, and every heartbeat carries it until a session opens. Before it calls the factory, the session Activity readsDescribeWorkflowExecutionuntil the server shows that heartbeat for this attempt. A retry that finds it is refused too. A describe the server refuses (PERMISSION_DENIED,UNAUTHENTICATED,NOT_FOUND,UNIMPLEMENTEDorINVALID_ARGUMENT), or details it cannot decode, fail the session Activity with a non-retryableDedicatedWorkerFailurethat says why, with permission advice only for the first two; the whole read-back, including stalled describes, is bounded by a 30-second deadline, after which the attempt fails and is retried.heartbeat_timeoutif that is shorter.get_toolsand stateful tool calls fail withDedicatedWorkerFailureonce the session Activity has ended, with the session's failure as the cause. The caller awaits the operation itself, as onmain, and a callback on the session cancels it when the session ends, so the caller fails at once. Withcancellation_type=WAIT_CANCELLATION_COMPLETEDthe operation is not cancelled but left to its own timeout, because no worker may be left to acknowledge the cancel, and an unacknowledged cancel keeps the Workflow from being evicted; for that type the caller waits for the operation or the session, whichever ends first. No operation is scheduled after the session ended. These failures no longer depend on an optionalschedule_to_start_timeout, which a caller-suppliedconfigmay leave out. When theasync withblock exits after the session ended on its own, for whatever reason, it raisesApplicationError(type="DedicatedWorkerFailure")with the session'sActivityErroras its cause, as the calls inside it do. If the session ended in the workflow task in which the block exits, the SDK drops its result when the block cancels it, so the error has no cause; and if a cancellation (a workflow cancel or anasyncio.timeout) is then leaving the block, the cancellation leaves it instead, as onmain. A session checks its run-scoped name before and right after the read-back, and holds it from registration untiltoolset.close()returns. Of two same-name sessions in one worker, the one that finishes its read-back second fails with 'Cannot connect to an already running toolset' and retries, as onmain. There is no version gate (see Replay below).async withblock of a run still schedules its operations onname@run_id, as onmain, the queue that sessions of every version poll. An operation left on that queue is refused by a later block's session with the same name: a session fails, with a non-retryableDedicatedWorkerFailure, any list or call that the server first scheduled before the session itself (activity.info().scheduled_time, which retries keep). The server sets that time, so the check does not depend on activity IDs thatconfigorserver_session_configset. Two blocks with the same name open at the same time are not supported: whichever session finishes its read-back first serves the name, so the other block's operations can fail withDedicatedWorkerFailure, or both blocks share one session. The refusal message and the README say so.reset_heartbeat=True, the describe permission, that a later block with the same name is not isolated from the earlier session until that session stops ([Bug] google_adk: a second stateful MCP block with the same name reaches the first block's MCP session #380), and that two blocks with the same name must not be open at the same time.The marker is stored after ADK opens a session, not before the first operation: a first connection that fails raises before ADK returns a session, so its retry keeps working. Recording it after the operation would let a host lost after a tool call's side effect be rebuilt.
Earlier versions of this PR sent the marker with awaited client heartbeats as well as the Worker's. With two writers, a Worker heartbeat sent before the session opened could reach the server after the marker and erase it. Without a heartbeat timeout, resets also stopped reaching the session. This version has one writer and keeps the Worker's heartbeats. Earlier versions also refused an earlier block's operations by comparing activity IDs, which callers can set, and then by giving each later block its own task queue (
name@run_id#N). A session recorded by an earlier build keeps pollingname@run_id, so after the Workflow worker was upgraded, that block's operations went to a queue nobody served. This version keeps the shared queue and compares the server's scheduled times instead.What callers see after a refused retry: the run's next tool call, or one already waiting, fails with
DedicatedWorkerFailurewithout waiting for a timeout. On the agent route, ADK catches that error while preparing the turn, logs it, and runs the turn without the toolset (google/adk-pythondoes this for any toolset that fails to load). The run then fails when theasync withblock exits, withApplicationError(type="DedicatedWorkerFailure")whose cause is the session Activity'sActivityError(or with no cause, when the session ended in the block's last workflow task and the SDK dropped its failure; a cancellation leaving the block in that workflow task stays a cancellation). If code in the block closes the toolset first, for example with ADK'srunner.close(), ADK closes it in its own task and only logs the error, and the block exits without it, as onmain.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, once a session was opened, that run gets
DedicatedWorkerFailureinstead. This also happens on a graceful deploy and after an Activity reset that keeps heartbeat details (reset_heartbeat=False). It also gets that error when its host is lost, or the attempt times out, before any session opened. Before upgrading, such a caller can move to the statelessTemporalMcpToolSetProviderandTemporalMcpToolSet, which the provider's docstring prefers when no persistent connection is needed, or catch the failure around theasync withblock and open a newTemporalStatefulMcpToolSetblock. Tools listed in one block now fail in a later block (onmainthe earlier block's session could still serve them): list the tools again inside each block. A session that ends on its own, for any reason, now leaves the block asApplicationError(type="DedicatedWorkerFailure")with theActivityErroras its cause, wheremainraised theActivityErroritself (when the session ended in the workflow task in which the block exits, after the block's last timer, the error has no cause, wheremainraised aCancelledError); code that catchesActivityErroraround the block should catchApplicationError(orFailureError). A block left before its first await, empty or raising, no longer fails withCancelledError.Temporary limitation: a retry after a lost host or a timed-out attempt is refused even when no session was opened, because the plugin cannot wait for a Worker heartbeat. This will be replaced once the Python SDK offers a heartbeat the plugin can wait for.
Also: a reset or unpause with
reset_heartbeat=Trueclears the marker, so the next attempt builds the toolset. The session Activity sends one more heartbeat at its start, and before calling the factory it callsDescribeWorkflowExecutiononce or a few times, so the Worker's client needs permission to describe the Workflow. The one-hour default start-to-close of the session Activity is now the longest a block can stay open. No public name, option or default changes.Replay and upgrades: Workflow code changes, without a version gate:
WAIT_CANCELLATION_COMPLETED. That includes an activation that resolves a stateful operation together with another activity or with a Workflow cancel:tests/histories/stateful_mcp_gather.jsonandstateful_mcp_cancel.json, recorded onmain, replay on this change.WAIT_CANCELLATION_COMPLETED, the caller waits for the operation or the session, so a stateful operation and another activity resolved in one activation, the stateful one first, resume in a different order than onmain. If the two branches next schedule different activity types, replay fails with[TMPRL1100]; if they schedule the same type, as the model calls of an ADKParallelAgentdo, the run replays without an error and each branch gets the other's result. The README says to let such runs finish before deploying.WAIT_CANCELLATION_COMPLETED, an operation that completes in the same workflow task as a workflow cancel or anasyncio.timeout: a history recorded onmainreplays on this change (tests/histories/stateful_mcp_cancel_wait.json), but one recorded on this change does not replay onmain, because this change re-raises the cancellation without the SDK recording its flag (a nondeterminism error for the cancel, an ActivityMachine error or[TMPRL1100]depending on what follows the call; for a timer, the second review found thatmainreplays it without an error and returns the tool result where the run recordedTIMEOUT).TRY_CANCELorABANDON, does not replay across builds, in either direction: this change sends a cancel or fails without scheduling wheremainkeeps waiting. It fails with[TMPRL1100], or with an ActivityMachine error for some histories recorded before this change. WithWAIT_CANCELLATION_COMPLETED, a history recorded onmainin which the operation was waiting when the session ended replays on this change, but one recorded on this change fails onmainwith[TMPRL1100].main.DedicatedWorkerFailureor a timeout, except a run that recovered as the README suggests (it caught the block'sDedicatedWorkerFailureand opened a new block): recorded on this change, it fails onmainwith[TMPRL1100], becausemain's block raises theActivityErrorthatexcept ApplicationErrormisses. A Worker deploy that replays one of these runs mid-run will fail its Workflow task until it runs on the build that recorded it.main, so a healthy session recorded on either build keeps serving its block's operations after the Workflow worker is replaced, in either direction. A session onmaindoes not check scheduled times, so until session hosts are upgraded an earlier block's leftover operation can still run there, as onmain.Why?
See #310. 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 tool calls succeeded against it with no error.
Checklist
Closes [Bug] google_adk: a retried stateful MCP session Activity silently opens a new, empty MCP session #310
How was this tested:
Supplemental local runs in Docker, with
temporalio1.34.0,google-adk2.12.0 andmcp1.30.0 from the plugin's lock and Temporal CLI 1.9.1:83745c9): the stateful file (46 tests) passed twice, andmake lintandmake buildpass.make test PYTEST_ARGS='-n 4'gave 222 passed, 5 skipped and one timeout outside this change (test_cold_agent_execution_and_replay, at load average 17), andtests/test_optional_mcp.pypassed when rerun alone. Each new check fails on its mutant: withcancellingalwaysFalse(dbc434f's behaviour),test_stateful_session_ends_with_the_blocks_last_task[cancel_first]ends withDedicatedWorkerFailureinstead of a cancellation; without cancelling pending heartbeats,test_stateful_session_after_worker_replaced[first_connection_fails_close_wait_ends_delayed_heartbeats]is refused; without the clear in thefinally,test_stateful_session_worker_shutdown_while_closingfindsmcp-session-may-be-openon attempt 2; and with4e8708b'sclose()that test times out. A control run of the stateful file atdbc434flogged twoTask was destroyed but it is pending!errors from the stalling codec; the two runs at this head logged none.3059bfa, on top ofde1a1c1;mainmerged in as4ad72ae, nopython/google_adkchange):make lint,make test PYTEST_ARGS='-n 4'(205 passed, 5 skipped) andmake buildpass;scripts/ci/check_conventions.pywas not run locally (no network in the container). The 28 stateful tests pass, including the new heartbeat-timeout, describe-permission and slow-heartbeat host-kill cases and the replay oftests/histories/stateful_mcp_*.json.test_stateful_session_after_workflow_resetfailed 3 times in about 60 runs, each time while the laptop running the container was asleep; it passed every other run.dbc434f:close()sends the clear in afinally, so a worker shutdown that interrupts its bounded wait no longer leaves a hung heartbeat encode as the attempt's last heartbeat task.test_stateful_session_worker_shutdown_while_closingshuts the worker down while every "may be open" encode hangs; with4e8708b'sclose()the shutdown never finishes. The 43 stateful tests andmake lintpass.4e8708b): the stateful file (42 tests),make lintandmake buildpass. Each new check fails on its mutant: withbc76fd3'scleanup()branch,test_stateful_session_ends_with_the_blocks_last_timerfails withDID NOT RAISE(the block exited cleanly); with the cancel count tested for truth,test_stateful_block_exit_error[compensation_raise_first]ends cancelled instead of with the body's error; without the second duplicate check,test_stateful_sessions_with_one_name_in_one_workerfails; with the permission advice for every refusal,[not_found]fails; and withclose()skipping the clear, or waiting without a limit,[heartbeat_encode_stalls]hangs.make test PYTEST_ARGS='-n 4'on a heavily loaded machine (load average 16) failed 4 tests, 3 of them outside this change (test_cold_agent_execution_and_replay, the replay-metrics test) and one host-kill timing case; CI passes on4e8708b(all fourgoogle_adkjobs, the conventions job andci-status).bc76fd3):make lint,make test PYTEST_ARGS='-n 4'(215 passed, 5 skipped) andmake buildpass, and the 38 stateful tests pass. Each new check fails on the mutant it pins: without the name reservation,test_stateful_sessions_with_one_name_in_one_workerfails withKeyError: 'stateful_server-stateful@<run_id>'; without theoperation.done()raise,tests/histories/stateful_mcp_cancel_wait.json(recorded onmain) fails replay; without the attempt check,[other_attempt_once]fails; when every describeRPCErrorcounts as a refusal,[unavailable_once]fails; with the earlier block-exit rule,test_stateful_block_exit_error[factory_fails]fails; and without theCancelledErrorhandling,[tool_from_earlier_block]fails withCancelledError('Cancelled'). The analysis's replay check gives 7 of 8 histories on both builds, the expected break as before; gather and cancel histories recorded onmainreplay onbc76fd3, and theWAIT_CANCELLATION_COMPLETEDcancel history recorded onbc76fd3fails onmainwith an ActivityMachine error, as listed under Replay.3b17169ande9b0dbc: an operation the session's end cancelled keeps the session's failure as its cause in every cancellation mode (raise ... from errhad replaced it with the operation's own cancellation), and the whole read-back runs under one deadline, with each describe getting the time left as itsrpc_timeout(in3059bfaa stalled describe or decode could outlast the deadline). On3059bfa's_mcp.py, the newoperation_waiting,operation_waiting_abandon,describe_stallsanddecode_stallscases fail; withe9b0dbcthe 32 stateful tests,make lint,make test PYTEST_ARGS='-n 4'(209 passed, 5 skipped) andmake buildpass.mainat88745dcwith the Workflow worker stopped (a gathered stateful call and plain activity resolved in one activation; a stateful call completed in the same activation as a Workflow cancel), and the same on this change: all four replay onmainand on this change. Onde1a1c1, the gather histories fail with[TMPRL1100] Activity type of scheduled event 'follow_up_a' does not match ...and the cancel histories with an ActivityMachine error.mainand onde1a1c1's_mcp.py: 7 of 8 histories replay on both builds; the run carried from the change to the change, whose retried session was refused, fails onmainwith[TMPRL1100] Nondeterminism error: No command scheduled for event.test_stateful_session_after_host_killed[heartbeat_timeout_slow_heartbeats]fails (the retried session is not refused); without the earlysession.done()raise,test_stateful_operations_fail_after_session_refused[operation_after_refusal_wait_cancellation]fails withassert 2 == 1; withde1a1c1's_mcp.py, 9 of the 12 new or changed cases fail, including the heartbeat-timeout, describe-permission and block-exit checks.c68bb8a):make sync,make format,make lint,make test PYTEST_ARGS='-n 4'(199 passed, 5 skipped),make buildandscripts/ci/check_conventions.pypass.main, session host onmain, replaced with this change: succeeds.main, replaced withc68bb8a(per-block queues): fails withDedicatedWorkerFailureafter the schedule-to-start timeout.mainthroughout, this change throughout, and recorded on this change then replaced withmain(session host on this change): all succeed.test_stateful_operation_of_ended_session_not_run_by_next_block: the session's host shuts down gracefully after a session opened, aput('OLD-PAYLOAD')waits on the queue, the retried session is refused, and the Workflow catches the failure and opens a second block with the same name, whosegetmust returnEMPTY. It also checks that every list and call of both blocks is scheduled onname@run_id.WAIT_CANCELLATION_COMPLETEDandTRY_CANCELwith default activity IDs, andWAIT_CANCELLATION_COMPLETEDwith session activity IDs set tosession-a/session-band to1000/1001.c68bb8a's_mcp.py, all four fail the queue check (the second block usesname@run_id#2).bb9b322's_mcp.py(earlier round), thesession-a/session-bcase failed (getreturnedOLD-PAYLOAD) and the1000/1001case failed (the first block'sget_tools, activity ID2, was refused).activity.info().scheduled_timewas the same on all three attempts; onlycurrent_attempt_scheduled_timechanged.WAIT_CANCELLATION_COMPLETEDandTRY_CANCEL, default IDs): histories recorded onbb9b322andc68bb8areplayed on both builds. That Workflow code has changed since; see the later replay results above.test_stateful_session_after_host_killed[heartbeat_timeout_call_waiting]: acall-toolwithWAIT_CANCELLATION_COMPLETEDand a 2-minute start-to-close timeout is running a tool that never returns when the session host is killed. The retried session is refused, and the run must fail within 10 seconds.ee42451's_mcp.py(earlier round), the run never failed (pytest timeout after 120 s): the cancelled call waited for an acknowledgment, and the Worker loggedEviction processed, but 2 tasks remain.WAIT_CANCELLATION_COMPLETEDcancel that is never acknowledged blocks eviction, while an operation left uncancelled does not.call-tool(scratch test, default cancellation type, earlier round): the run endsWORKFLOW_EXECUTION_CANCELEDwith the same history events onee42451and on that round's change.test_stateful_operations_fail_after_session_refused(start-to-close-onlyconfig, the session on its own host queue that shuts down gracefully after a session opened):list-toolswaiting, the refused retry cancels it and the run fails with the refusal.get_toolscalled after the refusal, nothing is scheduled and the run fails at once.8b32464's_mcp.py, both timed out (earlier round).test_stateful_session_after_worker_replaced[first_connection_fails_delayed_heartbeats]:McpToolsetwhose first connection fails, "may be open" heartbeats that take 1.5 s to encode, and failure attributes encoded through a 3 s codec. The Worker shuts down gracefully while a heartbeat is being encoded.8b32464's_mcp.pyit is refused too.test_stateful_session_after_host_killed[no_heartbeat_timeout]kills the session host, with no heartbeat timeout, after a session opened behind a throttled heartbeat. On3b9ea40the retried attempt built a new toolset; on8b32464and with this change it is refused without a factory call.mainat88745dcwith the marker constants added, the first review found that 16 ofde1a1c1's 22 stateful tests fail, mostly withTimeoutErrorwhile waiting for the refusal; the 6 that pass are the earlier tests and checks of behaviour that must not change. (An earlier bullet here described679d134's tests.)8b32464) fails as reported on 0.0.1 (google-adk2.13.0) and onmain. On8b32464its control reads its value, and the retried run fails withDedicatedWorkerFailurebecause the server heldmcp-session-may-be-open;getnever reached the MCP server.ee42451(earlier round): the host-kill and refused-operation histories (default cancellation type) recorded on either build replay on both. A history in which aWAIT_CANCELLATION_COMPLETEDcall was running when the session ended, recorded on that round's change, fails onee42451with[TMPRL1100], as described under Replay above.8b32464(earlier round): completed and waiting runs recorded on8b32464and on that round's change replay on both builds. Refused runs in which a later or waitinglist-toolsmet the ended session fail across builds, as described under Replay above, and replay on the build that recorded them. Live carries through a Worker replacement were not rerun for this change.Any docs updates needed?
The google_adk README now covers the stateful toolsets' retry behaviour, how operations fail after the session ends (including
WAIT_CANCELLATION_COMPLETED, and that a later block with the same name refuses such an operation whatever activity IDs are set), the error a block raises on exit, the heartbeat limitation, the one-hour cap, resets withreset_heartbeat=True, and the same-name caveat. Release notes are generated from commit subjects, and the title names only the refused retry, so the release draft should also name the other caller changes above (the error type that leaves the block, the new describe permission, and tools from an earlier block failing) and the replay changes.Not covered:
google-adk2.13.0 with this version, and the streamable HTTP and SSE transports in the tests (they use stdio).WAIT_CANCELLATION_COMPLETEDoperation runs on a lost host still waits for that operation's timeout, as onmain.WAIT_CANCELLATION_COMPLETEDoperation left on the queue after its session ended stays pending until its own timeout, or until a later block's session refuses it. Without a schedule-to-start or schedule-to-close timeout and without a later block, it stays pending until the run ends. A stale operation retried after its start-to-close timeout was not run against a later block; it is covered by the retry check ofscheduled_timeabove.McpToolset._mcp_session_managerandMCPSessionManager.create_session(). These are private to ADK but the same fromgoogle-adk2.4.0 to 2.13.0. If ADK renames either, the toolset falls back to recording the marker before its first operation, which also refuses a retry after a first connection that failed.activity.heartbeat()call, astemporalio1.34.0 does. Ending the attempt with the clear relies on three more SDK details intemporalio/worker/_activity.py: the completion waits only for the last heartbeat task ('Do final completion'), a heartbeat with no details skips the codec, and_heartbeat_asynccatches onlyException, so cancelling a heartbeat still being encoded does not report an error.async withblock with the same name can reach the earlier block's MCP session until that session notices its cancellation, up to one heartbeat interval; documented here, fix tracked in [Bug] google_adk: a second stateful MCP block with the same name reaches the first block's MCP session #380.main, not changed here:cleanup()treats a cancelledActivityErrorfrom the session as a clean exit even when its own task was cancelled while it waited, so a TaskGroup sibling failure during that wait lets the branch run its code after the block. A fix changes Workflow commands compared tomain, so it is left for a follow-up: [Bug] google_adk: a stateful MCP block can lose a cancellation while it exits #394.Open questions: none.