Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions src/google/adk/telemetry/_instrumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from __future__ import annotations

import asyncio
import contextlib
import dataclasses
import logging
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion src/google/adk/telemetry/_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
64 changes: 64 additions & 0 deletions tests/unittests/telemetry/test_instrumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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