SkillToolset: a cancelled registry fetch leaves a stale Future in the per-invocation cache, so resuming that invocation hangs or silently does nothing
Maintainer thường phản hồi trong vòng 3 ngày
Đánh giá
Issue này chưa được đánh giá.
Mô tả
🔴 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:
- A turn is cancelled while a registry fetch is in flight. The usual cause is
a client disconnect:api_server's_monitor_client_disconnectcancels the
run task. - The client resumes that invocation (
run_async(invocation_id=...)or
/runwithinvocationId), asResumabilityConfigdocuments. - 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:
pip install google-adk==2.14.0. No API key is needed; the repro uses a
fake model and a fake registry.- Save the Minimal Reproduction Code below as
repro.pyand run
python repro.py. - 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 sameINVOCATION_ABORTEDevents either
way, so those events are not what stops the resume. - Changing only that
exceptclause toexcept BaseExceptionin 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@df9f9d04andmain@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 inget_toolsbefore 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.
- Ngôn ngữ chính
- Python
- Star
- 22.3k
- Fork
- 4.4k
- Merge trung bình
- 1 ngày 2 giờ
- Pull request đã merge (30 ngày)
- 6
Chuẩn bị môi trường
- Không có Dockerfile hay tệp Docker Compose
- Có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của google/adk-python
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
google/adk-python#8360 ·
Maintainer thường phản hồi trong vòng 3 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 82/100
google/adk-python#8359 ·
Maintainer thường phản hồi trong vòng 3 ngày
-
Can pin to litellm version be changed?Có thể đã có người làm @llalitkumarrr đã nhận 10 ngày trước. Đang mởmodels
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 65/100
google/adk-python#8129 · 2 bình luận · 1 người được giao ·
Maintainer thường phản hồi trong vòng 3 ngày
-
OpenAPI tools ignore operation- and path-level server overridesCó thể đã có người làm @sanketpatil06 đã nhận 14 ngày trước. Đang mởtools
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 75/100
google/adk-python#8064 · 4 bình luận · 1 người được giao ·
Maintainer thường phản hồi trong vòng 3 ngày
-
Two docstrings in openapi_tool document parameters the signatures do not acceptCó thể đã có người làm @surajksharma07 đã nhận 17 ngày trước. Đang mở
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 88/100
google/adk-python#8024 · 1 bình luận · 1 người được giao ·
Maintainer thường phản hồi trong vòng 3 ngày
Tất cả issue của google/adk-python
Issue tương tự
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
vllm-project/vllm#70030 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
TigreGotico/tugaphone#408 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
t: bug
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
Maintainer thường phản hồi trong vòng 3 ngày
-
needs-triage
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 85/100
Azure/azure-sdk-for-python#50155 · 1 reaction ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 66/100
Maintainer thường phản hồi trong vòng 1 ngày