Skip to content

Commit 5805ca0

Browse files
committed
fix(ag2-classic): follow non-AG2 spans when finding the outer conversation
The processor tracked only AG2-scope spans and stopped the ancestor walk at the first untracked parent. A user span between two AG2 conversations (an inner initiate_chat inside the user's own span, agent-as-tool style) hid the outer conversation, so the inner chat id became a second session.id in the same trace. on_start now records (parent span id, AG2 span or None) for every live span on the provider, still bounded by _MAX_LIVE_SPANS, and on_end releases every span. The walk continues through non-AG2 spans. approved: Nikhil 2026-10-03 blanket Refs: TH-8237
1 parent 911cabf commit 5805ca0

3 files changed

Lines changed: 103 additions & 16 deletions

File tree

‎python/frameworks/ag2-classic/tests/test_processor.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,41 @@ def test_processor_keeps_session_on_outer_conversation_only():
260260
assert by_name["speaker_selection"].attributes["gen_ai.span.kind"] == "CHAIN"
261261

262262

263+
def test_non_ag2_span_between_conversations_does_not_split_the_session():
264+
"""Agent-as-tool: the user's own span wraps an inner initiate_chat."""
265+
provider, exporter = _pipeline()
266+
processor = provider._active_span_processor._span_processors[0]
267+
ag2 = provider.get_tracer(AG2_SCOPE)
268+
user = provider.get_tracer("user.app")
269+
with ag2.start_as_current_span("conversation outer") as outer:
270+
outer.set_attribute("ag2.span.type", "conversation")
271+
with user.start_as_current_span("user work"):
272+
with user.start_as_current_span("user inner work"):
273+
with ag2.start_as_current_span("conversation inner") as inner:
274+
inner.set_attribute("ag2.span.type", "conversation")
275+
inner.set_attribute("gen_ai.conversation.id", "inner-id")
276+
outer.set_attribute("gen_ai.conversation.id", "outer-id")
277+
by_name = {s.name: s for s in exporter.get_finished_spans()}
278+
assert by_name["conversation outer"].attributes["session.id"] == "outer-id"
279+
assert "session.id" not in by_name["conversation inner"].attributes
280+
assert "session.id" not in by_name["user work"].attributes
281+
# Every tracked span, AG2 or not, is released when it ends.
282+
assert processor._live == {}
283+
284+
285+
def test_live_span_tracking_is_bounded(monkeypatch):
286+
from traceai_ag2_classic import _processor
287+
288+
monkeypatch.setattr(_processor, "_MAX_LIVE_SPANS", 2)
289+
provider, exporter = _pipeline()
290+
processor = provider._active_span_processor._span_processors[0]
291+
user = provider.get_tracer("user.app")
292+
with user.start_as_current_span("a"), user.start_as_current_span("b"), user.start_as_current_span("c"):
293+
assert len(processor._live) == 2
294+
assert processor._live == {}
295+
assert len(exporter.get_finished_spans()) == 3
296+
297+
263298
def test_processor_preserves_bounded_attribute_limits():
264299
from opentelemetry.attributes import BoundedAttributes
265300

‎python/frameworks/ag2-classic/tests/test_setup.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,47 @@ def test_group_chat_is_one_trace_with_one_session(pipeline, fake):
443443
assert selection.attributes["ag2.speaker_selection.selected"] == "critic"
444444

445445

446+
def test_user_span_around_an_inner_chat_keeps_one_session(pipeline, fake):
447+
"""Agent-as-tool: a tool runs an inner chat inside the user's own span."""
448+
from autogen import ConversableAgent
449+
450+
provider, exporter, make = pipeline
451+
tracing = make()
452+
user_tracer = provider.get_tracer("user.app")
453+
terminates = lambda m: "TERMINATE" in str(m.get("content") or "") # noqa: E731
454+
expert = ConversableAgent("expert", llm_config=fake.llm_config(), human_input_mode="NEVER")
455+
asker = ConversableAgent("asker", llm_config=False, human_input_mode="NEVER")
456+
tracing.instrument_agent(expert)
457+
tracing.instrument_agent(asker)
458+
459+
def ask_expert(city: str) -> str:
460+
"""Ask the expert about a city."""
461+
with user_tracer.start_as_current_span("ask_expert work"):
462+
inner = asker.initiate_chat(expert, message="about " + city, max_turns=1, silent=True)
463+
return str(inner.summary)
464+
465+
assistant = ConversableAgent(
466+
"assistant", llm_config=fake.llm_config(), human_input_mode="NEVER", is_termination_msg=terminates
467+
)
468+
user = ConversableAgent(
469+
"user", llm_config=False, human_input_mode="NEVER", max_consecutive_auto_reply=3, is_termination_msg=terminates
470+
)
471+
assistant.register_for_llm(description="Ask the expert")(ask_expert)
472+
user.register_for_execution()(ask_expert)
473+
tracing.instrument_agent(assistant)
474+
tracing.instrument_agent(user)
475+
result = user.initiate_chat(assistant, message="hi", max_turns=3, silent=True)
476+
477+
finished = exporter.get_finished_spans()
478+
names = {s.name for s in finished}
479+
assert {"conversation user", "execute_tool ask_expert", "ask_expert work", "conversation asker"} <= names
480+
assert len({s.context.trace_id for s in finished}) == 1
481+
assert {s.attributes.get("session.id") for s in finished} - {None} == {str(result.chat_id)}
482+
inner = next(s for s in finished if s.name == "conversation asker")
483+
assert inner.attributes["gen_ai.conversation.id"] != str(result.chat_id)
484+
assert "session.id" not in inner.attributes
485+
486+
446487
def test_patterns_are_passed_to_upstream_instrument_pattern(pipeline, fake):
447488
from autogen import ConversableAgent
448489
from autogen.agentchat import initiate_group_chat

‎python/frameworks/ag2-classic/traceai_ag2_classic/_processor.py‎

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@
1212
* ``gen_ai.span.kind`` from upstream ``ag2.span.type`` (the ``SpanType`` enum).
1313
* ``session.id`` from ``gen_ai.conversation.id`` on the outermost
1414
``conversation`` span only. Nested chats (for example group-chat speaker
15-
selection) get their own ``chat_id`` upstream; those are not copied, so one
16-
run maps to one session.
15+
selection, or an inner chat a tool starts inside the user's own span) get
16+
their own ``chat_id`` upstream; those are not copied, so one run maps to one
17+
session. The ancestor walk follows every live span, AG2 or not.
1718
* ``gen_ai.cost.total`` from upstream ``gen_ai.usage.cost`` on LLM spans, and
1819
``gen_ai.usage.total_tokens`` = input + output on LLM spans.
1920
* ``gen_ai.request.parameters`` JSON from upstream ``gen_ai.request.*``
@@ -37,7 +38,7 @@
3738
import json
3839
import logging
3940
import threading
40-
from typing import Any, Dict, Mapping, Optional
41+
from typing import Any, Dict, Mapping, Optional, Tuple
4142

4243
from opentelemetry.context import Context
4344
from opentelemetry.sdk.trace import ReadableSpan, Span, SpanProcessor
@@ -111,8 +112,9 @@
111112
# its own upstream chat with its own ``chat_id``.
112113
_CONVERSATION_TYPES = ("conversation",)
113114

114-
# Upper bound on live AG2 spans tracked for the nested-conversation check, so a
115-
# span that is started and never ended cannot grow memory without limit.
115+
# Upper bound on live spans tracked (AG2 or not) for the nested-conversation
116+
# check, so a span that is started and never ended cannot grow memory without
117+
# limit. Spans past the bound are not tracked; an ancestor walk stops there.
116118
_MAX_LIVE_SPANS = 10000
117119

118120

@@ -264,28 +266,35 @@ class AG2ClassicSpanProcessor(SpanProcessor):
264266

265267
def __init__(self, capture_content: bool = False) -> None:
266268
self.capture_content = bool(capture_content)
267-
self._live: Dict[int, Span] = {}
269+
# span_id -> (parent span_id, the span if it is an AG2 span else None),
270+
# for every live span on the provider, AG2 or not. A user span between
271+
# two AG2 conversations must not hide the outer one.
272+
self._live: Dict[int, Tuple[Optional[int], Optional[Span]]] = {}
268273
self._lock = threading.Lock()
269274
self._disabled = False
270275

271276
# SpanProcessor interface ----------------------------------------------
272277

273278
def on_start(self, span: Span, parent_context: Optional[Context] = None) -> None:
274-
if self._disabled or not _is_ag2(span):
279+
if self._disabled:
275280
return
276281
try:
282+
parent = span.parent
283+
entry = (parent.span_id if parent is not None else None, span if _is_ag2(span) else None)
277284
with self._lock:
278285
if len(self._live) < _MAX_LIVE_SPANS:
279-
self._live[span.context.span_id] = span
286+
self._live[span.context.span_id] = entry
280287
except Exception: # pragma: no cover - never break the SDK
281288
return
282289

283290
def on_end(self, span: ReadableSpan) -> None:
284-
if self._disabled or not _is_ag2(span):
291+
if self._disabled:
285292
return
286293
try:
287294
with self._lock:
288295
self._live.pop(span.context.span_id, None)
296+
if not _is_ag2(span):
297+
return
289298
attributes = dict(span.attributes or {})
290299
root = True
291300
if attributes.get(SPAN_TYPE_KEY) == "conversation":
@@ -325,16 +334,18 @@ def force_flush(self, timeout_millis: int = 30000) -> bool:
325334

326335
def _has_live_conversation_ancestor(self, span: ReadableSpan) -> bool:
327336
parent = span.parent
337+
parent_id = parent.span_id if parent is not None else None
328338
seen = 0
329339
with self._lock:
330-
while parent is not None and seen < 256:
331-
live = self._live.get(parent.span_id)
332-
if live is None:
340+
while parent_id is not None and seen < 256:
341+
entry = self._live.get(parent_id)
342+
if entry is None:
333343
return False
334-
attrs = live.attributes or {}
335-
if attrs.get(SPAN_TYPE_KEY) in _CONVERSATION_TYPES:
336-
return True
337-
parent = live.parent
344+
parent_id, ag2_span = entry
345+
if ag2_span is not None:
346+
attrs = ag2_span.attributes or {}
347+
if attrs.get(SPAN_TYPE_KEY) in _CONVERSATION_TYPES:
348+
return True
338349
seen += 1
339350
return False
340351

0 commit comments

Comments
 (0)