Repository navigation
Description
Required Information
Describe the Bug:
During parallel toolset discovery, child-originated cancellation ends the public Runner.run_async iterator while another listing started by that invocation is still running. The sibling can complete work after the invocation has ended. This happens before calling the model, rather than during function-call execution.
Steps to Reproduce:
- Use a source checkout at
03725e8c67ca27b2c07569797a0c18e867e0b217with its Python dependencies installed. - Save the code below as
toolset_cancel_repro.pyat the checkout root. Runpython -B toolset_cancel_repro.py. - One public BaseToolset waits on an Event. Another waits until that listing starts, then raises
asyncio.CancelledError. The caller does not cancel Runner. - The first listing's finalizer is incomplete when Runner returns. Release its gate after Runner returns; it completes then. The probe joins it before teardown.
Expected Behavior:
Discovery should settle its owned sibling listing tasks before the invocation iterator ends, including cancelling and awaiting them on abort.
Observed Behavior:
The child-cancel case ends the iterator with zero events and zero model calls, leaving the sibling pending. The probe's outcome=success means Python iterator exhaustion, not a successful ADK answer.
Environment Details:
- Source version 2.15.1, commit
03725e8c67ca27b2c07569797a0c18e867e0b217. - Windows 11 build 26300, CPython 3.12.13.
- Real Runner, LlmAgent, BaseToolset subclasses and InMemorySessionService.
Model Information:
No LiteLLM. A scripted BaseLlm supplies a fixed answer for the success control. No model API/network calls; the child-cancel case never reaches the model.
Optional Information
Frequency / Controls:
Ran the nine-case experiment twice: 6/6 child-cancel cases retain a listing at iterator return; all 12 whole-consumer-cancel / normal-success controls pass.
child_cancel: iterator exhausted, cleaned_when_runner_returned=false, continued_after_abort=true, model_calls=0, events=[]
parent_cancel: CancelledError, cleaned_when_runner_returned=true, continued_after_abort=false
success: iterator exhausted, cleaned_when_runner_returned=true, model_calls=1
Source / Related Reports:
flows/llm_flows/tools/_agent_tools.py::process_agent_tools resolves tool unions with plain asyncio.gather. Its comment says failures cancel siblings, but child cancellation does not do that. The Runner experiment demonstrates the lifetime gap.
- Parallel tool child cancellation leaves sibling tasks running past invocation completion #7172 / fix(tools): cancel sibling tools on child-originated cancellation #7180 concern parallel function-call execution. Current
_batch_executor._gather_or_cancelalready cleans up cancellation; discovery does not use it. - fix: keep the results of finished parallel tool calls on abort #7992 concerns completed function-call results on abort. SkillToolset: a cancelled registry fetch leaves a stale Future in the per-invocation cache, so resuming that invocation hangs or silently does nothing #8221 / fix(skills): keep a cancelled registry fetch from hanging resumed runs #8222 concern SkillToolset's cached Future; this probe uses no SkillToolset.
- bug: Runner.run_async tool_context may not be fully cleaned up on task cancellation #6271 concerns caller cancellation, which passes here. Bug Report: MCP Module Raises CancelledError and Prevents Custom Error Handling #3708 concerns transport cancellation/error handling, rather than sibling discovery settlement.
- perf(flows): Resolve agent tool unions in parallel #5875 introduced parallel discovery. Related open/closed issue and PR searches found no discovery-specific equivalent; please link one if this belongs there.
Limits:
This shows task/finalizer lifetime using Event-backed public toolsets. It does not demonstrate a permanent resource leak, a real MCP server failure or an external side effect. No production fix, full-suite result or Linux reproduction is claimed. Whether discovery should isolate a self-cancelled toolset or abort is a separate policy choice; either way owned sibling work needs a settled lifetime.
AI assistance: OpenAI Codex inspected source, wrote and ran the offline reproducer, and checked related reports.
Minimal Reproduction Code:
import asyncio
import json
import platform
import sys
from pathlib import Path
sys.path.insert(0, str(Path.cwd() / 'src'))
from google.adk.agents import LlmAgent
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_response import LlmResponse
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.tools.base_toolset import BaseToolset
from google.genai import types
class OfflineModel(BaseLlm):
model: str = 'offline'
calls: int = 0
async def generate_content_async(self, llm_request, stream=False):
self.calls += 1
yield LlmResponse(content=types.Content(role='model', parts=[types.Part(text='done')]))
async def experiment(mode):
started = asyncio.Event()
release = asyncio.Event()
cleaned = asyncio.Event()
completed = asyncio.Event()
class WaitingTools(BaseToolset):
async def get_tools(self, readonly_context=None):
started.set()
try:
await release.wait()
completed.set()
return []
finally:
cleaned.set()
async def close(self):
pass
class OtherTools(BaseToolset):
async def get_tools(self, readonly_context=None):
await started.wait()
if mode == 'child_cancel':
raise asyncio.CancelledError('listing cancelled by its own operation')
return []
async def close(self):
pass
sessions = InMemorySessionService()
model = OfflineModel()
runner = Runner(app_name='probe', agent=LlmAgent(name='agent', model=model, tools=[WaitingTools(), OtherTools()]), session_service=sessions)
session = await sessions.create_session(app_name='probe', user_id='u')
events = []
async def consume():
async for event in runner.run_async(user_id='u', session_id=session.id, new_message=types.Content(role='user', parts=[types.Part(text='go')])):
events.append(dict(author=event.author, error_code=event.error_code, error_message=event.error_message))
task = asyncio.create_task(consume())
await asyncio.wait_for(started.wait(), 60)
if mode == 'parent_cancel':
task.cancel()
elif mode == 'success':
release.set()
outcome = 'success'
try:
await asyncio.wait_for(task, 3)
except asyncio.CancelledError:
outcome = 'cancelled'
before = cleaned.is_set()
# Deliberately release and join the probe's outstanding work before teardown.
release.set()
await asyncio.wait_for(cleaned.wait(), 3)
result = dict(mode=mode, outcome=outcome, cleaned_when_runner_returned=before, continued_after_abort=mode != 'success' and completed.is_set(), model_calls=model.calls, events=events)
print(json.dumps(result), flush=True)
return result
async def main():
print(json.dumps(dict(python=platform.python_version(), platform=platform.platform())), flush=True)
results = []
for _ in range(3):
for mode in ('child_cancel', 'parent_cancel', 'success'):
results.append(await experiment(mode))
assert all(not r['cleaned_when_runner_returned'] and r['continued_after_abort'] for r in results if r['mode'] == 'child_cancel')
assert all(r['cleaned_when_runner_returned'] and not r['continued_after_abort'] for r in results if r['mode'] != 'child_cancel')
from pathlib import Path
Path(__file__).with_name('results.json').write_text(json.dumps(results, indent=2), encoding='utf-8')
print('3/3 child-origin cancellation leaves sibling listing active; 6/6 controls pass', flush=True)
asyncio.run(main())
Activity
chelsealong commentedon Nov 27, 2026
May I work on this issue (#8384: Toolset discovery can outlive Runner.runasync after a sibling listing cancels itself) and, if I can reproduce it, submit a focused fix with regression coverage? Please let me know if someone is already handling it or if you would prefer a different approach. I would use Codex assistance and disclose that in any PR.
surajksharma07 commentedon Nov 27, 2026
@OUAO-FRANK Reproduced on main at 03725e8: plain exceptions get caught per toolset, but CancelledError gets past that, and the plain asyncio.gather in _agent_tools.process_agent_tools never cancels the other listings.
A workaround that worked for me: wrap each _convert_tool_union_to_tools(...) call in asyncio.create_task and await _batch_executor._gather_or_cancel(tasks) in its place, the same helper the function-call path uses. Locally the slow sibling then finishes before run_async returns, and the normal run still works. Could you check whether that holds up on your side? Also, have you seen this with a real toolset like MCP, or only with the probe?
@chelsealong feel free to pick this up. Please test it thoroughly first and add a regression test before you raise the PR. run_async still ending with zero events on a self-cancel is probably a separate discussion.