agentrail-python 0.2.0__py3-none-any.whl → 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentrail_python/__init__.py +2 -5
- agentrail_python/_cli.py +173 -0
- agentrail_python/_client.py +32 -22
- agentrail_python/_handoff.py +10 -2
- agentrail_python/_init.py +15 -41
- agentrail_python/_options.py +1 -5
- agentrail_python/_outbound.py +39 -17
- agentrail_python/_privacy.py +5 -0
- agentrail_python/_processors.py +171 -215
- agentrail_python/_runtime.py +46 -6
- agentrail_python/_version.py +1 -1
- agentrail_python/asgi.py +6 -3
- agentrail_python/httpx.py +19 -15
- agentrail_python/mcp.py +32 -15
- agentrail_python/requests.py +14 -9
- agentrail_python/wsgi.py +5 -4
- {agentrail_python-0.2.0.dist-info → agentrail_python-0.4.0.dist-info}/METADATA +72 -5
- agentrail_python-0.4.0.dist-info/RECORD +26 -0
- {agentrail_python-0.2.0.dist-info → agentrail_python-0.4.0.dist-info}/WHEEL +1 -1
- agentrail_python-0.2.0.dist-info/RECORD +0 -25
- {agentrail_python-0.2.0.dist-info → agentrail_python-0.4.0.dist-info}/licenses/LICENSE +0 -0
agentrail_python/_processors.py
CHANGED
|
@@ -1,44 +1,141 @@
|
|
|
1
1
|
# Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
|
|
2
|
-
"""
|
|
2
|
+
"""Agentrail's own tracer provider, export queues and delivery to its collector.
|
|
3
|
+
|
|
4
|
+
Nothing here is registered globally: the application's OpenTelemetry setup,
|
|
5
|
+
and any other tracer it runs, never sees Agentrail's spans, and Agentrail never
|
|
6
|
+
sees theirs. Nothing is read from OpenTelemetry's environment variables either:
|
|
7
|
+
``OTEL_*`` configure the application's own SDK and exporters.
|
|
8
|
+
"""
|
|
3
9
|
|
|
4
10
|
from __future__ import annotations
|
|
5
11
|
|
|
12
|
+
import math
|
|
6
13
|
import os
|
|
14
|
+
import random
|
|
15
|
+
import threading
|
|
7
16
|
import time
|
|
8
17
|
import weakref
|
|
9
|
-
from
|
|
10
|
-
from
|
|
18
|
+
from datetime import timezone
|
|
19
|
+
from email.utils import parsedate_to_datetime
|
|
11
20
|
|
|
12
21
|
import requests
|
|
13
22
|
from opentelemetry import context as otel_context
|
|
14
|
-
from opentelemetry import
|
|
15
|
-
from opentelemetry.exporter.otlp.proto.
|
|
16
|
-
from opentelemetry.
|
|
17
|
-
from opentelemetry.
|
|
18
|
-
CarrierT,
|
|
19
|
-
Getter,
|
|
20
|
-
Setter,
|
|
21
|
-
TextMapPropagator,
|
|
22
|
-
default_getter,
|
|
23
|
-
default_setter,
|
|
24
|
-
)
|
|
25
|
-
from opentelemetry.sdk._logs import LogRecordProcessor, ReadableLogRecord, ReadWriteLogRecord
|
|
26
|
-
from opentelemetry.sdk._logs.export import LogRecordExportResult
|
|
27
|
-
from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor
|
|
23
|
+
from opentelemetry.exporter.otlp.proto.common._log_encoder import encode_logs
|
|
24
|
+
from opentelemetry.exporter.otlp.proto.common.trace_encoder import encode_spans
|
|
25
|
+
from opentelemetry.sdk._logs import ReadableLogRecord
|
|
26
|
+
from opentelemetry.sdk.trace import ReadableSpan, SpanLimits, SpanProcessor, TracerProvider
|
|
28
27
|
from opentelemetry.sdk.trace import Span as SdkSpan
|
|
29
|
-
from opentelemetry.sdk.trace.
|
|
30
|
-
from opentelemetry.sdk.trace.sampling import Decision, Sampler, SamplingResult
|
|
31
|
-
from opentelemetry.trace import Link, SpanKind, TraceState
|
|
32
|
-
from opentelemetry.util.types import Attributes
|
|
28
|
+
from opentelemetry.sdk.trace.sampling import ALWAYS_ON
|
|
33
29
|
|
|
34
30
|
from ._client import Client
|
|
35
|
-
from .
|
|
36
|
-
from .
|
|
37
|
-
from ._privacy import StructuredLog, copy_log, copy_span, log_weight, span_weight, without_payloads
|
|
31
|
+
from ._options import Options, resolve
|
|
32
|
+
from ._privacy import copy_span, log_weight, span_weight, without_payloads
|
|
38
33
|
from ._queue import ExportQueue
|
|
39
|
-
from ._runtime import Runtime, SpanMeta
|
|
34
|
+
from ._runtime import Runtime, SpanMeta, current
|
|
40
35
|
from ._suppression import suppressed
|
|
41
36
|
|
|
37
|
+
# The SDK's defaults, stated, so OTEL_SPAN_*_LIMIT and OTEL_ATTRIBUTE_*_LIMIT
|
|
38
|
+
# (the application's) never cut Agentrail's spans: no length limit.
|
|
39
|
+
_LIMITS = SpanLimits(
|
|
40
|
+
max_attributes=128,
|
|
41
|
+
max_events=128,
|
|
42
|
+
max_links=128,
|
|
43
|
+
max_span_attributes=128,
|
|
44
|
+
max_event_attributes=128,
|
|
45
|
+
max_link_attributes=128,
|
|
46
|
+
max_attribute_length=SpanLimits.UNSET,
|
|
47
|
+
max_span_attribute_length=SpanLimits.UNSET,
|
|
48
|
+
)
|
|
49
|
+
# What opentelemetry-exporter-otlp-proto-http 1.45 retries, and how.
|
|
50
|
+
_ATTEMPTS = 6
|
|
51
|
+
_JITTER = 0.2
|
|
52
|
+
_RETRYABLE = frozenset((429, 502, 503, 504))
|
|
53
|
+
_UNREACHABLE = (requests.ConnectionError, requests.Timeout)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _retry_after(value: str | None) -> float | None:
|
|
57
|
+
"""The seconds a Retry-After header asks for: delay-seconds or an HTTP-date."""
|
|
58
|
+
if value is None:
|
|
59
|
+
return None
|
|
60
|
+
value = value.strip()
|
|
61
|
+
try:
|
|
62
|
+
seconds: float | None = float(value)
|
|
63
|
+
except ValueError:
|
|
64
|
+
seconds = None
|
|
65
|
+
if seconds is not None:
|
|
66
|
+
return max(seconds, 0.0) if math.isfinite(seconds) else None
|
|
67
|
+
try:
|
|
68
|
+
when = parsedate_to_datetime(value)
|
|
69
|
+
except (TypeError, ValueError):
|
|
70
|
+
return None
|
|
71
|
+
if when.tzinfo is None:
|
|
72
|
+
when = when.replace(tzinfo=timezone.utc)
|
|
73
|
+
return max(when.timestamp() - time.time(), 0.0)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class _Collector:
|
|
77
|
+
"""One signal's path on Agentrail's collector, configured by Agentrail alone.
|
|
78
|
+
|
|
79
|
+
OpenTelemetry's OTLP exporters also take the application's
|
|
80
|
+
``OTEL_EXPORTER_OTLP_*`` settings: its headers (a vendor's key would reach
|
|
81
|
+
Agentrail), compression, certificates and timeout. This sends the batch
|
|
82
|
+
OpenTelemetry's encoder builds with Agentrail's headers only, uncompressed,
|
|
83
|
+
over requests' own TLS.
|
|
84
|
+
|
|
85
|
+
It retries as that exporter does (1.45): six attempts at most, all within the
|
|
86
|
+
export timeout, on 429, 502, 503 and 504 and when the collector cannot be
|
|
87
|
+
reached (once at once, then with backoff), waiting 2**n seconds within 20%
|
|
88
|
+
or what Retry-After asks, never past the deadline, and not once shut down.
|
|
89
|
+
urllib3's Retry does not fit: it has no overall deadline and its waits
|
|
90
|
+
cannot be cut short at shutdown, and the queue's flush and shutdown bounds
|
|
91
|
+
rely on both.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
def __init__(self, url: str, secret: str, timeout: float, session: requests.Session) -> None:
|
|
95
|
+
self._url = url
|
|
96
|
+
self._headers = {"Authorization": f"Bearer {secret}", "Content-Type": "application/x-protobuf"}
|
|
97
|
+
self._timeout = timeout
|
|
98
|
+
self._session = session
|
|
99
|
+
self._stopped = threading.Event()
|
|
100
|
+
|
|
101
|
+
def send(self, body: bytes) -> bool:
|
|
102
|
+
deadline = time.monotonic() + self._timeout
|
|
103
|
+
for attempt in range(_ATTEMPTS):
|
|
104
|
+
wait = 2**attempt * random.uniform(1 - _JITTER, 1 + _JITTER)
|
|
105
|
+
try:
|
|
106
|
+
response = self._post(body, deadline)
|
|
107
|
+
except _UNREACHABLE:
|
|
108
|
+
retryable = True
|
|
109
|
+
else:
|
|
110
|
+
if 200 <= response.status_code < 400:
|
|
111
|
+
return True
|
|
112
|
+
retryable = response.status_code in _RETRYABLE
|
|
113
|
+
asked = _retry_after(response.headers.get("retry-after")) if retryable else None
|
|
114
|
+
if asked is not None:
|
|
115
|
+
wait = asked
|
|
116
|
+
if not retryable or attempt + 1 == _ATTEMPTS or wait >= deadline - time.monotonic():
|
|
117
|
+
return False
|
|
118
|
+
if self._stopped.wait(wait):
|
|
119
|
+
return False
|
|
120
|
+
return False
|
|
121
|
+
|
|
122
|
+
def _post(self, body: bytes, deadline: float) -> requests.Response:
|
|
123
|
+
try:
|
|
124
|
+
return self._attempt(body, deadline)
|
|
125
|
+
except _UNREACHABLE:
|
|
126
|
+
# At once, once: usually a pooled connection the collector closed.
|
|
127
|
+
return self._attempt(body, deadline)
|
|
128
|
+
|
|
129
|
+
def _attempt(self, body: bytes, deadline: float) -> requests.Response:
|
|
130
|
+
remaining = deadline - time.monotonic()
|
|
131
|
+
if remaining <= 0:
|
|
132
|
+
raise requests.Timeout("The export timeout passed before the collector answered.")
|
|
133
|
+
return self._session.post(self._url, data=body, headers=self._headers, timeout=remaining, allow_redirects=False)
|
|
134
|
+
|
|
135
|
+
def shutdown(self) -> None:
|
|
136
|
+
self._stopped.set()
|
|
137
|
+
self._session.close()
|
|
138
|
+
|
|
42
139
|
|
|
43
140
|
class _SpanProcessor(SpanProcessor):
|
|
44
141
|
def __init__(self, runtime: Runtime, queue: ExportQueue[ReadableSpan]) -> None:
|
|
@@ -48,7 +145,7 @@ class _SpanProcessor(SpanProcessor):
|
|
|
48
145
|
def on_start(self, span: SdkSpan, parent_context: otel_context.Context | None = None) -> None:
|
|
49
146
|
if suppressed():
|
|
50
147
|
return
|
|
51
|
-
ctx =
|
|
148
|
+
ctx = current() if parent_context is None else parent_context
|
|
52
149
|
state = self._runtime.state(ctx)
|
|
53
150
|
if state is None:
|
|
54
151
|
return
|
|
@@ -71,192 +168,51 @@ class _SpanProcessor(SpanProcessor):
|
|
|
71
168
|
return True
|
|
72
169
|
|
|
73
170
|
|
|
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
|
-
def __init__(self, runtime: Runtime, base: Sampler) -> None:
|
|
123
|
-
self._runtime = runtime
|
|
124
|
-
self._base = base
|
|
125
|
-
|
|
126
|
-
def should_sample(
|
|
127
|
-
self,
|
|
128
|
-
parent_context: otel_context.Context | None,
|
|
129
|
-
trace_id: int,
|
|
130
|
-
name: str,
|
|
131
|
-
kind: SpanKind | None = None,
|
|
132
|
-
attributes: Attributes = None,
|
|
133
|
-
links: Sequence[Link] | None = None,
|
|
134
|
-
trace_state: TraceState | None = None,
|
|
135
|
-
) -> SamplingResult:
|
|
136
|
-
result = self._base.should_sample(parent_context, trace_id, name, kind, attributes, links, trace_state)
|
|
137
|
-
ctx = otel_context.get_current() if parent_context is None else parent_context
|
|
138
|
-
if result.decision == Decision.DROP and not suppressed() and self._runtime.state(ctx) is not None:
|
|
139
|
-
# The SDK starts a span with the sampler's attributes only, and a DROP
|
|
140
|
-
# carries none: keep the ones the span was started with.
|
|
141
|
-
returned = cast(Attributes, result.attributes) # pyright: ignore[reportUnknownMemberType]
|
|
142
|
-
merged = {**(attributes or {}), **(returned or {})}
|
|
143
|
-
return SamplingResult(Decision.RECORD_ONLY, merged, result.trace_state)
|
|
144
|
-
return result
|
|
145
|
-
|
|
146
|
-
def get_description(self) -> str:
|
|
147
|
-
return f"Agentrail({self._base.get_description()})"
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
class _Propagator(TextMapPropagator):
|
|
151
|
-
"""Managed work is never continued from, or injected with, an unsigned header.
|
|
152
|
-
|
|
153
|
-
Unmanaged work goes to the customer's propagator.
|
|
154
|
-
"""
|
|
155
|
-
|
|
156
|
-
def __init__(self, runtime: Runtime, base: TextMapPropagator | None) -> None:
|
|
157
|
-
self._runtime = runtime
|
|
158
|
-
self._base = base
|
|
159
|
-
|
|
160
|
-
def extract(
|
|
161
|
-
self,
|
|
162
|
-
carrier: CarrierT,
|
|
163
|
-
context: otel_context.Context | None = None,
|
|
164
|
-
getter: Getter[CarrierT] = default_getter, # type: ignore[assignment]
|
|
165
|
-
) -> otel_context.Context:
|
|
166
|
-
ctx = otel_context.get_current() if context is None else context
|
|
167
|
-
if self._runtime.state(ctx) is not None or self._base is None:
|
|
168
|
-
return ctx
|
|
169
|
-
return self._base.extract(carrier, context, getter)
|
|
170
|
-
|
|
171
|
-
def inject(
|
|
172
|
-
self,
|
|
173
|
-
carrier: CarrierT,
|
|
174
|
-
context: otel_context.Context | None = None,
|
|
175
|
-
setter: Setter[CarrierT] = default_setter, # type: ignore[assignment]
|
|
176
|
-
) -> None:
|
|
177
|
-
ctx = otel_context.get_current() if context is None else context
|
|
178
|
-
if self._runtime.state(ctx) is not None or suppressed() or self._base is None:
|
|
179
|
-
return
|
|
180
|
-
self._base.inject(carrier, context, setter)
|
|
181
|
-
|
|
182
|
-
@property
|
|
183
|
-
def fields(self) -> set[str]:
|
|
184
|
-
return set(OWNED_HEADERS) | (set() if self._base is None else set(self._base.fields))
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
def _export_spans(exporter: OTLPSpanExporter, spans: Sequence[ReadableSpan]) -> bool:
|
|
188
|
-
return exporter.export(spans) == SpanExportResult.SUCCESS
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
def _export_logs(exporter: OTLPLogExporter, records: Sequence[ReadableLogRecord]) -> bool:
|
|
192
|
-
return exporter.export(records) == LogRecordExportResult.SUCCESS
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
class Processors:
|
|
196
|
-
"""Construct before the customer's tracer provider; then ``bind`` that provider once.
|
|
197
|
-
|
|
198
|
-
Registers nothing globally.
|
|
199
|
-
"""
|
|
200
|
-
|
|
201
|
-
def __init__(self, options: Options) -> None:
|
|
202
|
-
resolved = resolve(options)
|
|
203
|
-
self._runtime = runtime = Runtime(resolved)
|
|
204
|
-
headers = {"Authorization": f"Bearer {options.collector.secret}"}
|
|
205
|
-
timeout = resolved.queue.export_timeout
|
|
206
|
-
span_session, log_session = requests.Session(), requests.Session()
|
|
207
|
-
span_exporter = OTLPSpanExporter(
|
|
208
|
-
endpoint=f"{resolved.endpoint}/v1/traces", headers=headers, timeout=timeout, session=span_session
|
|
209
|
-
)
|
|
210
|
-
log_exporter = OTLPLogExporter(
|
|
211
|
-
endpoint=f"{resolved.endpoint}/v1/logs", headers=headers, timeout=timeout, session=log_session
|
|
212
|
-
)
|
|
213
|
-
# A forked child must not write to a connection the parent still uses:
|
|
214
|
-
# it drops the pooled connections it inherited and opens its own.
|
|
215
|
-
# Weak references: a shut-down SDK's sessions are not kept alive by the hook.
|
|
216
|
-
if hasattr(os, "register_at_fork"):
|
|
217
|
-
sessions = (weakref.ref(span_session), weakref.ref(log_session))
|
|
218
|
-
|
|
219
|
-
def drop_inherited_connections() -> None:
|
|
220
|
-
for reference in sessions:
|
|
221
|
-
session = reference()
|
|
222
|
-
if session is not None:
|
|
223
|
-
session.close()
|
|
224
|
-
|
|
225
|
-
os.register_at_fork(after_in_child=drop_inherited_connections)
|
|
226
|
-
self.spans: ExportQueue[ReadableSpan] = ExportQueue(
|
|
227
|
-
"traces",
|
|
228
|
-
resolved.queue,
|
|
229
|
-
lambda batch: _export_spans(span_exporter, batch),
|
|
230
|
-
lambda code, count: runtime.report(code, "traces", count),
|
|
231
|
-
span_exporter.shutdown,
|
|
232
|
-
weigh=span_weight,
|
|
233
|
-
strip=without_payloads,
|
|
234
|
-
)
|
|
235
|
-
self.logs: ExportQueue[ReadableLogRecord] = ExportQueue(
|
|
236
|
-
"logs",
|
|
237
|
-
resolved.queue,
|
|
238
|
-
lambda batch: _export_logs(log_exporter, batch),
|
|
239
|
-
lambda code, count: runtime.report(code, "logs", count),
|
|
240
|
-
log_exporter.shutdown,
|
|
241
|
-
weigh=log_weight,
|
|
242
|
-
)
|
|
243
|
-
self.span_processor: SpanProcessor = _SpanProcessor(runtime, self.spans)
|
|
244
|
-
self.log_processor: LogRecordProcessor = _LogProcessor(runtime, self.logs)
|
|
245
|
-
self.propagator: TextMapPropagator = _Propagator(runtime, options.propagator)
|
|
246
|
-
self._bound = False
|
|
247
|
-
|
|
248
|
-
def sampler(self, base: Sampler) -> Sampler:
|
|
249
|
-
"""Wrap the customer's sampler so managed spans it drops stay record-only."""
|
|
250
|
-
return _Sampler(self._runtime, base)
|
|
251
|
-
|
|
252
|
-
def bind(self, provider: trace.TracerProvider) -> Client:
|
|
253
|
-
"""The client that records with ``provider``. Call once."""
|
|
254
|
-
if self._bound:
|
|
255
|
-
raise ConfigurationError("These processors are already bound to a tracer provider.")
|
|
256
|
-
self._bound = True
|
|
257
|
-
return Client(self._runtime, provider, self.spans, self.logs)
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
def create_processors(options: Options) -> Processors:
|
|
261
|
-
"""Agentrail's sampler wrapper, span and log processors and propagator for an existing setup."""
|
|
262
|
-
return Processors(options)
|
|
171
|
+
def build(options: Options) -> Client:
|
|
172
|
+
"""A client with its own tracer provider and export queues. Registers nothing globally."""
|
|
173
|
+
resolved = resolve(options)
|
|
174
|
+
runtime = Runtime(resolved)
|
|
175
|
+
secret = options.collector.secret
|
|
176
|
+
timeout = resolved.queue.export_timeout
|
|
177
|
+
span_session, log_session = requests.Session(), requests.Session()
|
|
178
|
+
traces = _Collector(f"{resolved.endpoint}/v1/traces", secret, timeout, span_session)
|
|
179
|
+
logs_collector = _Collector(f"{resolved.endpoint}/v1/logs", secret, timeout, log_session)
|
|
180
|
+
# A forked child must not write to a connection the parent still uses:
|
|
181
|
+
# it drops the pooled connections it inherited and opens its own.
|
|
182
|
+
# Weak references: a shut-down SDK's sessions are not kept alive by the hook.
|
|
183
|
+
if hasattr(os, "register_at_fork"):
|
|
184
|
+
sessions = (weakref.ref(span_session), weakref.ref(log_session))
|
|
185
|
+
|
|
186
|
+
def drop_inherited_connections() -> None:
|
|
187
|
+
for reference in sessions:
|
|
188
|
+
session = reference()
|
|
189
|
+
if session is not None:
|
|
190
|
+
session.close()
|
|
191
|
+
|
|
192
|
+
os.register_at_fork(after_in_child=drop_inherited_connections)
|
|
193
|
+
spans: ExportQueue[ReadableSpan] = ExportQueue(
|
|
194
|
+
"traces",
|
|
195
|
+
resolved.queue,
|
|
196
|
+
lambda batch: traces.send(encode_spans(batch).SerializePartialToString()),
|
|
197
|
+
lambda code, count: runtime.report(code, "traces", count),
|
|
198
|
+
traces.shutdown,
|
|
199
|
+
weigh=span_weight,
|
|
200
|
+
strip=without_payloads,
|
|
201
|
+
)
|
|
202
|
+
logs: ExportQueue[ReadableLogRecord] = ExportQueue(
|
|
203
|
+
"logs",
|
|
204
|
+
resolved.queue,
|
|
205
|
+
lambda batch: logs_collector.send(encode_logs(batch).SerializePartialToString()),
|
|
206
|
+
lambda code, count: runtime.report(code, "logs", count),
|
|
207
|
+
logs_collector.shutdown,
|
|
208
|
+
weigh=log_weight,
|
|
209
|
+
)
|
|
210
|
+
# Every span this provider starts is Agentrail's own, so all are sampled;
|
|
211
|
+
# the client's shutdown (``init`` runs it at exit) ends the provider too.
|
|
212
|
+
# OTEL_SDK_DISABLED, read by the SDK's provider itself, still turns it off:
|
|
213
|
+
# its tracer records nothing, reported as entry_not_recording.
|
|
214
|
+
provider = TracerProvider(sampler=ALWAYS_ON, resource=runtime.resource, span_limits=_LIMITS, shutdown_on_exit=False)
|
|
215
|
+
provider.add_span_processor(_SpanProcessor(runtime, spans))
|
|
216
|
+
client = Client(runtime, provider, spans, logs)
|
|
217
|
+
client._on_shutdown.append(provider.shutdown) # pyright: ignore[reportPrivateUsage]
|
|
218
|
+
return client
|
agentrail_python/_runtime.py
CHANGED
|
@@ -1,17 +1,29 @@
|
|
|
1
1
|
# Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
|
|
2
|
-
"""Per-installation state: context keys, the resource, and span metadata.
|
|
2
|
+
"""Per-installation state: context keys, the resource, and span metadata.
|
|
3
|
+
|
|
4
|
+
Agentrail keeps its request state, milestone mark and current span in a
|
|
5
|
+
context slot of its own (``current``), never in OpenTelemetry's runtime
|
|
6
|
+
context: that one belongs to the application's tracer. OpenTelemetry's ASGI
|
|
7
|
+
middleware inside ours attaches a context extracted into an empty ``Context``,
|
|
8
|
+
and the MCP SDK continues a client's ``_meta`` traceparent the same way; either
|
|
9
|
+
would wipe keys of ours kept there. Nothing here reads, clears or replaces the
|
|
10
|
+
application's current span.
|
|
11
|
+
"""
|
|
3
12
|
|
|
4
13
|
from __future__ import annotations
|
|
5
14
|
|
|
15
|
+
import contextlib
|
|
6
16
|
import threading
|
|
7
17
|
import uuid
|
|
18
|
+
from contextvars import ContextVar, Token
|
|
8
19
|
from dataclasses import dataclass, field
|
|
9
20
|
from typing import Literal
|
|
10
21
|
|
|
11
22
|
from opentelemetry import context as otel_context
|
|
23
|
+
from opentelemetry import trace
|
|
12
24
|
from opentelemetry.sdk.resources import Resource
|
|
13
25
|
from opentelemetry.sdk.util.instrumentation import InstrumentationScope
|
|
14
|
-
from opentelemetry.trace import Link, SpanContext
|
|
26
|
+
from opentelemetry.trace import Link, Span, SpanContext
|
|
15
27
|
from opentelemetry.util.types import AttributeValue
|
|
16
28
|
|
|
17
29
|
from ._handoff import key_id, keyed_hash
|
|
@@ -29,6 +41,32 @@ from ._version import VERSION
|
|
|
29
41
|
COMPONENT = "agentrail-python"
|
|
30
42
|
Attributes = dict[str, AttributeValue]
|
|
31
43
|
|
|
44
|
+
_EMPTY = otel_context.Context()
|
|
45
|
+
_slot: ContextVar[otel_context.Context] = ContextVar("agentrail_python_context", default=_EMPTY)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def current() -> otel_context.Context:
|
|
49
|
+
"""Agentrail's own context: what its spans are parented on and its state is read from."""
|
|
50
|
+
return _slot.get()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def current_span() -> Span:
|
|
54
|
+
"""Agentrail's current span: its request entry or milestone, never the application's span."""
|
|
55
|
+
return trace.get_current_span(_slot.get())
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def attach(ctx: otel_context.Context) -> Token[otel_context.Context]:
|
|
59
|
+
return _slot.set(ctx)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def detach(token: Token[otel_context.Context]) -> None:
|
|
63
|
+
# ValueError: the scope closed in another context than it opened in (Starlette
|
|
64
|
+
# steps a sync streamed body in a fresh thread-pool copy per chunk; the event
|
|
65
|
+
# loop closes an abandoned async generator in a task of its own). That context
|
|
66
|
+
# never held this value, so there is nothing to restore.
|
|
67
|
+
with contextlib.suppress(ValueError):
|
|
68
|
+
_slot.reset(token)
|
|
69
|
+
|
|
32
70
|
|
|
33
71
|
@dataclass
|
|
34
72
|
class RequestState:
|
|
@@ -37,8 +75,10 @@ class RequestState:
|
|
|
37
75
|
verified: bool = False
|
|
38
76
|
links: list[Link] = field(default_factory=lambda: [])
|
|
39
77
|
location: Attributes = field(default_factory=lambda: {})
|
|
78
|
+
cli: Attributes = field(default_factory=lambda: {})
|
|
79
|
+
"""What a CLI's x-agentrail-cli header said of the request (``_cli.py``); set before the application runs."""
|
|
40
80
|
entry: SpanContext | None = None
|
|
41
|
-
"""The
|
|
81
|
+
"""The request's own entry span, the only one a CLI's header is recorded on."""
|
|
42
82
|
_identity: Attributes | None = None
|
|
43
83
|
_lock: threading.Lock = field(default_factory=threading.Lock)
|
|
44
84
|
|
|
@@ -84,7 +124,7 @@ class RequestFacts:
|
|
|
84
124
|
|
|
85
125
|
|
|
86
126
|
REQUEST_FACTS = otel_context.create_key("agentrail.http.request_facts")
|
|
87
|
-
"""Where the HTTP wrappers leave a request's facts for the MCP steps it carries."""
|
|
127
|
+
"""Where the HTTP wrappers leave a request's facts, in ``current()``, for the MCP steps it carries."""
|
|
88
128
|
|
|
89
129
|
|
|
90
130
|
@dataclass
|
|
@@ -154,11 +194,11 @@ class Runtime:
|
|
|
154
194
|
self._spans_lock = threading.Lock()
|
|
155
195
|
|
|
156
196
|
def state(self, ctx: otel_context.Context | None = None) -> RequestState | None:
|
|
157
|
-
value = otel_context.get_value(self.state_key, ctx)
|
|
197
|
+
value = otel_context.get_value(self.state_key, current() if ctx is None else ctx)
|
|
158
198
|
return value if isinstance(value, RequestState) else None
|
|
159
199
|
|
|
160
200
|
def mark(self, ctx: otel_context.Context | None = None) -> Mark | None:
|
|
161
|
-
value = otel_context.get_value(self.mark_key, ctx)
|
|
201
|
+
value = otel_context.get_value(self.mark_key, current() if ctx is None else ctx)
|
|
162
202
|
return value if isinstance(value, Mark) else None
|
|
163
203
|
|
|
164
204
|
def remember(self, trace_id: int, span_id: int, meta: SpanMeta) -> None:
|
agentrail_python/_version.py
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
# Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
|
|
2
|
-
VERSION = "0.
|
|
2
|
+
VERSION = "0.4.0"
|
agentrail_python/asgi.py
CHANGED
|
@@ -11,7 +11,7 @@ from opentelemetry import context as otel_context
|
|
|
11
11
|
from opentelemetry.trace import StatusCode
|
|
12
12
|
|
|
13
13
|
from ._options import IncomingRequest
|
|
14
|
-
from ._runtime import REQUEST_FACTS, RequestFacts
|
|
14
|
+
from ._runtime import REQUEST_FACTS, RequestFacts, attach, detach
|
|
15
15
|
|
|
16
16
|
if TYPE_CHECKING:
|
|
17
17
|
from ._client import Client
|
|
@@ -99,7 +99,10 @@ class AgentrailASGIMiddleware:
|
|
|
99
99
|
status.append(int(message["status"]))
|
|
100
100
|
await send(message)
|
|
101
101
|
|
|
102
|
-
|
|
102
|
+
# Agentrail's own context, never OpenTelemetry's: the application's
|
|
103
|
+
# tracer keeps its current span, and middleware of its own inside this
|
|
104
|
+
# one cannot reset the request.
|
|
105
|
+
token = attach(ctx)
|
|
103
106
|
try:
|
|
104
107
|
await self.app(scope, receive, observed_send)
|
|
105
108
|
except BaseException as error:
|
|
@@ -118,4 +121,4 @@ class AgentrailASGIMiddleware:
|
|
|
118
121
|
span.set_attribute("http.route", route)
|
|
119
122
|
span.end()
|
|
120
123
|
finally:
|
|
121
|
-
|
|
124
|
+
detach(token)
|
agentrail_python/httpx.py
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
|
|
4
4
|
``httpx.Client(transport=agentrail_python.httpx.transport(agentrail))``. Each
|
|
5
5
|
redirect passes through the transport again, so every actual destination is
|
|
6
|
-
admitted on its own.
|
|
6
|
+
admitted on its own. The application's headers, its tracers' included, pass
|
|
7
|
+
through; only an allowed origin's traceparent is replaced by a signed one.
|
|
7
8
|
"""
|
|
8
9
|
|
|
9
10
|
from __future__ import annotations
|
|
@@ -13,7 +14,6 @@ from typing import TYPE_CHECKING
|
|
|
13
14
|
|
|
14
15
|
import httpx
|
|
15
16
|
|
|
16
|
-
from ._handoff import OWNED_HEADERS
|
|
17
17
|
from ._outbound import begin, finish, origin
|
|
18
18
|
|
|
19
19
|
if TYPE_CHECKING:
|
|
@@ -22,7 +22,9 @@ if TYPE_CHECKING:
|
|
|
22
22
|
from ._client import Client
|
|
23
23
|
|
|
24
24
|
|
|
25
|
-
def _prepare(client: Client, request: httpx.Request) -> Span | None:
|
|
25
|
+
def _prepare(client: Client, request: httpx.Request) -> tuple[httpx.Request, Span | None]:
|
|
26
|
+
"""The request to send, and the call's span. The application's request is left
|
|
27
|
+
as it was: httpx builds a redirect from it, never from what was sent."""
|
|
26
28
|
url = request.url
|
|
27
29
|
target = url.raw_path.decode("ascii")
|
|
28
30
|
outgoing = begin(
|
|
@@ -33,12 +35,14 @@ def _prepare(client: Client, request: httpx.Request) -> Span | None:
|
|
|
33
35
|
target,
|
|
34
36
|
str(url),
|
|
35
37
|
)
|
|
36
|
-
if outgoing.
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
for name
|
|
40
|
-
|
|
41
|
-
|
|
38
|
+
if not outgoing.changes:
|
|
39
|
+
return request, outgoing.span
|
|
40
|
+
headers = request.headers.copy()
|
|
41
|
+
for name in outgoing.remove:
|
|
42
|
+
headers.pop(name, None)
|
|
43
|
+
headers.update(outgoing.headers)
|
|
44
|
+
sent = httpx.Request(request.method, url, headers=headers, stream=request.stream, extensions=request.extensions)
|
|
45
|
+
return sent, outgoing.span
|
|
42
46
|
|
|
43
47
|
|
|
44
48
|
class _Stream(httpx.SyncByteStream):
|
|
@@ -104,11 +108,11 @@ class AgentrailTransport(httpx.BaseTransport):
|
|
|
104
108
|
self._base = base if base is not None else httpx.HTTPTransport()
|
|
105
109
|
|
|
106
110
|
def handle_request(self, request: httpx.Request) -> httpx.Response:
|
|
107
|
-
span = _prepare(self._client, request)
|
|
111
|
+
sent, span = _prepare(self._client, request)
|
|
108
112
|
if span is None:
|
|
109
|
-
return self._base.handle_request(
|
|
113
|
+
return self._base.handle_request(sent)
|
|
110
114
|
try:
|
|
111
|
-
response = self._base.handle_request(
|
|
115
|
+
response = self._base.handle_request(sent)
|
|
112
116
|
except BaseException as error:
|
|
113
117
|
finish(span, None, error)
|
|
114
118
|
raise
|
|
@@ -130,11 +134,11 @@ class AgentrailAsyncTransport(httpx.AsyncBaseTransport):
|
|
|
130
134
|
self._base = base if base is not None else httpx.AsyncHTTPTransport()
|
|
131
135
|
|
|
132
136
|
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
|
|
133
|
-
span = _prepare(self._client, request)
|
|
137
|
+
sent, span = _prepare(self._client, request)
|
|
134
138
|
if span is None:
|
|
135
|
-
return await self._base.handle_async_request(
|
|
139
|
+
return await self._base.handle_async_request(sent)
|
|
136
140
|
try:
|
|
137
|
-
response = await self._base.handle_async_request(
|
|
141
|
+
response = await self._base.handle_async_request(sent)
|
|
138
142
|
except BaseException as error:
|
|
139
143
|
finish(span, None, error)
|
|
140
144
|
raise
|