SkillToolset: a cancelled registry fetch leaves a stale Future in the per-invocation cache, so resuming that invocation hangs or silently does nothing

未關閉
#8,221 1 則留言 0 個 reaction 已指派 1 人 在 GitHub 檢視

維護者通常 3 天內回覆

@sanketpatil06 已經在處理了。

開始於 2026年11月18日。

  • #8222 來自 @sablea —— 未關閉

評估

這個 Issue 還沒有評估資料。

描述

tools

🔴 Required Information

Describe the Bug:

SkillToolset._get_or_fetch_skill puts a placeholder asyncio.Future into
_fetched_skill_cache[invocation_id][skill_name] before it awaits
registry.get_skill(...). The cleanup is in an except Exception block
(src/google/adk/tools/skill_toolset.py, around L2495-2501 on main @ c74df83c):

fut = loop.create_future()
turn_cache[skill_name] = fut
try:
  skill = await self._registry.get_skill(name=skill_name)
  fut.set_result(skill)
  turn_cache[skill_name] = skill
  return skill
except Exception as e:          # <- asyncio.CancelledError is a BaseException
  fut.set_exception(e)
  fut.exception()
  turn_cache.pop(skill_name, None)
  raise

If the fetch is cancelled, the Future is never resolved and is never removed
from the cache. asyncio.CancelledError subclasses BaseException, so
except Exception does not catch it. Any later lookup of the same skill in the
same invocation reaches await cached on that Future.

The cache is keyed by invocation_id, and resuming an invocation reuses its id.
A resumable app that uses a SkillRegistry is therefore affected like this:

  1. A turn is cancelled while a registry fetch is in flight. The usual cause is
    a client disconnect: api_server's _monitor_client_disconnect cancels the
    run task.
  2. The client resumes that invocation (run_async(invocation_id=...) or
    /run with invocationId), as ResumabilityConfig documents.
  3. The first resume hangs on the pending Future, and the registry is never
    called again. If that hung request is then cancelled, for example by a client
    timeout, the Future becomes cancelled. Later resumes then return at once
    with no events and no error, so the user's message is never answered.

The stale entry stays until 16 other invocations push it out
(_max_cache_turns). A fresh process, or a fresh SkillToolset, resumes the
same invocation without trouble.

The ResumabilityConfig docstring says "any temporary / in-memory state will
be lost upon resumption". This cache lives on the toolset instance and survives
for the life of the process.

Steps to Reproduce:

  1. pip install google-adk==2.14.0. No API key is needed; the repro uses a
    fake model and a fake registry.
  2. Save the Minimal Reproduction Code below as repro.py and run
    python repro.py.
  3. It prints resume hung for 10s; registry calls=2; cache entry=<Future ...>.

Expected Behavior:

Resuming the invocation refetches the skill (the registry is healthy again by
then) and the turn completes. A cancelled fetch should leave no state behind
that a later caller would wait on.

Observed Behavior:

The first resume never completes, and the registry is not called again. After
that request is cancelled, later resumes yield nothing and the turn is
silently lost.

I checked three ways the fetch can get cancelled. All use a resumable app with
a registry-backed SkillToolset:

Trigger How the fetch is cancelled In-process (Runner) Real HTTP (adk api_server, SQLite sessions, client drops /run_sse, resume via /run)
Disconnect during get_tools re-fetch (the repro below) A skill activated in an earlier turn is re-fetched by get_tools before the model call, and the client disconnects. Model behaviour does not matter resume hangs resume hangs
Disconnect during load_skill The client disconnects while load_skill awaits the registry. On resume the model re-calls load_skill after the "Invocation was aborted by client." result, as a real model normally would resume hangs resume hangs
Sibling tool fails in a parallel batch Another tool in the same batch raises, so _gather_or_cancel cancels load_skill stale Future left in the cache, but no hang: the error event is terminal, so resume re-runs nothing not tested

The same happens over HTTP. I ran a real adk api_server with SQLite
sessions (on main @ 95d8610e / 2.13.0; the code is unchanged since), dropped
the /run_sse connection mid-fetch, then resumed via /run
with invocationId. The client gives up after 10 s on each request:

resume #1 on SAME process : HUNG, client gave up after 10.0s
resume #2 on SAME process : HTTP 200 after 0.02s, 0 events: []
resume #3 on SAME process : HTTP 200 after 0.00s, 0 events: []
control resume on FRESH process: HTTP 200 after 0.48s, 2 events (model says "done")

Server log during the dropped turn:

[registry] get_skill call #2
Client disconnected. Aborting agent run for session ...
[registry] call #2 CANCELLED

The server logs no error for resumes #2 and #3. Once the hung request is
cancelled, the cached Future is cancelled too. The next await cached raises
CancelledError, the runner logs it as
Root node root was cancelled by an external cancellation., and the turn ends
with nothing.

The bug is not Windows-specific. The same in-process repro on Linux
(Ubuntu, kernel 6.8, Python 3.11.15, main @ c74df83c) gives the same
output:

before the fix: resume hung for 10s; registry calls=2; cache entry=<Future cancelled>
after the fix:  resumed OK

Controls:

  • Resuming the same invocation on a fresh process with the same SQLite session
    DB completes. The session holds the same INVOCATION_ABORTED events either
    way, so those events are not what stops the resume.
  • Changing only that except clause to except BaseException in memory
    removes the hang.
  • In-process, after resume #2 returned nothing, deleting only
    _fetched_skill_cache[invocation_id]["remote-skill"] let resume #3 complete
    (the registry was called again and the model said "done").

Environment Details:

  • ADK Library Version: 2.14.0 (also main @ df9f9d04 and main @ c74df83c). The code was
    introduced with the skill registry in 380d261e5, so v1.34.0 through v2.14.0
    are affected.
  • Desktop OS: Windows 11
  • Also reproduced on: Linux (Ubuntu, kernel 6.8, Python 3.11.15), main @ c74df83c
  • Python Version: 3.11.18 (Windows), 3.11.15 (Linux)

Model Information:

  • Are you using LiteLLM: No
  • Which model is being used: N/A. The repro uses a scripted BaseLlm, and
    the hang happens in get_tools before any model call.

🟡 Optional Information

Regression:

No. The behaviour has existed since the per-invocation fetch cache was added in
v1.34.0. Still present on main @ c74df83c.

Additional Context:

The fix is small: give CancelledError its own cleanup branch that cancels the
Future and drops the cache entry. I have a PR with regression tests ready and
will link it here.

Minimal Reproduction Code:

import asyncio

from google.adk.agents.llm_agent import LlmAgent
from google.adk.apps.app import App, ResumabilityConfig
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.in_memory_session_service import InMemorySessionService
from google.adk.skills import models
from google.adk.skills.skill_registry import SkillRegistry
from google.adk.tools.skill_toolset import SkillToolset
from google.genai import types


class FakeModel(BaseLlm):
  """Calls load_skill until it has a successful result, then answers."""
  model: str = "fake"

  async def generate_content_async(self, llm_request, stream=False):
    loaded = any(
        p.function_response and p.function_response.name == "load_skill"
        and "error" not in (p.function_response.response or {})
        for c in llm_request.contents for p in c.parts or []
    )
    part = types.Part(text="done") if loaded else types.Part(
        function_call=types.FunctionCall(
            name="load_skill", args={"skill_name": "remote-skill"}))
    yield LlmResponse(content=types.Content(role="model", parts=[part]))


class FlakyRegistry(SkillRegistry):
  """The 2nd get_skill call stalls (network hiccup); all others succeed."""

  def __init__(self):
    self.calls = 0
    self.stalled = asyncio.Event()

  async def get_skill(self, *, name):
    self.calls += 1
    if self.calls == 2:
      self.stalled.set()
      await asyncio.Event().wait()
    return models.Skill(
        frontmatter=models.Frontmatter(name=name, description="remote"),
        instructions="Remote skill instructions.")

  async def search_skills(self, *, query):
    return []


def msg(text):
  return types.Content(role="user", parts=[types.Part(text=text)])


async def drain(agen):
  async for _ in agen:
    pass


async def main():
  registry = FlakyRegistry()
  agent = LlmAgent(name="root", model=FakeModel(),
                   tools=[SkillToolset(registry=registry)])
  app = App(name="repro", root_agent=agent,
            resumability_config=ResumabilityConfig(is_resumable=True))
  sessions = InMemorySessionService()
  runner = Runner(app=app, session_service=sessions)
  s = await sessions.create_session(app_name="repro", user_id="u")

  # Turn 1 activates the registry skill normally.
  await drain(runner.run_async(user_id="u", session_id=s.id,
                               new_message=msg("turn 1")))

  # Turn 2: get_tools re-fetches the active skill and the registry stalls.
  # The client goes away, so the run is cancelled mid-fetch.
  turn2 = asyncio.create_task(drain(runner.run_async(
      user_id="u", session_id=s.id, new_message=msg("turn 2"))))
  await registry.stalled.wait()
  turn2.cancel()
  await asyncio.gather(turn2, return_exceptions=True)

  # Resume turn 2 by invocation_id. The registry is healthy again.
  s = await sessions.get_session(app_name="repro", user_id="u", session_id=s.id)
  invocation_id = s.events[-1].invocation_id
  try:
    await asyncio.wait_for(drain(runner.run_async(
        user_id="u", session_id=s.id, invocation_id=invocation_id)), 10)
    print("resumed OK")
  except asyncio.TimeoutError:
    cached = agent.tools[0]._fetched_skill_cache[invocation_id]["remote-skill"]
    print(f"resume hung for 10s; registry calls={registry.calls}; "
          f"cache entry={cached!r}")


asyncio.run(main())

How often has this issue occurred?:

  • Always (100%) once a registry fetch is cancelled and the same invocation is
    resumed in the same process.

主要語言
Python
星號
22.3k
分支
4.4k
平均合併
1 天 2 小時
30 天內合併 PR
6

環境準備

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

google/adk-python 的其他 Issue

查看 google/adk-python 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。