Repository navigation
Description
Package: temporalio-openai-agents main (be1e411), openai-agents 0.22.0.
What happens
activity_as_tool() takes cancellation_type, but ActivityCancellationType.WAIT_CANCELLATION_COMPLETED has no effect. If the Workflow is cancelled while the tool's Activity runs, the run ends CANCELED as soon as the cancel is requested. The Activity gets the cancel and cleans up after the Workflow has closed, and the history has no ACTIVITY_TASK_CANCELED. The same Activity called with workflow.execute_activity(...) and the same options ends the Workflow only after its cleanup.
Reproduction
One file, no network or API key. It cancels the same Activity twice: once called with workflow.execute_activity, once as an agent tool with activity_as_tool. On cancel, the Activity takes 1 s to clean up.
"""activity_as_tool ignores cancellation_type=WAIT_CANCELLATION_COMPLETED.
python repro.py (starts a local Temporal dev server; no API key needed)
The same Activity, with the same options, is cancelled twice: once called with
workflow.execute_activity, once as an agent tool with activity_as_tool. On cancel
the Activity takes 1 s to clean up. With WAIT_CANCELLATION_COMPLETED the Workflow
should end only after that cleanup.
"""
import asyncio
import importlib.metadata
import os
import sys
import time
import uuid
from datetime import timedelta
from temporalio import activity, workflow
from temporalio.api.enums.v1 import EventType
from temporalio.client import Client, WorkflowFailureError
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
from temporalio.workflow import ActivityCancellationType
with workflow.unsafe.imports_passed_through():
from agents import Agent, Model, Runner
from temporalio.openai_agents import OpenAIAgentsPlugin
from temporalio.openai_agents.testing import ResponseBuilders, TestModelProvider
from temporalio.openai_agents.workflow import activity_as_tool
STARTED: set[str] = set()
CLEANED_UP: dict[str, float] = {}
@activity.defn
async def slow(city: str) -> str:
"""Look up the weather slowly."""
STARTED.add(activity.info().workflow_id)
try:
while True:
activity.heartbeat()
await asyncio.sleep(0.2)
except asyncio.CancelledError:
await asyncio.sleep(1) # cleanup, shorter than the heartbeat timeout
CLEANED_UP[activity.info().workflow_id] = time.monotonic()
raise
OPTIONS = dict(
start_to_close_timeout=timedelta(seconds=60),
heartbeat_timeout=timedelta(seconds=2),
cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,
)
@workflow.defn
class PlainWorkflow:
@workflow.run
async def run(self) -> str:
return await workflow.execute_activity(slow, "Tokyo", **OPTIONS)
@workflow.defn
class AgentWorkflow:
@workflow.run
async def run(self) -> str:
tool = activity_as_tool(slow, **OPTIONS)
result = await Runner.run(Agent(name="helper", tools=[tool]), "Go.")
return result.final_output
class CallTheTool(Model):
async def get_response(self, *args, **kwargs):
return ResponseBuilders.tool_call('{"city": "Tokyo"}', "slow")
def stream_response(self, *args, **kwargs):
raise NotImplementedError
async def cancel_during_activity(client: Client, run, label: str) -> None:
workflow_id = f"{label}-{uuid.uuid4()}"
handle = await client.start_workflow(run, id=workflow_id, task_queue=label)
while workflow_id not in STARTED:
await asyncio.sleep(0.05)
await handle.cancel()
try:
await handle.result()
except WorkflowFailureError:
pass
closed = time.monotonic()
await asyncio.sleep(3) # let the Activity finish its cleanup
events = [
EventType.Name(e.event_type).removeprefix("EVENT_TYPE_")
async for e in handle.fetch_history_events()
]
cancel_events = [e for e in events if "CANCEL" in e]
cleanup = CLEANED_UP.get(workflow_id)
when = "never" if cleanup is None else ("before" if cleanup <= closed else "after")
print(f"{label:16} {' -> '.join(cancel_events)}")
print(f"{'':16} Activity cleanup finished {when} the Workflow closed")
async def main() -> None:
v = importlib.metadata.version
print(f"temporalio {v('temporalio')}, openai-agents {v('openai-agents')}")
async with await WorkflowEnvironment.start_local() as env:
plain = env.client
agents = Client(**{**env.client.config(), "plugins": [
OpenAIAgentsPlugin(model_provider=TestModelProvider(CallTheTool()))]})
async with Worker(plain, task_queue="execute_activity", workflows=[PlainWorkflow], activities=[slow]):
await cancel_during_activity(plain, PlainWorkflow.run, "execute_activity")
worker = Worker(agents, task_queue="activity_as_tool", workflows=[AgentWorkflow], activities=[slow])
asyncio.create_task(worker.run())
await cancel_during_activity(agents, AgentWorkflow.run, "activity_as_tool")
# Skip this Worker's shutdown: on temporalio 1.34.0 it never finishes
# (temporalio/sdk-python#1938).
sys.stdout.flush()
os._exit(0)
if __name__ == "__main__":
asyncio.run(main())Output on temporalio 1.35.0 (Python 3.13.16; the dev server's banner is left out):
temporalio 1.35.0, openai-agents 0.22.0
execute_activity WORKFLOW_EXECUTION_CANCEL_REQUESTED -> ACTIVITY_TASK_CANCEL_REQUESTED -> ACTIVITY_TASK_CANCELED -> WORKFLOW_EXECUTION_CANCELED
Activity cleanup finished before the Workflow closed
activity_as_tool WORKFLOW_EXECUTION_CANCEL_REQUESTED -> ACTIVITY_TASK_CANCEL_REQUESTED -> WORKFLOW_EXECUTION_CANCELED
Activity cleanup finished after the Workflow closed
On temporalio 1.34.0 the output is the same:
temporalio 1.34.0, openai-agents 0.22.0
execute_activity WORKFLOW_EXECUTION_CANCEL_REQUESTED -> ACTIVITY_TASK_CANCEL_REQUESTED -> ACTIVITY_TASK_CANCELED -> WORKFLOW_EXECUTION_CANCELED
Activity cleanup finished before the Workflow closed
activity_as_tool WORKFLOW_EXECUTION_CANCEL_REQUESTED -> ACTIVITY_TASK_CANCEL_REQUESTED -> WORKFLOW_EXECUTION_CANCELED
Activity cleanup finished after the Workflow closed
On 1.34.0 the Worker also logs RuntimeError: Eviction processed, but 3 tasks remain after the agent run and its shutdown never finishes. That is temporalio/sdk-python#1938, fixed in temporalio 1.35.0.
Cause
From reading the source and tracing a run, not from a patch: the Agents SDK runs each tool call in its own task. When the run is cancelled, the parent-cancellation branch of _FunctionToolBatchExecutor.execute() in agents/run_internal/tool_execution.py calls _cancel_pending_tasks_for_parent_cancellation(). That cancels the tool tasks and adds done callbacks without awaiting them, and execute() then re-raises CancelledError at once (0.22.0, lines 1626-1635 and lines 1777-1783). So Runner.run returns while the Activity handle is still waiting for the cancel to complete, and the Workflow closes. Upstream this is on purpose: test_parent_cancellation_does_not_wait_for_tool_cleanup pins it, and 0.24.0 behaves the same.
Impact
A tool Activity that uses WAIT_CANCELLATION_COMPLETED so that its cleanup finishes before the Workflow ends doesn't get that. The Workflow, and anything that waits on it such as a parent Workflow, sees CANCELED while the cleanup is still running.
Fix options
- Work around it in the plugin: for example, track the tasks that
activity_as_tooltools start, and whenRunner.runis cancelled, wait for them before re-raising. - Document the limit: say in the README and in the
activity_as_tooldocstring thatWAIT_CANCELLATION_COMPLETEDdoesn't hold for tool Activities. - Upstream, the Agents SDK could offer an option to await cancelled tool tasks before re-raising, as
asyncio.gatherdoes.
Activity
sangkyoonnam commentedon Nov 5, 2026
@campoy, I prototyped the Activity follow-up on top of #226. Tracking
activity_as_toolcalls in the same run-scoped set makes the direct-call/tool comparison pass withWAIT_CANCELLATION_COMPLETED, whileTRY_CANCELstill closes before cleanup. All four cases passed in three runs with temporalio 1.35.0 and openai-agents 0.22.0. I have not tested replay compatibility yet.I'd like to take this after #226, with
run_streamedleft for a separate change. Does that fit your plan?