Skip to content

Commit 9c2c1bf

Browse files
committed
fix(ag2): keep BoundedAttributes and the dropped count on normalized spans
R7: AG2SpanProcessor.on_end replaced span._attributes with a plain dict. ReadableSpan.dropped_attributes (exported as dropped_attributes_count) reads BoundedAttributes.dropped and returns 0 for anything else, so every normalized AG2 span reported 0 dropped attributes, and the span's max_span_attributes / max_attribute_length limits and its ended-span immutability were lost. on_end now rebuilds a BoundedAttributes with the previous maxlen, max_value_len and immutability, and carries the previous dropped count over. Keys the processor adds count against the same limit: on a span already full, the oldest key is evicted and counted, as the SDK does (only reachable at the limit, 128 by default). Docstring, README note and CHANGELOG updated. Tests first, red on c1196a4 (2 failed): test_normalizing_keeps_the_sdk_dropped_attribute_count (assert 0 == 1 on span.dropped_attributes) and test_keys_the_processor_adds_count_against_span_limits (plain dict kept 3 keys over a limit of 2). Green: 88 passed on ag2 1.1.2. approved: Nikhil 2026-10-03 blanket Refs: TH-8236
1 parent c1196a4 commit 9c2c1bf

4 files changed

Lines changed: 73 additions & 2 deletions

File tree

‎python/frameworks/ag2/CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,7 @@
4343
that reset and is put back first. Installing on a provider that uses
4444
`ConcurrentMultiSpanProcessor` logs a warning (normalization before export
4545
is not guaranteed there).
46+
- Normalized spans keep the SDK's `BoundedAttributes` instead of a plain
47+
dict, so `dropped_attributes_count` is no longer reset to 0 and the span's
48+
attribute limits still apply (a key the processor adds to a full span
49+
evicts the oldest one and is counted).

‎python/frameworks/ag2/README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,10 @@ Notes:
186186
compaction and uninstrumented sub-agent spend does not reach the trace.
187187
- Network trace propagation (`ag2.otel.traceparent`) is upstream. Apart from
188188
that usage move, the processor never removes attributes it did not hide by
189-
request.
189+
request, except under a span attribute limit: the processor keeps the
190+
span's `BoundedAttributes` (limits and `dropped_attributes_count` carry
191+
over), so on a span already at `max_span_attributes` (128 by default) a key
192+
it adds evicts the oldest one and the drop is counted, as the SDK does.
190193

191194
## Troubleshooting
192195

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

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,46 @@ def test_pending_context_sessions_are_bounded_and_released_on_end():
285285
assert len(processor._session_by_span) == 0
286286

287287

288+
def _limited_pipeline(max_span_attributes: int, config: TraceConfig = TraceConfig(), max_attribute_length=None):
289+
from opentelemetry.sdk.trace import SpanLimits
290+
291+
exporter = InMemorySpanExporter()
292+
provider = TracerProvider(
293+
span_limits=SpanLimits(max_span_attributes=max_span_attributes, max_attribute_length=max_attribute_length),
294+
shutdown_on_exit=False,
295+
)
296+
provider.add_span_processor(SimpleSpanProcessor(exporter))
297+
assert install_span_processor(provider, config=config) is True
298+
return provider, exporter
299+
300+
301+
def test_normalizing_keeps_the_sdk_dropped_attribute_count():
302+
"""ReadableSpan.dropped_attributes (exported as dropped_attributes_count)
303+
reads the BoundedAttributes counter; replacing the attributes must keep it."""
304+
from opentelemetry.attributes import BoundedAttributes
305+
306+
provider, exporter = _limited_pipeline(2, TraceConfig(hide_inputs=True), max_attribute_length=64)
307+
# The SDK keeps the two newest keys and counts "a" as dropped.
308+
_emit(provider, {"a": 1, "b": 2, "gen_ai.input.messages": "secret"})
309+
(span,) = exporter.get_finished_spans()
310+
assert attrs(span) == {"b": 2}
311+
assert span.dropped_attributes == 1
312+
assert isinstance(span._attributes, BoundedAttributes)
313+
assert (span._attributes.maxlen, span._attributes.max_value_len) == (2, 64)
314+
with pytest.raises(TypeError):
315+
span._attributes["late"] = "write" # ended spans stay immutable
316+
317+
318+
def test_keys_the_processor_adds_count_against_span_limits():
319+
provider, exporter = _limited_pipeline(2)
320+
_emit(provider, {"x": 1, "gen_ai.operation.name": "chat"}) # full, nothing dropped yet
321+
(span,) = exporter.get_finished_spans()
322+
# Adding gen_ai.span.kind evicts the oldest key, as the SDK would, and
323+
# the eviction is counted.
324+
assert attrs(span) == {"gen_ai.operation.name": "chat", "gen_ai.span.kind": "LLM"}
325+
assert span.dropped_attributes == 1
326+
327+
288328
def test_processor_only_adds_keys_by_default(pipeline):
289329
"""Nothing AG2 set is stripped, including propagation-related keys."""
290330
provider, exporter = pipeline

‎python/frameworks/ag2/traceai_ag2/_processor.py‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
from fi_instrumentation.fi_types import FiSpanKindValues, SpanAttributes
4444
from fi_instrumentation.instrumentation.config import TraceConfig
4545
from fi_instrumentation.instrumentation.context_attributes import get_attributes_from_context
46+
from opentelemetry.attributes import BoundedAttributes
4647
from opentelemetry.context import Context
4748
from opentelemetry.sdk.trace import ReadableSpan, Span, SpanProcessor
4849

@@ -235,6 +236,29 @@ def _apply_trace_config(attributes: Dict[str, Any], config: TraceConfig) -> Dict
235236
return masked
236237

237238

239+
def _bounded_like(previous: Any, attributes: Dict[str, Any]) -> Any:
240+
"""Return ``attributes`` in the container the span already used.
241+
242+
The SDK keeps span attributes in ``BoundedAttributes``, and
243+
``ReadableSpan.dropped_attributes`` (exported as
244+
``dropped_attributes_count``) reads its ``dropped`` counter, which a plain
245+
dict would reset to 0. The span's limits and immutability are kept and the
246+
count is carried over. Keys this processor adds count against the same
247+
``max_span_attributes`` limit: when the span is full the oldest key is
248+
evicted and counted, as the SDK does for ``set_attribute``.
249+
"""
250+
if not isinstance(previous, BoundedAttributes):
251+
return attributes
252+
bounded = BoundedAttributes(
253+
maxlen=previous.maxlen,
254+
attributes=attributes,
255+
immutable=getattr(previous, "_immutable", True),
256+
max_value_len=previous.max_value_len,
257+
)
258+
bounded.dropped += previous.dropped
259+
return bounded
260+
261+
238262
class AG2SpanProcessor(SpanProcessor):
239263
"""Normalize AG2 ``TelemetryMiddleware`` spans before export.
240264
@@ -331,7 +355,7 @@ def on_end(self, span: ReadableSpan) -> None:
331355
# ``ReadableSpan.attributes`` is a read-only view over
332356
# ``_attributes``; every later processor and exporter in the
333357
# chain receives this same object.
334-
span._attributes = mapped # type: ignore[attr-defined]
358+
span._attributes = _bounded_like(span._attributes, mapped) # type: ignore[attr-defined]
335359
except Exception: # pragma: no cover - defensive
336360
logger.debug("traceai-ag2: could not normalize span %r", getattr(span, "name", None), exc_info=True)
337361

0 commit comments

Comments
 (0)