Skip to content

Agno async stream wrapper leaks span/context on post-yield errors (span never ended, no ERROR status) #1430

Description

@graysoncooper

Describe the bug

AsyncStreamingResultWrapper.__anext__ in the Agno instrumentor only handles StopAsyncIteration. If the wrapped async stream raises any other exception after yielding at least one event, the span is never ended and no error is recorded, and a stale entry is left in the context manager.

async def __anext__(self):
"""Async iteration that keeps agent span active."""
context_token = otel_context.attach(self.agent_context)
try:
item = await self.original_result.__anext__()
return item
except StopAsyncIteration:
# Clean up when iteration is complete
if not self._consumed:
self._consumed = True
self.span.end()
self.streaming_context_manager.remove_context(self.agent_id)
raise
finally:
otel_context.detach(context_token)

The outer agent wrapper sets span.set_status(OK) before returning the wrapper and returns it, so its own try/except cannot catch errors raised later during consumer iteration. __anext__ catches only StopAsyncIteration; its finally merely detaches the context token. Any other exception mid-stream therefore skips span.set_status(ERROR), span.record_exception, span.end(), and remove_context.

Net effect: an errored async Agent/Team stream produces a span that is never ended (never exported), with no error recorded, plus a stale _contexts entry. For an observability SDK this is a telemetry-correctness defect on a realistic path (LLM streams failing mid-iteration).

Reproduction

  1. Instrument an Agno Agent.arun(..., stream=True) (or Team.arun) whose underlying async generator raises after yielding at least one event.
  2. Observe that no span is exported for the failed stream, no exception is recorded on it, and a stale entry remains in the context manager.

Suggested fix

In AsyncStreamingResultWrapper.__anext__, add an except Exception as e: that sets span.set_status(ERROR), span.record_exception(e), span.end(), and remove_context(...) (guarded so it runs once), then re-raises, mirroring the sync path and the outer wrapper's handler.

Environment: current main (HEAD f8e907b at time of report). Path introduced by #1265.


Found while testing Ito, an automated code-review tool, against recently-merged PRs. It's free for open source. Sharing this because it looked like a real bug worth fixing, not to sell anything: https://app.ito.ai/share/8c8baa02-5ba9-416d-b5bb-a7d2e8792c35?tab=details

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions