Skip to content

Commit 74f2a85

Browse files
clean up usage of preant context propogation
1 parent 192a7dc commit 74f2a85

15 files changed

Lines changed: 89 additions & 66 deletions

File tree

libraries/microsoft-agents-a365-observability-core/microsoft_agents_a365/observability/core/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
from .tool_call_details import ToolCallDetails
3434
from .tool_type import ToolType
3535
from .trace_processor.span_processor import SpanProcessor
36-
from .utils import extract_trace_context
36+
from .utils import extract_context_from_headers, get_traceparent
3737

3838
__all__ = [
3939
# Main SDK functions
@@ -73,7 +73,8 @@
7373
"InferenceOperationType",
7474
"ToolType",
7575
# Utility functions
76-
"extract_trace_context",
76+
"extract_context_from_headers",
77+
"get_traceparent",
7778
# Constants
7879
# all constants from constants.py are exported via *
7980
]

libraries/microsoft-agents-a365-observability-core/microsoft_agents_a365/observability/core/execute_tool_scope.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def start(
4747
tenant_details: The details of the tenant
4848
request: Optional request details for additional context
4949
parent_context: Optional OpenTelemetry Context used to link this span to an
50-
upstream operation. Use ``extract_trace_context()`` to convert a
50+
upstream operation. Use ``extract_context_from_headers()`` to convert a
5151
Context from HTTP headers containing W3C traceparent.
5252
start_time: Optional explicit start time as a datetime object. Useful when
5353
recording a tool call after execution has already completed.
@@ -90,7 +90,7 @@ def __init__(
9090
tenant_details: The details of the tenant
9191
request: Optional request details for additional context
9292
parent_context: Optional OpenTelemetry Context used to link this span to an
93-
upstream operation. Use ``extract_trace_context()`` to convert a
93+
upstream operation. Use ``extract_context_from_headers()`` to convert a
9494
Context from HTTP headers containing W3C traceparent.
9595
start_time: Optional explicit start time as a datetime object. Useful when
9696
recording a tool call after execution has already completed.

libraries/microsoft-agents-a365-observability-core/microsoft_agents_a365/observability/core/inference_scope.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def start(
5050
tenant_details: The details of the tenant
5151
request: Optional request details for additional context
5252
parent_context: Optional OpenTelemetry Context used to link this span to an
53-
upstream operation. Use ``extract_trace_context()`` to convert a
53+
upstream operation. Use ``extract_context_from_headers()`` to convert a
5454
Context from HTTP headers containing W3C traceparent.
5555
start_time: Optional explicit start time as a datetime object.
5656
end_time: Optional explicit end time as a datetime object.
@@ -80,7 +80,7 @@ def __init__(
8080
tenant_details: The details of the tenant
8181
request: Optional request details for additional context
8282
parent_context: Optional OpenTelemetry Context used to link this span to an
83-
upstream operation. Use ``extract_trace_context()`` to convert a
83+
upstream operation. Use ``extract_context_from_headers()`` to convert a
8484
Context from HTTP headers containing W3C traceparent.
8585
start_time: Optional explicit start time as a datetime object.
8686
end_time: Optional explicit end time as a datetime object.

libraries/microsoft-agents-a365-observability-core/microsoft_agents_a365/observability/core/invoke_agent_scope.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def start(
6666
caller_agent_details: Optional details of the caller agent
6767
caller_details: Optional details of the non-agentic caller
6868
parent_context: Optional OpenTelemetry Context used to link this span to an
69-
upstream operation. Use ``extract_trace_context()`` to convert a
69+
upstream operation. Use ``extract_context_from_headers()`` to convert a
7070
Context from HTTP headers containing W3C traceparent.
7171
start_time: Optional explicit start time as a datetime object.
7272
end_time: Optional explicit end time as a datetime object.
@@ -109,7 +109,7 @@ def __init__(
109109
caller_agent_details: Optional details of the caller agent
110110
caller_details: Optional details of the non-agentic caller
111111
parent_context: Optional OpenTelemetry Context used to link this span to an
112-
upstream operation. Use ``extract_trace_context()`` to convert a
112+
upstream operation. Use ``extract_context_from_headers()`` to convert a
113113
Context from HTTP headers containing W3C traceparent.
114114
start_time: Optional explicit start time as a datetime object.
115115
end_time: Optional explicit end time as a datetime object.

libraries/microsoft-agents-a365-observability-core/microsoft_agents_a365/observability/core/opentelemetry_scope.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def __init__(
114114
agent_details: Optional agent details
115115
tenant_details: Optional tenant details
116116
parent_context: Optional OpenTelemetry Context used to link this span to an
117-
upstream operation. Use ``extract_trace_context()`` to extract a
117+
upstream operation. Use ``extract_context_from_headers()`` to extract a
118118
Context from HTTP headers containing W3C traceparent.
119119
start_time: Optional explicit start time as a datetime object.
120120
Useful when recording an operation after it has already completed.
@@ -303,24 +303,19 @@ def get_context(self) -> Context | None:
303303
return set_span_in_context(self._span)
304304
return None
305305

306-
def inject_trace_context(self) -> dict[str, str]:
307-
"""Inject trace context headers for distributed tracing propagation.
306+
def inject_context_to_headers(self) -> dict[str, str]:
307+
"""Inject this span's trace context into W3C HTTP headers.
308308
309-
This method returns a dictionary of headers containing the trace
310-
context (traceparent and tracestate) that can be used to propagate
311-
the current span's context to downstream services via HTTP headers
312-
or other transport mechanisms.
313-
314-
The headers follow the W3C Trace Context specification and include:
315-
- ``traceparent``: Contains version, trace-id, parent-id, and trace-flags
316-
- ``tracestate``: Contains vendor-specific trace information (if any)
309+
Returns a dictionary of headers containing ``traceparent`` and
310+
optionally ``tracestate`` that can be forwarded to downstream services
311+
or stored for later context propagation.
317312
318313
Example usage:
319314
320315
.. code-block:: python
321316
322317
scope = OpenTelemetryScope(...)
323-
headers = scope.inject_trace_context()
318+
headers = scope.inject_context_to_headers()
324319
# Add headers to outgoing HTTP request
325320
requests.get("https://downstream-service/api", headers=headers)
326321

libraries/microsoft-agents-a365-observability-core/microsoft_agents_a365/observability/core/spans_scopes/output_scope.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def start(
3636
tenant_details: The details of the tenant
3737
response: The response details from the agent
3838
parent_context: Optional OpenTelemetry Context used to link this span to an
39-
upstream operation. Use ``extract_trace_context()`` to convert a
39+
upstream operation. Use ``extract_context_from_headers()`` to convert a
4040
Context from HTTP headers containing W3C traceparent.
4141
start_time: Optional explicit start time as a datetime object.
4242
end_time: Optional explicit end time as a datetime object.
@@ -64,7 +64,7 @@ def __init__(
6464
tenant_details: The details of the tenant
6565
response: The response details from the agent
6666
parent_context: Optional OpenTelemetry Context used to link this span to an
67-
upstream operation. Use ``extract_trace_context()`` to convert a
67+
upstream operation. Use ``extract_context_from_headers()`` to convert a
6868
Context from HTTP headers containing W3C traceparent.
6969
start_time: Optional explicit start time as a datetime object.
7070
end_time: Optional explicit end time as a datetime object.

libraries/microsoft-agents-a365-observability-core/microsoft_agents_a365/observability/core/utils.py

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,12 @@
3030
logger.addHandler(logging.NullHandler())
3131

3232

33-
def extract_trace_context(headers: dict[str, str]) -> context.Context:
34-
"""Extract trace context from HTTP headers.
33+
def extract_context_from_headers(headers: dict[str, str]) -> context.Context:
34+
"""Extract an OpenTelemetry Context from W3C trace HTTP headers.
3535
36-
This function extracts W3C Trace Context from a dictionary of HTTP headers
37-
using OpenTelemetry's standard propagation mechanism.
36+
Parses ``traceparent`` (and optionally ``tracestate``) headers and returns
37+
an OpenTelemetry Context that can be passed as ``parent_context`` to any
38+
scope's ``start()`` method.
3839
3940
Args:
4041
headers: Dictionary of HTTP headers containing trace context.
@@ -51,7 +52,7 @@ def extract_trace_context(headers: dict[str, str]) -> context.Context:
5152
headers = {
5253
"traceparent": "00-1234567890abcdef1234567890abcdef-abcdefabcdef1234-01"
5354
}
54-
parent_context = extract_trace_context(headers)
55+
parent_context = extract_context_from_headers(headers)
5556
with InferenceScope.start(
5657
details, agent, tenant, parent_context=parent_context
5758
):
@@ -60,6 +61,29 @@ def extract_trace_context(headers: dict[str, str]) -> context.Context:
6061
return extract(headers)
6162

6263

64+
def get_traceparent(headers: dict[str, str]) -> str | None:
65+
"""Return the W3C ``traceparent`` value from a headers dictionary.
66+
67+
Args:
68+
headers: Dictionary of HTTP headers, typically obtained from
69+
:meth:`OpenTelemetryScope.inject_context_to_headers`.
70+
71+
Returns:
72+
The traceparent string (e.g.
73+
``"00-<trace-id>-<span-id>-<flags>"``), or ``None`` if the
74+
key is not present.
75+
76+
Example::
77+
78+
.. code-block:: python
79+
80+
# Extract traceparent from incoming HTTP request headers
81+
traceparent = get_traceparent(request.headers)
82+
turn_context.turn_state[A365_PARENT_TRACEPARENT_KEY] = traceparent
83+
"""
84+
return headers.get("traceparent")
85+
86+
6387
def safe_json_dumps(obj: Any, **kwargs: Any) -> str:
6488
return json.dumps(obj, default=str, ensure_ascii=False, **kwargs)
6589

libraries/microsoft-agents-a365-observability-hosting/microsoft_agents_a365/observability/hosting/__init__.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,15 @@
1010
ObservabilityHostingManager,
1111
ObservabilityHostingOptions,
1212
)
13-
from .middleware.output_logging_middleware import A365_PARENT_SPAN_KEY, OutputLoggingMiddleware
13+
from .middleware.output_logging_middleware import (
14+
A365_PARENT_TRACEPARENT_KEY,
15+
OutputLoggingMiddleware,
16+
)
1417

1518
__all__ = [
1619
"BaggageMiddleware",
1720
"OutputLoggingMiddleware",
18-
"A365_PARENT_SPAN_KEY",
21+
"A365_PARENT_TRACEPARENT_KEY",
1922
"ObservabilityHostingManager",
2023
"ObservabilityHostingOptions",
2124
]

libraries/microsoft-agents-a365-observability-hosting/microsoft_agents_a365/observability/hosting/middleware/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,12 @@
33

44
from .baggage_middleware import BaggageMiddleware
55
from .observability_hosting_manager import ObservabilityHostingManager, ObservabilityHostingOptions
6-
from .output_logging_middleware import A365_PARENT_SPAN_KEY, OutputLoggingMiddleware
6+
from .output_logging_middleware import A365_PARENT_TRACEPARENT_KEY, OutputLoggingMiddleware
77

88
__all__ = [
99
"BaggageMiddleware",
1010
"OutputLoggingMiddleware",
11-
"A365_PARENT_SPAN_KEY",
11+
"A365_PARENT_TRACEPARENT_KEY",
1212
"ObservabilityHostingManager",
1313
"ObservabilityHostingOptions",
1414
]

libraries/microsoft-agents-a365-observability-hosting/microsoft_agents_a365/observability/hosting/middleware/output_logging_middleware.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,16 @@
2424
from microsoft_agents_a365.observability.core.models.response import Response
2525
from microsoft_agents_a365.observability.core.spans_scopes.output_scope import OutputScope
2626
from microsoft_agents_a365.observability.core.tenant_details import TenantDetails
27-
from microsoft_agents_a365.observability.core.utils import extract_trace_context
27+
from microsoft_agents_a365.observability.core.utils import extract_context_from_headers
2828

2929
from ..scope_helpers.utils import (
3030
get_execution_type_pair,
3131
)
3232

3333
logger = logging.getLogger(__name__)
3434

35-
# TurnState key for the parent span reference (W3C traceparent string).
36-
A365_PARENT_SPAN_KEY = "A365ParentSpanId"
35+
# TurnState key for the parent trace context (W3C traceparent string).
36+
A365_PARENT_TRACEPARENT_KEY = "A365ParentTraceparent"
3737

3838

3939
def _derive_agent_details(context: TurnContext) -> AgentDetails | None:
@@ -110,7 +110,7 @@ def _derive_execution_type(context: TurnContext) -> str | None:
110110
class OutputLoggingMiddleware:
111111
"""Middleware that creates :class:`OutputScope` spans for outgoing messages.
112112
113-
Links to a parent span when :data:`A365_PARENT_SPAN_KEY` is set in
113+
Links to a parent span when :data:`A365_PARENT_TRACEPARENT_KEY` is set in
114114
``turn_state``.
115115
116116
**Privacy note:** Outgoing message content is captured verbatim as span
@@ -176,16 +176,15 @@ async def handler(
176176
await send_next()
177177
return
178178

179-
parent_id: str | None = turn_context.turn_state.get(A365_PARENT_SPAN_KEY)
179+
traceparent: str | None = turn_context.turn_state.get(A365_PARENT_TRACEPARENT_KEY)
180180
parent_context = None
181-
if parent_id:
182-
# Convert W3C traceparent string to Context using OpenTelemetry's extract
183-
parent_context = extract_trace_context({"traceparent": parent_id})
181+
if traceparent:
182+
parent_context = extract_context_from_headers({"traceparent": traceparent})
184183
else:
185184
logger.warning(
186-
"[OutputLoggingMiddleware] No parent span ref in turn_state under "
185+
"[OutputLoggingMiddleware] No traceparent in turn_state under "
187186
"'%s'. OutputScope will not be linked to a parent.",
188-
A365_PARENT_SPAN_KEY,
187+
A365_PARENT_TRACEPARENT_KEY,
189188
)
190189

191190
output_scope = OutputScope.start(

0 commit comments

Comments
 (0)