-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathtest_tracing.py
More file actions
369 lines (292 loc) · 15.1 KB
/
test_tracing.py
File metadata and controls
369 lines (292 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
"""Tests for tracing configuration — not invocation spans (those live in the invocations package)."""
import os
from unittest import mock
from opentelemetry import baggage as _otel_baggage, context as _otel_context
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
from opentelemetry.sdk.resources import Resource
from azure.ai.agentserver.core import AgentServerHost
from azure.ai.agentserver.core._config import (
resolve_agent_name,
resolve_agent_version,
resolve_appinsights_connection_string,
)
from azure.ai.agentserver.core._tracing import _FoundryEnrichmentSpanProcessor
class _CollectorExporter(SpanExporter):
"""In-memory span collector for tests."""
def __init__(self):
self.spans = []
def export(self, spans):
self.spans.extend(spans)
return SpanExportResult.SUCCESS
def shutdown(self):
return True
def force_flush(self, timeout_millis=30000):
return True
# ------------------------------------------------------------------ #
# Tracing enabled / disabled
# ------------------------------------------------------------------ #
class TestTracingToggle:
"""Observability is configured when App Insights or OTLP endpoint is available."""
def test_observability_always_called(self) -> None:
"""configure_observability is always called (it handles both logging and tracing)."""
env = os.environ.copy()
env.pop("APPLICATIONINSIGHTS_CONNECTION_STRING", None)
env.pop("OTEL_EXPORTER_OTLP_ENDPOINT", None)
with mock.patch.dict(os.environ, env, clear=True):
mock_configure = mock.MagicMock()
AgentServerHost(configure_observability=mock_configure)
mock_configure.assert_called_once()
def test_observability_receives_appinsights_env_var(self) -> None:
with mock.patch.dict(os.environ, {"APPLICATIONINSIGHTS_CONNECTION_STRING": "InstrumentationKey=00000000-0000-0000-0000-000000000000"}):
mock_configure = mock.MagicMock()
AgentServerHost(configure_observability=mock_configure)
mock_configure.assert_called_once()
assert mock_configure.call_args[1]["connection_string"] == "InstrumentationKey=00000000-0000-0000-0000-000000000000"
def test_observability_receives_otlp_env_var(self) -> None:
with mock.patch.dict(os.environ, {"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4318"}):
mock_configure = mock.MagicMock()
AgentServerHost(configure_observability=mock_configure)
mock_configure.assert_called_once()
def test_observability_receives_constructor_connection_string(self) -> None:
mock_configure = mock.MagicMock()
AgentServerHost(
applicationinsights_connection_string="InstrumentationKey=ctor",
configure_observability=mock_configure,
)
mock_configure.assert_called_once_with(
connection_string="InstrumentationKey=ctor",
log_level=None,
)
def test_observability_disabled_when_none(self) -> None:
"""Passing configure_observability=None disables all SDK-managed observability."""
with mock.patch.dict(os.environ, {"APPLICATIONINSIGHTS_CONNECTION_STRING": "InstrumentationKey=00000000-0000-0000-0000-000000000000"}):
# Should not raise even with App Insights configured
AgentServerHost(configure_observability=None)
# ------------------------------------------------------------------ #
# Application Insights connection string resolution
# ------------------------------------------------------------------ #
class TestAppInsightsConnectionString:
"""Tests for resolve_appinsights_connection_string()."""
def test_explicit_wins(self) -> None:
assert resolve_appinsights_connection_string("InstrumentationKey=abc") == "InstrumentationKey=abc"
def test_env_var(self) -> None:
with mock.patch.dict(
os.environ,
{"APPLICATIONINSIGHTS_CONNECTION_STRING": "InstrumentationKey=env"},
):
assert resolve_appinsights_connection_string(None) == "InstrumentationKey=env"
def test_none_when_unset(self) -> None:
env = os.environ.copy()
env.pop("APPLICATIONINSIGHTS_CONNECTION_STRING", None)
with mock.patch.dict(os.environ, env, clear=True):
assert resolve_appinsights_connection_string(None) is None
def test_explicit_overrides_env_var(self) -> None:
with mock.patch.dict(
os.environ,
{"APPLICATIONINSIGHTS_CONNECTION_STRING": "InstrumentationKey=env"},
):
result = resolve_appinsights_connection_string("InstrumentationKey=explicit")
assert result == "InstrumentationKey=explicit"
# ------------------------------------------------------------------ #
# _setup_distro_export (mocked)
# ------------------------------------------------------------------ #
class TestSetupDistroExport:
"""Verify _configure_tracing calls the distro with the right args."""
def test_distro_called_when_conn_str_provided(self) -> None:
with mock.patch("azure.ai.agentserver.core._tracing._setup_distro_export") as mock_distro:
from azure.ai.agentserver.core import _tracing
_tracing._configure_tracing(connection_string="InstrumentationKey=00000000-0000-0000-0000-000000000000")
mock_distro.assert_called_once()
kwargs = mock_distro.call_args[1]
assert kwargs["connection_string"] == "InstrumentationKey=00000000-0000-0000-0000-000000000000"
assert len(kwargs["span_processors"]) >= 1
assert len(kwargs["log_record_processors"]) >= 1
def test_distro_called_without_conn_str(self) -> None:
with mock.patch("azure.ai.agentserver.core._tracing._setup_distro_export") as mock_distro:
from azure.ai.agentserver.core import _tracing
_tracing._configure_tracing(connection_string=None)
mock_distro.assert_called_once()
kwargs = mock_distro.call_args[1]
assert kwargs["connection_string"] is None
# ------------------------------------------------------------------ #
# Constructor passes / skips connection string
# ------------------------------------------------------------------ #
class TestConstructorConnectionString:
"""Verify AgentServerHost forwards the connection string to configure_observability."""
def test_constructor_passes_connection_string(self) -> None:
mock_configure = mock.MagicMock()
AgentServerHost(
applicationinsights_connection_string="InstrumentationKey=ctor",
configure_observability=mock_configure,
)
mock_configure.assert_called_once_with(
connection_string="InstrumentationKey=ctor",
log_level=None,
)
# ------------------------------------------------------------------ #
# FoundryEnrichmentSpanProcessor: attribute timing
# ------------------------------------------------------------------ #
class TestFoundryEnrichmentSpanProcessor:
"""Agent identity attributes are set in _on_ending so that underlying
frameworks (LangChain, Semantic Kernel, etc.) cannot overwrite them.
Tests use real OTel spans with an in-memory exporter to verify the
exported attributes end-to-end.
"""
@staticmethod
def _create_provider(processor):
"""Return (TracerProvider, _CollectorExporter) wired with *processor*."""
collector = _CollectorExporter()
provider = TracerProvider(resource=Resource.create({}))
provider.add_span_processor(processor)
provider.add_span_processor(SimpleSpanProcessor(collector))
return provider, collector
def test_agent_attrs_present_on_exported_span(self) -> None:
proc = _FoundryEnrichmentSpanProcessor(
agent_name="my-agent", agent_version="1.0",
agent_id="my-agent:1.0", project_id="proj-123",
)
provider, collector = self._create_provider(proc)
tracer = provider.get_tracer("test")
with tracer.start_as_current_span("span"):
pass
attrs = dict(collector.spans[0].attributes)
assert attrs["gen_ai.agent.name"] == "my-agent"
assert attrs["gen_ai.agent.version"] == "1.0"
assert attrs["gen_ai.agent.id"] == "my-agent:1.0"
assert attrs["microsoft.foundry.project.id"] == "proj-123"
def test_agent_attrs_survive_framework_overwrite(self) -> None:
"""A framework setting agent attrs mid-span must not win."""
proc = _FoundryEnrichmentSpanProcessor(
agent_name="my-agent", agent_version="1.0",
agent_id="my-agent:1.0", project_id="proj-123",
)
provider, collector = self._create_provider(proc)
tracer = provider.get_tracer("test")
with tracer.start_as_current_span("span") as span:
span.set_attribute("gen_ai.agent.name", "framework-agent")
span.set_attribute("gen_ai.agent.id", "framework-agent:0.1")
attrs = dict(collector.spans[0].attributes)
assert attrs["gen_ai.agent.name"] == "my-agent"
assert attrs["gen_ai.agent.id"] == "my-agent:1.0"
def test_none_fields_are_skipped(self) -> None:
proc = _FoundryEnrichmentSpanProcessor(
agent_name=None, agent_version=None,
agent_id=None, project_id=None,
)
provider, collector = self._create_provider(proc)
tracer = provider.get_tracer("test")
with tracer.start_as_current_span("span"):
pass
attrs = dict(collector.spans[0].attributes)
assert "gen_ai.agent.name" not in attrs
assert "gen_ai.agent.version" not in attrs
assert "gen_ai.agent.id" not in attrs
assert "microsoft.foundry.project.id" not in attrs
def test_no_crash_when_span_lacks_attributes(self) -> None:
"""If the SDK changes internals, _on_ending must not raise."""
proc = _FoundryEnrichmentSpanProcessor(
agent_name="a", agent_version="1", agent_id="a:1",
)
fake_span = object() # no _attributes at all
proc._on_ending(fake_span) # should not raise
# -- session ID and conversation ID from baggage -------------------
def test_session_id_from_baggage(self) -> None:
"""session_id baggage is stamped as microsoft.session.id."""
proc = _FoundryEnrichmentSpanProcessor()
provider, collector = self._create_provider(proc)
tracer = provider.get_tracer("test")
ctx = _otel_baggage.set_baggage(
"azure.ai.agentserver.session_id", "session-456",
)
with tracer.start_as_current_span("span", context=ctx):
pass
attrs = dict(collector.spans[0].attributes)
assert attrs["microsoft.session.id"] == "session-456"
assert "gen_ai.conversation.id" not in attrs
def test_conversation_id_from_baggage(self) -> None:
"""conversation_id baggage is stamped as gen_ai.conversation.id."""
proc = _FoundryEnrichmentSpanProcessor()
provider, collector = self._create_provider(proc)
tracer = provider.get_tracer("test")
ctx = _otel_baggage.set_baggage(
"azure.ai.agentserver.conversation_id", "conv-123",
)
with tracer.start_as_current_span("span", context=ctx):
pass
attrs = dict(collector.spans[0].attributes)
assert attrs["gen_ai.conversation.id"] == "conv-123"
assert "microsoft.session.id" not in attrs
def test_both_session_and_conversation_set_independently(self) -> None:
"""When both baggage keys are present, both span attrs are set."""
proc = _FoundryEnrichmentSpanProcessor()
provider, collector = self._create_provider(proc)
tracer = provider.get_tracer("test")
ctx = _otel_baggage.set_baggage(
"azure.ai.agentserver.session_id", "session-456",
)
ctx = _otel_baggage.set_baggage(
"azure.ai.agentserver.conversation_id", "conv-123", context=ctx,
)
with tracer.start_as_current_span("span", context=ctx):
pass
attrs = dict(collector.spans[0].attributes)
assert attrs["microsoft.session.id"] == "session-456"
assert attrs["gen_ai.conversation.id"] == "conv-123"
def test_no_ids_when_no_baggage(self) -> None:
"""Neither attr is set when no baggage is present."""
proc = _FoundryEnrichmentSpanProcessor()
provider, collector = self._create_provider(proc)
tracer = provider.get_tracer("test")
with tracer.start_as_current_span("span"):
pass
attrs = dict(collector.spans[0].attributes)
assert "microsoft.session.id" not in attrs
assert "gen_ai.conversation.id" not in attrs
def test_baggage_ids_propagate_to_child_spans(self) -> None:
"""Child spans inherit both IDs from baggage."""
proc = _FoundryEnrichmentSpanProcessor()
provider, collector = self._create_provider(proc)
tracer = provider.get_tracer("test")
ctx = _otel_baggage.set_baggage(
"azure.ai.agentserver.session_id", "session-456",
)
ctx = _otel_baggage.set_baggage(
"azure.ai.agentserver.conversation_id", "conv-789", context=ctx,
)
token = _otel_context.attach(ctx)
try:
with tracer.start_as_current_span("parent"):
with tracer.start_as_current_span("child"):
pass
finally:
_otel_context.detach(token)
spans_by_name = {s.name: dict(s.attributes) for s in collector.spans}
assert spans_by_name["child"]["microsoft.session.id"] == "session-456"
assert spans_by_name["child"]["gen_ai.conversation.id"] == "conv-789"
assert spans_by_name["parent"]["microsoft.session.id"] == "session-456"
assert spans_by_name["parent"]["gen_ai.conversation.id"] == "conv-789"
# ------------------------------------------------------------------ #
# Agent name / version resolution with new env vars
# ------------------------------------------------------------------ #
class TestAgentIdentityResolution:
"""Tests for resolve_agent_name() and resolve_agent_version()."""
def test_agent_name_from_env(self) -> None:
with mock.patch.dict(os.environ, {"FOUNDRY_AGENT_NAME": "my-agent"}):
assert resolve_agent_name() == "my-agent"
def test_agent_name_default_empty(self) -> None:
env = os.environ.copy()
env.pop("FOUNDRY_AGENT_NAME", None)
with mock.patch.dict(os.environ, env, clear=True):
assert resolve_agent_name() == ""
def test_agent_version_from_env(self) -> None:
with mock.patch.dict(os.environ, {"FOUNDRY_AGENT_VERSION": "2.0"}):
assert resolve_agent_version() == "2.0"
def test_agent_version_default_empty(self) -> None:
env = os.environ.copy()
env.pop("FOUNDRY_AGENT_VERSION", None)
with mock.patch.dict(os.environ, env, clear=True):
assert resolve_agent_version() == ""