Observed async generator resumes under another generator’s span
Describe the bug
On DeepEval 4.2.7 (also main at b13093cf9c9b5468dbe7d00529e8f20e14300d55), interleaving two observed async generators can attach a tool call executed inside the first generator to the second generator's span.
_ObservedAsyncGenIter enters its observer once, but subsequent __anext__() and athrow() calls do not restore the generator's tracing context. Resuming it in another asyncio task can also lose the original span and trace.
To reproduce
Python 3.12.14 on Linux. No API key or model requests are needed; only the trace-posting boundary is replaced.
import os
os.environ["DEEPEVAL_TELEMETRY_OPT_OUT"] = "1"
os.environ["DEEPEVAL_DISABLE_DOTENV"] = "1"
os.environ["DEEPEVAL_DISABLE_LEGACY_KEYFILE"] = "1"
os.environ["DEEPEVAL_UPDATE_WARNING_OPT_IN"] = "0"
import asyncio
from deepeval.tracing import observe
from deepeval.tracing.context import current_span_context
from deepeval.tracing.tracing import trace_manager
trace_manager.post_trace = lambda *args, **kwargs: None
@observe(type="tool")
def tool():
return current_span_context.get().parent_uuid
@observe()
async def stream():
yield current_span_context.get().uuid
yield tool()
async def main():
first, second = stream(), stream()
try:
first_id = await first.__anext__()
second_id = await second.__anext__()
parent_id = await first.__anext__()
print("tool parent is first stream:", parent_id == first_id)
print("tool parent is second stream:", parent_id == second_id)
finally:
await second.aclose()
await first.aclose()
asyncio.run(main())Actual:
tool parent is first stream: False
tool parent is second stream: TrueExpected behavior
The tool called from inside first belongs to first (True, False).
Proposed scope / additional context
Restore the suspended generator's span/trace context before __anext__() or athrow(), including nested observers still open across a yield. If a nested generator was closed by the consumer while suspended, restore the nearest still-active ancestor instead.
This preserves the existing consumer-between-yields parenting semantics represented in context_safety_sync_observe_between_yields_schema.json. It does not propose full isolation of independent streams or changes to aclose, cancellation, asend, or streamed output capture.
Checked the nearby open work as of September 30: #3301 (cancellation), #3302 (asend), #3324 (async output capture), and #3259 (tracing migration) do not restore the suspended generator's context on resume.
AI assistance was used for the investigation and regression tests.
Source: confident-ai/deepeval