Skip to content

Commit 43e25de

Browse files
nik13claude
andcommitted
fix(strands): don't add Strands' OTLP exporter for a collector the provider already exports to (TH-8727)
configure_strands_tracing() always called StrandsTelemetry's setup_otlp_exporter(), which adds an upstream OTLP exporter to the provider it is given. With README Option 1 (register(), then configure_strands_tracing(tracer_provider=...)) and OTEL_EXPORTER_OTLP_* pointing at Future AGI, as the README's environment section suggests, that exporter and register()'s Future AGI exporter both sent every span to Future AGI once fi-instrumentation-otel stopped dropping register()'s exporter on add_span_processor(). Before that fix, the drop hid the duplicate. The instrumentor now resolves the endpoint Strands' exporter would use (OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, else OTEL_EXPORTER_OTLP_ENDPOINT, else localhost:4318) and skips it, with an INFO line, when a processor on the provider already exports to the same host and port. Any other collector still gets Strands' exporter; the console exporter and the meter are unchanged. Tests: unit tests for the decision, plus README Option 1 run for real (register(), the real exporters, collectors on 127.0.0.1) in a fresh interpreter, because conftest.py mocks opentelemetry for the session. Release: traceai-strands 0.1.1 (version, __version__, a new CHANGELOG). The fi-instrumentation-otel 1.1.1 entry names the case. Not published. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 79be724 commit 43e25de

9 files changed

Lines changed: 460 additions & 9 deletions

File tree

‎python/CHANGELOG.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@
99
added later now run next to it, as in upstream OpenTelemetry.
1010
**Behaviour change:** code that relied on `add_span_processor()` to swap out
1111
`register()`'s exporter now exports to both; pass `register(span_exporter=...)`
12-
to export somewhere else instead.
12+
to export somewhere else instead. If you pointed a second OTLP exporter at
13+
Future AGI to work around this (for example traceai-strands with
14+
`OTEL_EXPORTER_OTLP_*` set to the Future AGI endpoint), remove it or upgrade
15+
traceai-strands to 0.1.1, or every span arrives twice.
1316
- A `TracerProvider()` constructed directly is unchanged: its first
1417
`add_span_processor()` call still replaces the default `SimpleSpanProcessor`
1518
added on construction.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
## [0.1.1] - 2026-10-21
2+
### Fixed
3+
- `configure_strands_tracing()` no longer adds Strands' OTLP span exporter for a collector the tracer provider already
4+
exports to. With the provider `fi_instrumentation.register()` returns and `OTEL_EXPORTER_OTLP_*` pointing at Future AGI,
5+
every span reached Future AGI twice once fi-instrumentation-otel stopped dropping `register()`'s exporter when another
6+
span processor is added (TH-8727). The skip is logged at INFO. Strands' OTLP exporter is still added for any other
7+
collector, including the default `localhost:4318`, and the console exporter and meter are set up as before.
8+
9+
## [0.1.0]
10+
### Feature
11+
- Added support for AWS Strands Agents instrumentation.

‎python/frameworks/strands/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ agent = Agent(
5454
response = agent("Hello!")
5555
```
5656

57+
`register()`'s exporter sends the spans to Future AGI, so Option 1 needs no `OTEL_EXPORTER_OTLP_*` setting. Set `OTEL_EXPORTER_OTLP_*` only to send a second copy to another collector: Strands' own OTLP exporter is added for it. When those variables point at a collector the provider already exports to, such as Future AGI, that exporter is not added, so spans are not sent twice. On fi-instrumentation-otel 1.1.0 and earlier, Strands adding its own exporter replaced `register()`'s, so spans stopped reaching Future AGI: upgrade fi-instrumentation-otel as well.
58+
5759
### Option 2: Direct OTLP Configuration
5860

5961
```python
@@ -223,7 +225,7 @@ The integration captures these OpenTelemetry GenAI semantic attributes:
223225

224226
## Environment Variables
225227

226-
Strands respects standard OpenTelemetry environment variables:
228+
Strands respects standard OpenTelemetry environment variables. With Option 1 they are optional and configure a second destination; see Option 1 above.
227229

228230
```bash
229231
# OTLP endpoint

‎python/frameworks/strands/pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
44

55
[project]
66
name = "traceai-strands"
7-
version = "0.1.0"
7+
version = "0.1.1"
88
description = "TraceAI instrumentation for AWS Strands Agents"
99
readme = "README.md"
1010
license = "Apache-2.0"
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
"""README Option 1, run for real: register(), then configure_strands_tracing(tracer_provider=...).
2+
3+
Run by test_real_export.py in a fresh interpreter, because conftest.py replaces opentelemetry,
4+
fi_instrumentation and strands with mocks for the rest of the test session. Two OTLP/HTTP
5+
collectors on 127.0.0.1 record the span names they receive: one is Future AGI (FI_BASE_URL), the
6+
other a second backend.
7+
8+
argv[1] says where OTEL_EXPORTER_OTLP_TRACES_ENDPOINT points Strands' own OTLP exporter:
9+
"future-agi" the Future AGI collector, as the README's environment section suggests
10+
"other" the second collector
11+
12+
Prints one JSON line with what each collector received.
13+
14+
strands-agents is not a dev dependency. Without it, `strands.telemetry` is a copy of the part of
15+
strands-agents' StrandsTelemetry this package calls: setup_otlp_exporter() wraps the upstream
16+
OTLP/HTTP span exporter in a BatchSpanProcessor and adds it to the provider. With strands-agents
17+
installed, the real StrandsTelemetry is used.
18+
"""
19+
20+
import gzip
21+
import json
22+
import os
23+
import sys
24+
import threading
25+
import types
26+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
27+
from typing import Any, List, Tuple
28+
29+
from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
30+
31+
32+
def _collector() -> Tuple[ThreadingHTTPServer, List[str]]:
33+
received: List[str] = []
34+
35+
class _Handler(BaseHTTPRequestHandler):
36+
def do_POST(self) -> None:
37+
body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
38+
if self.headers.get("Content-Encoding") == "gzip":
39+
body = gzip.decompress(body)
40+
request = ExportTraceServiceRequest()
41+
request.ParseFromString(body)
42+
received.extend(
43+
span.name
44+
for resource_spans in request.resource_spans
45+
for scope_spans in resource_spans.scope_spans
46+
for span in scope_spans.spans
47+
)
48+
self.send_response(200)
49+
self.send_header("Content-Length", "0")
50+
self.end_headers()
51+
52+
def log_message(self, *args: Any) -> None:
53+
pass
54+
55+
server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
56+
threading.Thread(target=server.serve_forever, daemon=True).start()
57+
return server, received
58+
59+
60+
def _install_strands_telemetry_stand_in() -> bool:
61+
"""Use strands-agents when installed; otherwise install the copy described above."""
62+
try:
63+
import strands.telemetry # noqa: F401
64+
65+
return True
66+
except ImportError:
67+
pass
68+
69+
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
70+
from opentelemetry.sdk.trace.export import BatchSpanProcessor
71+
72+
class StrandsTelemetry:
73+
def __init__(self, tracer_provider: Any = None) -> None:
74+
self.tracer_provider = tracer_provider
75+
76+
def setup_otlp_exporter(self, **kwargs: Any) -> "StrandsTelemetry":
77+
self.tracer_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(**kwargs)))
78+
return self
79+
80+
strands = types.ModuleType("strands")
81+
telemetry = types.ModuleType("strands.telemetry")
82+
telemetry.StrandsTelemetry = StrandsTelemetry
83+
strands.telemetry = telemetry
84+
sys.modules["strands"] = strands
85+
sys.modules["strands.telemetry"] = telemetry
86+
return False
87+
88+
89+
def main() -> None:
90+
mode = sys.argv[1]
91+
future_agi, future_agi_received = _collector()
92+
other, other_received = _collector()
93+
future_agi_url = f"http://127.0.0.1:{future_agi.server_address[1]}"
94+
95+
for name in list(os.environ):
96+
if name.startswith("OTEL_"):
97+
del os.environ[name]
98+
os.environ["FI_BASE_URL"] = future_agi_url
99+
os.environ["FI_API_KEY"] = "test-api-key"
100+
os.environ["FI_SECRET_KEY"] = "test-secret-key"
101+
if mode == "future-agi":
102+
os.environ["OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"] = f"{future_agi_url}/tracer/v1/traces"
103+
elif mode == "other":
104+
os.environ["OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"] = (
105+
f"http://127.0.0.1:{other.server_address[1]}/v1/traces"
106+
)
107+
else:
108+
raise SystemExit(f"unknown mode {mode!r}")
109+
110+
real_strands = _install_strands_telemetry_stand_in()
111+
112+
from fi_instrumentation import register
113+
from fi_instrumentation.fi_types import ProjectType
114+
115+
from traceai_strands import configure_strands_tracing
116+
117+
provider = register(
118+
project_type=ProjectType.OBSERVE,
119+
project_name="traceai-strands-test",
120+
set_global_tracer_provider=False,
121+
verbose=False,
122+
)
123+
# fi-instrumentation-otel 1.1.0 and earlier mark register()'s exporter as a default that the
124+
# next add_span_processor() call replaces (fixed by TH-8727).
125+
register_marks_its_exporter = bool(getattr(provider, "_default_processor", False))
126+
127+
configure_strands_tracing(tracer_provider=provider, enable_metrics=False)
128+
129+
span_processors = len(provider._active_span_processor._span_processors)
130+
tracer = provider.get_tracer("traceai-strands-test")
131+
for i in range(3):
132+
with tracer.start_as_current_span(f"span-{i}"):
133+
pass
134+
provider.force_flush(timeout_millis=10_000)
135+
136+
print(
137+
json.dumps(
138+
{
139+
"real_strands": real_strands,
140+
"register_marks_its_exporter": register_marks_its_exporter,
141+
"span_processors": span_processors,
142+
"future_agi": sorted(future_agi_received),
143+
"other": sorted(other_received),
144+
}
145+
),
146+
flush=True,
147+
)
148+
# register() installed signal handlers and an exit-time shutdown; neither is needed here.
149+
os._exit(0)
150+
151+
152+
if __name__ == "__main__":
153+
main()

‎python/frameworks/strands/tests/test_instrumentor.py‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
"""Tests for the instrumentor module."""
22

33
import os
4+
import sys
5+
from types import SimpleNamespace
6+
47
import pytest
58
from unittest.mock import MagicMock, patch
69

@@ -182,3 +185,142 @@ def test_merges_existing_trace_attributes(self):
182185
call_kwargs = mock_agent_class.call_args[1]
183186
assert call_kwargs["trace_attributes"]["session.id"] == "sess-123"
184187
assert call_kwargs["trace_attributes"]["custom"] == "value"
188+
189+
190+
class _RecordingStrandsTelemetry:
191+
"""Stands in for strands.telemetry.StrandsTelemetry and records which exporters were set up."""
192+
193+
calls: list = []
194+
195+
def __init__(self, tracer_provider=None):
196+
self.tracer_provider = tracer_provider
197+
198+
def setup_otlp_exporter(self, **kwargs):
199+
self.calls.append("otlp")
200+
return self
201+
202+
def setup_console_exporter(self, **kwargs):
203+
self.calls.append("console")
204+
return self
205+
206+
def setup_meter(self, **kwargs):
207+
self.calls.append("meter")
208+
return self
209+
210+
211+
def _provider_exporting_to(endpoint, batch=False):
212+
"""A tracer provider shaped like the SDK's, with one processor exporting to `endpoint`."""
213+
exporter = SimpleNamespace(_endpoint=endpoint)
214+
if batch:
215+
# Recent OTel SDKs keep a BatchSpanProcessor's exporter on an inner _batch_processor.
216+
processor = SimpleNamespace(_batch_processor=SimpleNamespace(_exporter=exporter))
217+
else:
218+
processor = SimpleNamespace(span_exporter=exporter)
219+
return SimpleNamespace(
220+
_active_span_processor=SimpleNamespace(_span_processors=(processor,))
221+
)
222+
223+
224+
_FUTURE_AGI = "http://127.0.0.1:5999/tracer/v1/traces"
225+
226+
227+
class TestStrandsOtlpExporterIsNotDoubled:
228+
"""Strands' OTLP exporter is not added for a collector the provider already exports to.
229+
230+
With register()'s provider, the Future AGI exporter already sends every span. Pointing
231+
OTEL_EXPORTER_OTLP_* at Future AGI as well used to add a second exporter for the same
232+
collector, so every span arrived twice once fi-instrumentation-otel stopped dropping
233+
register()'s exporter on add_span_processor() (TH-8727).
234+
"""
235+
236+
@pytest.fixture(autouse=True)
237+
def _recording_telemetry(self, monkeypatch):
238+
StrandsInstrumentor._instance = None
239+
StrandsInstrumentor._is_instrumented = False
240+
_RecordingStrandsTelemetry.calls = []
241+
monkeypatch.setattr(
242+
sys.modules["strands.telemetry"], "StrandsTelemetry", _RecordingStrandsTelemetry
243+
)
244+
for name in ("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "OTEL_EXPORTER_OTLP_ENDPOINT"):
245+
monkeypatch.delenv(name, raising=False)
246+
yield
247+
StrandsInstrumentor._instance = None
248+
StrandsInstrumentor._is_instrumented = False
249+
250+
@pytest.mark.parametrize("batch", [False, True], ids=["simple", "batch"])
251+
def test_not_added_when_the_traces_endpoint_is_the_providers_collector(
252+
self, monkeypatch, batch
253+
):
254+
monkeypatch.setenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", _FUTURE_AGI)
255+
256+
configure_strands_tracing(
257+
tracer_provider=_provider_exporting_to(_FUTURE_AGI, batch=batch),
258+
enable_metrics=False,
259+
)
260+
261+
assert _RecordingStrandsTelemetry.calls == []
262+
263+
def test_not_added_when_the_base_endpoint_is_the_providers_collector(self, monkeypatch):
264+
monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://127.0.0.1:5999/")
265+
266+
configure_strands_tracing(
267+
tracer_provider=_provider_exporting_to(_FUTURE_AGI), enable_metrics=False
268+
)
269+
270+
assert _RecordingStrandsTelemetry.calls == []
271+
272+
def test_not_added_when_otlp_endpoint_is_the_providers_collector(self, monkeypatch):
273+
# configure_strands_tracing() stores otlp_endpoint in OTEL_EXPORTER_OTLP_ENDPOINT;
274+
# monkeypatch puts the variable back afterwards.
275+
monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "")
276+
277+
configure_strands_tracing(
278+
tracer_provider=_provider_exporting_to("https://api.futureagi.com/tracer/v1/traces"),
279+
otlp_endpoint="https://API.futureagi.com:443",
280+
enable_metrics=False,
281+
)
282+
283+
assert _RecordingStrandsTelemetry.calls == []
284+
285+
def test_console_exporter_and_meter_are_still_set_up(self, monkeypatch):
286+
monkeypatch.setenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", _FUTURE_AGI)
287+
288+
configure_strands_tracing(
289+
tracer_provider=_provider_exporting_to(_FUTURE_AGI),
290+
enable_console_exporter=True,
291+
enable_metrics=True,
292+
)
293+
294+
assert _RecordingStrandsTelemetry.calls == ["console", "meter"]
295+
296+
@pytest.mark.parametrize(
297+
"traces_endpoint",
298+
[
299+
"http://127.0.0.1:6000/v1/traces", # another port
300+
"http://collector.internal:5999/v1/traces", # another host
301+
],
302+
)
303+
def test_added_for_another_collector(self, monkeypatch, traces_endpoint):
304+
monkeypatch.setenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", traces_endpoint)
305+
306+
configure_strands_tracing(
307+
tracer_provider=_provider_exporting_to(_FUTURE_AGI), enable_metrics=False
308+
)
309+
310+
assert _RecordingStrandsTelemetry.calls == ["otlp"]
311+
312+
def test_added_for_the_default_endpoint_when_nothing_is_set(self):
313+
configure_strands_tracing(
314+
tracer_provider=_provider_exporting_to(_FUTURE_AGI), enable_metrics=False
315+
)
316+
317+
assert _RecordingStrandsTelemetry.calls == ["otlp"]
318+
319+
def test_added_when_the_provider_has_no_span_processors(
320+
self, monkeypatch, mock_tracer_provider
321+
):
322+
monkeypatch.setenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", _FUTURE_AGI)
323+
324+
configure_strands_tracing(tracer_provider=mock_tracer_provider, enable_metrics=False)
325+
326+
assert _RecordingStrandsTelemetry.calls == ["otlp"]

0 commit comments

Comments
 (0)