Skip to content

invoke_agent span isn't marked as an error when the invocation is cancelled #8524

Backlog

Description

@Abdulrehman1978

Describe the Bug

When an agent invocation is cancelled via asyncio.CancelledError (for example via task.cancel() or asyncio.wait_for(...)), the invoke_agent <name> span ends with StatusCode.UNSET and no error.type attribute, and gen_ai.agent.invocation.duration omits error.type.

In src/google/adk/telemetry/_instrumentation.py:

  • _recording_span catches except Exception as exc:
  • record_agent_invocation catches except Exception as e:

Because asyncio.CancelledError inherits from BaseException rather than Exception (Python 3.8+), neither handler catches it. (GeneratorExit should still not be flagged as an error, so catching (Exception, asyncio.CancelledError) is the right boundary.)

Minimal Reproduction

import asyncio
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
trace.set_tracer_provider(provider)

from google.adk.agents import LlmAgent
from google.adk.models.base_llm import BaseLlm
from google.adk.runners import InMemoryRunner
from google.genai import types

class SlowLlm(BaseLlm):
    model: str = "slow"
    started: object = None
    async def generate_content_async(self, llm_request, stream=False):
        self.started.set()
        await asyncio.sleep(10)
        yield

async def main():
    started = asyncio.Event()
    agent = LlmAgent(name="slow_agent", model=SlowLlm(started=started))
    runner = InMemoryRunner(agent=agent, app_name="app")
    s = await runner.session_service.create_session(app_name="app", user_id="u")
    async def go():
        async for _ in runner.run_async(user_id="u", session_id=s.id, new_message=types.UserContent("hi")):
            pass
    task = asyncio.create_task(go())
    await started.wait()
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        pass
    for sp in exporter.get_finished_spans():
        if sp.name.startswith("invoke_agent"):
            print(sp.name, sp.status.status_code.name, sp.attributes.get("error.type"))

asyncio.run(main())
# Output on main: invoke_agent slow_agent UNSET None

Expected Behavior

invoke_agent slow_agent ends with StatusCode.ERROR and error.type == "CancelledError", and record_agent_invocation_duration receives the CancelledError so error.type="CancelledError" is recorded on the metric as well.

Activity

  1. chelsealong commented on Dec 5, 2026

    @chelsealong
    Contributor

    May I work on this issue (#8524: invokeagent span isn't marked as an error when the invocation is cancelled) 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.

  2. Abdulrehman1978 commented on Dec 5, 2026

    @Abdulrehman1978
    Author

    @chelsealong Thanks for the interest! I've already opened #8525 with the fix and regression tests (passing locally on \ ests/unittests/telemetry/).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions