From 1a298d782a4fa3b620030aba90a12754c0e6774a Mon Sep 17 00:00:00 2001 From: Andrey Buzin Date: Mon, 16 Nov 2026 13:24:12 -0800 Subject: [PATCH 1/2] Honor explicit live telemetry parents The OTel adapter deferred to the ambient OTel context for every live framework parent. An explicit parent different from the current span was therefore ignored in the exported tree. Use the live parent's OTel context when it differs from the ambient framework parent. Keep ambient OTel parenting otherwise, so user spans can still wrap framework spans and sub-agent runs. Cover explicit and non-current parents, raw OTel wrappers, and a mocked sub-agent run inside a tool's own OTel span. --- src/ai/telemetry/otel.py | 9 ++-- tests/telemetry/test_otel.py | 101 +++++++++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 3 deletions(-) diff --git a/src/ai/telemetry/otel.py b/src/ai/telemetry/otel.py index 1a76905d..4692700c 100644 --- a/src/ai/telemetry/otel.py +++ b/src/ai/telemetry/otel.py @@ -567,10 +567,13 @@ def shutdown(self) -> None: def _parent_context( self, span: telemetry.Span ) -> opentelemetry.context.Context | None: - # sometimes we need to set a parent span that isn't currently live. - if span.parent_id is None or span.parent_id in self._live: - # here the parent span is actually live, proceed as normal + if span.parent_id is None: return None + if parent := self._live.get(span.parent_id): + current = telemetry.current_span() + if current is not None and current.id == span.parent_id: + return None + return opentelemetry.trace.set_span_in_context(parent) # parent is indeed not live # opentelemetry.io/docs/languages/python/cookbook/ diff --git a/tests/telemetry/test_otel.py b/tests/telemetry/test_otel.py index e0f403d3..9b0f03f5 100644 --- a/tests/telemetry/test_otel.py +++ b/tests/telemetry/test_otel.py @@ -705,3 +705,104 @@ def test_run_span_attributes() -> None: {"type": "function", "name": "lookup"} ] assert "gen_ai.input.messages" in attrs + + +async def test_explicit_live_parent_is_the_otel_parent( + otel_env: tuple[InMemorySpanExporter, TracerProvider], +) -> None: + """``span(parent=...)`` overrides the ambient parent, also in OTel.""" + exporter, _ = otel_env + telemetry = ai.telemetry + async with ( + telemetry.span("a") as a, + telemetry.span("b"), + telemetry.span("c", parent=a) as c, + ): + assert c.parent_id == a.id # the framework span tree is right + + spans = {s.name: s for s in exporter.get_finished_spans()} + parent = spans["c"].parent + assert parent is not None + assert parent.span_id == spans["a"].context.span_id + + +async def test_child_of_a_not_current_span_is_its_otel_child( + otel_env: tuple[InMemorySpanExporter, TracerProvider], +) -> None: + """A span opened with ``set_as_current=False`` can still be a parent.""" + exporter, _ = otel_env + telemetry = ai.telemetry + async with ( + telemetry.span("outer"), + telemetry.span("stream", set_as_current=False) as stream, + telemetry.span("child", parent=stream, set_as_current=False), + ): + pass + + spans = {s.name: s for s in exporter.get_finished_spans()} + parent = spans["child"].parent + assert parent is not None + assert parent.span_id == spans["stream"].context.span_id + + +async def test_framework_span_inside_raw_span_keeps_ambient_otel_parent( + otel_env: tuple[InMemorySpanExporter, TracerProvider], +) -> None: + exporter, provider = otel_env + tracer = provider.get_tracer("user-code") + telemetry = ai.telemetry + async with telemetry.span("a") as a: + with tracer.start_as_current_span("raw"): + async with telemetry.span("b") as b: + assert b.parent_id == a.id + + spans = {s.name: s for s in exporter.get_finished_spans()} + raw, child = spans["raw"], spans["b"] + assert raw.parent is not None + assert raw.parent.span_id == spans["a"].context.span_id + assert child.parent is not None + assert child.parent.span_id == raw.context.span_id + + +async def test_subagent_inside_tool_raw_span_keeps_ambient_otel_parent( + otel_env: tuple[InMemorySpanExporter, TracerProvider], +) -> None: + exporter, provider = otel_env + tracer = provider.get_tracer("user-code") + + @ai.tool + async def research(topic: str) -> str: + """Run a sub-agent inside the user's own OTel span.""" + with tracer.start_as_current_span("user: research step"): + subagent = ai.Agent() + async with subagent.run( + MOCK_MODEL, [ai.user_message(topic)] + ) as stream: + async for _ in stream: + pass + return "ok" + + mock_llm( + [ + [tool_call_msg(name="research", args='{"topic": "x"}')], + [text_msg("sub answer", id="m-sub")], + [text_msg("done", id="m-done")], + ] + ) + async with ai.Agent(tools=[research]).run( + MOCK_MODEL, [ai.user_message("go")] + ) as stream: + async for _ in stream: + pass + + spans = exporter.get_finished_spans() + raw = next(s for s in spans if s.name == "user: research step") + tool = next(s for s in spans if s.name == "execute_tool research") + assert raw.parent is not None + assert raw.parent.span_id == tool.context.span_id + children = [ + s + for s in spans + if s.parent is not None and s.parent.span_id == raw.context.span_id + ] + assert [s.name for s in children] == ["invoke_agent Agent"] From 2ebe9e45f9f828d855974f1eebe0e500e00f2495 Mon Sep 17 00:00:00 2001 From: Andrey Buzin Date: Thu, 19 Nov 2026 16:01:58 -0800 Subject: [PATCH 2/2] Address review --- src/ai/telemetry/otel.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/ai/telemetry/otel.py b/src/ai/telemetry/otel.py index 4692700c..a2cc7a2f 100644 --- a/src/ai/telemetry/otel.py +++ b/src/ai/telemetry/otel.py @@ -567,12 +567,17 @@ def shutdown(self) -> None: def _parent_context( self, span: telemetry.Span ) -> opentelemetry.context.Context | None: + # sometimes we need to set a parent span that isn't currently live. if span.parent_id is None: + # no parent was specified return None if parent := self._live.get(span.parent_id): current = telemetry.current_span() if current is not None and current.id == span.parent_id: + # parent is live and current, proceed as normal + # keep ambient otel context, including raw spans under parent return None + # the parent is live but not current return opentelemetry.trace.set_span_in_context(parent) # parent is indeed not live