From c9ac4c94ea59cdee1e3700290ae717c73b4bfd65 Mon Sep 17 00:00:00 2001 From: Abdulrehman Satkut Date: Sat, 5 Dec 2026 10:52:48 +0530 Subject: [PATCH] fix(telemetry): mark invoke_agent span as error on asyncio cancellation (#8524) --- src/google/adk/telemetry/_instrumentation.py | 18 +++--- src/google/adk/telemetry/_metrics.py | 2 +- .../telemetry/test_instrumentation.py | 64 +++++++++++++++++++ 3 files changed, 75 insertions(+), 9 deletions(-) diff --git a/src/google/adk/telemetry/_instrumentation.py b/src/google/adk/telemetry/_instrumentation.py index 7b4654a492c..72bc8e67fec 100644 --- a/src/google/adk/telemetry/_instrumentation.py +++ b/src/google/adk/telemetry/_instrumentation.py @@ -14,6 +14,7 @@ from __future__ import annotations +import asyncio import contextlib import dataclasses import logging @@ -92,14 +93,15 @@ def _recording_span(span: trace.Span) -> Iterator[trace.Span]: `start_as_current_span` would, but leaves the ambient context alone: the span travels by value instead, so it can cross a `yield` safely. - Catches `Exception` rather than `BaseException`, for the reason upstream - `use_span` does: what directly subclasses `BaseException` is not an error - the operation made. `GeneratorExit` in particular only says the consumer - stopped reading, which is routine for the generators these spans wrap. + Catches `(Exception, asyncio.CancelledError)` rather than `BaseException`, + for the reason upstream `use_span` does: what directly subclasses + `BaseException` (aside from `asyncio.CancelledError`) is not an error the + operation made. `GeneratorExit` in particular only says the consumer stopped + reading, which is routine for the generators these spans wrap. """ try: yield span - except Exception as exc: # pylint: disable=broad-except + except (Exception, asyncio.CancelledError) as exc: # pylint: disable=broad-except if span.is_recording(): span.record_exception(exc) span.set_attribute(ERROR_TYPE, tracing.resolve_error_type(exc)) @@ -703,7 +705,7 @@ def _is_sse_request(invocation_context: InvocationContext) -> bool: def _record_agent_metrics( agent_name: str, elapsed_s: float, - caught_error: Exception | None, + caught_error: BaseException | None, ) -> None: try: _metrics.record_agent_invocation_duration( @@ -983,7 +985,7 @@ async def record_agent_invocation( `stream_in_scope` instead of holding a token across a yield (b/485899016). """ start_time = time.monotonic() - caught_error: Exception | None = None + caught_error: BaseException | None = None span_name = f"invoke_agent {agent.name}" parent_context = context_api.get_current() span = tracing.tracer.start_span(span_name, context=parent_context) @@ -998,7 +1000,7 @@ async def record_agent_invocation( with _recording_span(span): tracing.trace_agent_invocation(span, agent, ctx) yield scope - except Exception as e: + except (Exception, asyncio.CancelledError) as e: caught_error = e raise finally: diff --git a/src/google/adk/telemetry/_metrics.py b/src/google/adk/telemetry/_metrics.py index 796d76d9faf..72d0fabc0ae 100644 --- a/src/google/adk/telemetry/_metrics.py +++ b/src/google/adk/telemetry/_metrics.py @@ -503,7 +503,7 @@ def _create_token_histogram( def record_agent_invocation_duration( agent_name: str, elapsed_s: float, - error: Exception | None = None, + error: BaseException | None = None, ) -> None: """Records the duration of the agent invocation.""" attrs = {gen_ai_attributes.GEN_AI_AGENT_NAME: agent_name} diff --git a/tests/unittests/telemetry/test_instrumentation.py b/tests/unittests/telemetry/test_instrumentation.py index 00c50dbea03..cd87ad14c48 100644 --- a/tests/unittests/telemetry/test_instrumentation.py +++ b/tests/unittests/telemetry/test_instrumentation.py @@ -3202,3 +3202,67 @@ async def test_a_run_nobody_is_collecting_for_still_works(): assert _about(busy.tool_seconds(), _SLICE) assert busy.model_seconds() == 0.0 + + +@pytest.mark.asyncio +async def test_record_agent_invocation_marks_cancelled_span_as_error( + telemetry: _Telemetry, +): + """Cancelling an agent invocation marks invoke_agent as ERROR with CancelledError.""" + agent = _agent() + ctx = await _invocation_context(agent) + started = asyncio.Event() + + async def run_cancelled_agent() -> None: + async with _instrumentation.record_agent_invocation(ctx, agent): + started.set() + await asyncio.sleep(10) + + with mock.patch.object( + _metrics, "record_agent_invocation_duration" + ) as mock_record: + task = asyncio.create_task(run_cancelled_agent()) + await started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + spans = [ + s for s in telemetry._span_exporter.get_finished_spans() + if s.name == f"invoke_agent {agent.name}" + ] + assert len(spans) == 1 + span = spans[0] + assert span.status.status_code == trace.StatusCode.ERROR + assert span.attributes["error.type"] == "CancelledError" + + mock_record.assert_called_once() + assert isinstance(mock_record.call_args[0][2], asyncio.CancelledError) + + +@pytest.mark.asyncio +async def test_record_agent_invocation_does_not_mark_generator_exit_as_error( + telemetry: _Telemetry, +): + """GeneratorExit is not caught as an agent invocation error.""" + agent = _agent() + ctx = await _invocation_context(agent) + + with mock.patch.object( + _metrics, "record_agent_invocation_duration" + ) as mock_record: + with pytest.raises(GeneratorExit): + async with _instrumentation.record_agent_invocation(ctx, agent): + raise GeneratorExit() + + spans = [ + s for s in telemetry._span_exporter.get_finished_spans() + if s.name == f"invoke_agent {agent.name}" + ] + assert len(spans) == 1 + span = spans[0] + assert span.status.status_code != trace.StatusCode.ERROR + assert "error.type" not in (span.attributes or {}) + + mock_record.assert_called_once() + assert mock_record.call_args[0][2] is None