struct-sdk 0.5.28__tar.gz → 0.5.30__tar.gz
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.
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/PKG-INFO +2 -1
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/README.md +3 -1
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/pyproject.toml +4 -1
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_auto.py +7 -7
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_fork_safe_http.py +31 -2
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_observations/health.py +93 -40
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_observations/poller.py +2 -1
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_operation_details.py +4 -7
- struct_sdk-0.5.30/src/struct_sdk/_otel_logs.py +52 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/core.py +46 -18
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/mcp.py +43 -23
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/.gitignore +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/LICENSE +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/PYPI.md +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/__init__.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_container.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_distro.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_event_loop.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_genai_content.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_metrics.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_observations/__init__.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_observations/config.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_observations/identity.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_observations/native_events.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_observations/outputs.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_observations/routing.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_observations/runtime.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_observations/self_metrics.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_observations/uwsgi.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/_pool.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/ag2.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/anthropic.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/autogen.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/claude_agent.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/crewai.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/gcp.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/google_genai.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/langchain.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/litellm.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/llamaindex.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/openai.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/openai_agents.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/pydantic_ai.py +0 -0
- {struct_sdk-0.5.28 → struct_sdk-0.5.30}/src/struct_sdk/temporal.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: struct-sdk
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.30
|
|
4
4
|
Summary: Python SDK for OTel auto-instrumentation and live instrumentation on Struct.
|
|
5
5
|
Project-URL: Homepage, https://struct.ai
|
|
6
6
|
Project-URL: Documentation, https://docs.struct.ai/observability/instrumentation/python
|
|
@@ -24,6 +24,7 @@ Classifier: Topic :: System :: Monitoring
|
|
|
24
24
|
Requires-Python: >=3.10
|
|
25
25
|
Requires-Dist: opentelemetry-api>=1.45.1
|
|
26
26
|
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27.0
|
|
27
|
+
Requires-Dist: opentelemetry-instrumentation-logging>=0.66b1
|
|
27
28
|
Requires-Dist: opentelemetry-sdk>=1.27.0
|
|
28
29
|
Requires-Dist: struct-sdk-native==0.2.1
|
|
29
30
|
Requires-Dist: wrapt>=1.17.3
|
|
@@ -866,7 +866,9 @@ header, nothing in SNS message attributes or Lambda payloads), so Datadog's
|
|
|
866
866
|
propagation is unchanged. An AWS instrumentor your own setup turns on keeps its
|
|
867
867
|
propagator, and because both clients share botocore's request hook, its HTTP
|
|
868
868
|
headers reach the other client's requests too. Logs, process metrics, thread context, AI spans and libraries
|
|
869
|
-
ddtrace doesn't patch still go to Struct.
|
|
869
|
+
ddtrace doesn't patch still go to Struct. ddtrace records none of Struct's own requests
|
|
870
|
+
and adds no trace headers to them; with ddtrace's opt-in `urllib3` integration, that holds
|
|
871
|
+
from ddtrace 4.17.0. With `DD_TRACE_OTEL_ENABLED=true`,
|
|
870
872
|
ddtrace's OpenTelemetry provider isn't the OpenTelemetry SDK, so Struct attaches no
|
|
871
873
|
span exporter to it. AI spans go to Struct on Struct's own provider, and Struct installs
|
|
872
874
|
its provider for metrics and logs if you left those unset.
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "struct-sdk"
|
|
7
|
-
version = "0.5.
|
|
7
|
+
version = "0.5.30"
|
|
8
8
|
description = "Python SDK for OTel auto-instrumentation and live instrumentation on Struct."
|
|
9
9
|
readme = "PYPI.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -29,6 +29,9 @@ dependencies = [
|
|
|
29
29
|
"opentelemetry-api>=1.45.1",
|
|
30
30
|
"opentelemetry-sdk>=1.27.0",
|
|
31
31
|
"opentelemetry-exporter-otlp-proto-http>=1.27.0",
|
|
32
|
+
# The app-log bridge's handler. OpenTelemetry 1.46.0 removed the SDK's own;
|
|
33
|
+
# 0.66b1 is the first release paired with API 1.45.1.
|
|
34
|
+
"opentelemetry-instrumentation-logging>=0.66b1",
|
|
32
35
|
# Stream proxies (struct_sdk.openai): isinstance-transparent, as in
|
|
33
36
|
# OpenLLMetry and ddtrace. Already required by every OTel instrumentor.
|
|
34
37
|
# 1.17.3 is the first release with CPython 3.14 wheels.
|
|
@@ -34,14 +34,14 @@ from dataclasses import dataclass, field
|
|
|
34
34
|
from importlib.metadata import PackageNotFoundError, entry_points, version
|
|
35
35
|
from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional
|
|
36
36
|
|
|
37
|
-
from opentelemetry import
|
|
37
|
+
from opentelemetry import context, metrics, trace
|
|
38
38
|
from opentelemetry.context import _SUPPRESS_INSTRUMENTATION_KEY, Context
|
|
39
39
|
from opentelemetry.propagators.textmap import TextMapPropagator
|
|
40
|
-
from opentelemetry.sdk._logs import LoggerProvider, LogRecordProcessor
|
|
41
40
|
from opentelemetry.sdk.metrics import MeterProvider
|
|
42
41
|
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
|
|
43
42
|
|
|
44
|
-
from struct_sdk import _metrics
|
|
43
|
+
from struct_sdk import _metrics, _otel_logs
|
|
44
|
+
from struct_sdk._otel_logs import LoggerProvider, LogRecordProcessor
|
|
45
45
|
from struct_sdk.core import (
|
|
46
46
|
_body_value,
|
|
47
47
|
_contain_logged,
|
|
@@ -272,7 +272,7 @@ def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
|
|
|
272
272
|
|
|
273
273
|
host_tracer_provider = trace.get_tracer_provider()
|
|
274
274
|
host_meter_provider = metrics.get_meter_provider()
|
|
275
|
-
host_logger_provider =
|
|
275
|
+
host_logger_provider = _otel_logs.api.get_logger_provider()
|
|
276
276
|
options = _with_env_disabled(options)
|
|
277
277
|
owns_traces = isinstance(host_tracer_provider, trace.ProxyTracerProvider)
|
|
278
278
|
no_host = owns_traces and _is_unset(host_meter_provider) and _is_unset(host_logger_provider)
|
|
@@ -312,7 +312,7 @@ def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
|
|
|
312
312
|
sdk._meter_provider = meter_provider
|
|
313
313
|
metrics.set_meter_provider(meter_provider)
|
|
314
314
|
if owns_logs:
|
|
315
|
-
|
|
315
|
+
_otel_logs.api.set_logger_provider(logger_provider)
|
|
316
316
|
|
|
317
317
|
if _enabled(options, METRICS):
|
|
318
318
|
def attach_metrics() -> None:
|
|
@@ -928,8 +928,8 @@ class _ExportPathFilteringLogProcessor(LogRecordProcessor):
|
|
|
928
928
|
if not self._skip(log_data):
|
|
929
929
|
_safe(lambda: self._inner.emit(log_data), site="auto.host_logs.emit") # type: ignore[attr-defined] # ty: ignore[missing-attribute]
|
|
930
930
|
|
|
931
|
-
def shutdown(self) -> None:
|
|
932
|
-
_shut_down_within(self._inner, self._budget_seconds)
|
|
931
|
+
def shutdown(self, timeout_millis: float = 30_000, **_kwargs: Any) -> None:
|
|
932
|
+
_shut_down_within(self._inner, min(self._budget_seconds, max(0, timeout_millis) / 1000))
|
|
933
933
|
|
|
934
934
|
def force_flush(self, timeout_millis: int = 30000) -> bool:
|
|
935
935
|
flushed = False
|
|
@@ -148,9 +148,38 @@ def environment_settings(
|
|
|
148
148
|
}
|
|
149
149
|
|
|
150
150
|
|
|
151
|
+
# From 4.17.0, ddtrace's requests and urllib3 integrations leave a request carrying this header
|
|
152
|
+
# untraced and without trace headers: it is how ddtrace marks its own OTLP exports
|
|
153
|
+
# (`ddtrace.internal.constants`). Struct's requests carry it for an app that turns ddtrace's urllib3
|
|
154
|
+
# integration on, which sees them below `_UntracedSession.send` (SDK-PY-112). ddtrace is never imported.
|
|
155
|
+
DDTRACE_UNTRACED_HEADERS = {"dd-otlp-export": "true"}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class _UntracedSession(requests.Session):
|
|
159
|
+
"""A session whose ``send`` hands the request straight to its adapter.
|
|
160
|
+
|
|
161
|
+
Tracers wrap ``requests.Session.send``, and one that ignores OpenTelemetry's suppression
|
|
162
|
+
(ddtrace, in every release) would record Struct's exports as the app's work and add its trace
|
|
163
|
+
headers to them (SDK-PY-112). Nothing Struct sends needs what ``Session.send`` adds: it asks
|
|
164
|
+
for no redirects and keeps no cookies. ``Session.request`` still merges the environment's
|
|
165
|
+
proxies and CA bundle before calling this.
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
def send(
|
|
169
|
+
self, request: requests.PreparedRequest, **kwargs: Any
|
|
170
|
+
) -> requests.Response:
|
|
171
|
+
kwargs.pop("allow_redirects", None)
|
|
172
|
+
response = self.get_adapter(request.url or "").send(request, **kwargs)
|
|
173
|
+
if not kwargs.get("stream"):
|
|
174
|
+
response.content # noqa: B018 - reads the body, as Session.send does, so the connection returns to its pool
|
|
175
|
+
return response
|
|
176
|
+
|
|
177
|
+
|
|
151
178
|
def fork_safe_session() -> requests.Session:
|
|
152
|
-
"""A new session that a forked child releases cleanly
|
|
153
|
-
session
|
|
179
|
+
"""A new session that a forked child releases cleanly and that tracers leave alone. Every
|
|
180
|
+
session the SDK owns uses this."""
|
|
181
|
+
session = _UntracedSession()
|
|
182
|
+
session.headers.update(DDTRACE_UNTRACED_HEADERS)
|
|
154
183
|
_sessions.add(session)
|
|
155
184
|
return session
|
|
156
185
|
|
|
@@ -23,10 +23,10 @@ from typing import Any, Callable, Mapping, Optional, Sequence
|
|
|
23
23
|
from uuid import uuid4
|
|
24
24
|
|
|
25
25
|
from opentelemetry import context
|
|
26
|
-
from opentelemetry._logs import LogRecord, LoggerProvider, SeverityNumber
|
|
27
26
|
from opentelemetry.context import Context, _SUPPRESS_INSTRUMENTATION_KEY
|
|
28
27
|
|
|
29
28
|
from struct_sdk import core
|
|
29
|
+
from struct_sdk._otel_logs import LogRecord, SeverityNumber, api
|
|
30
30
|
from struct_sdk._observations.poller import ConfigClientStatus, ObservationConfigClient
|
|
31
31
|
|
|
32
32
|
_MAX_INT = (1 << 63) - 1
|
|
@@ -68,6 +68,10 @@ HealthSink = Callable[[list[ConditionRecord], list[IdRecord]], Optional[tuple[in
|
|
|
68
68
|
# in each 5-minute window of the Observation health monitor (checked every minute). Health stays
|
|
69
69
|
# best-effort: a refused attempt waits for the next heartbeat, with no retry.
|
|
70
70
|
HEARTBEAT_SECONDS = 240.0
|
|
71
|
+
# Changes of state waiting in order for the next pass. Past it, or past their own byte charge
|
|
72
|
+
# (``HealthLimits.max_bytes``), a change is counted in overflow and its condition's latest state is
|
|
73
|
+
# sent after the changes waiting.
|
|
74
|
+
MAX_TRANSITIONS = 256
|
|
71
75
|
|
|
72
76
|
|
|
73
77
|
@dataclass(frozen=True)
|
|
@@ -109,6 +113,16 @@ class _Condition:
|
|
|
109
113
|
class _Entry:
|
|
110
114
|
condition: _Condition
|
|
111
115
|
due: float
|
|
116
|
+
# Its changes waiting to be sent; until none waits, it is not restated on the heartbeat.
|
|
117
|
+
queued: int = 0
|
|
118
|
+
# A change of it was dropped at the queue's bound: its latest state is sent after those waiting.
|
|
119
|
+
dropped: bool = False
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass(frozen=True, slots=True)
|
|
123
|
+
class _Transition:
|
|
124
|
+
entry: _Entry
|
|
125
|
+
condition: _Condition
|
|
112
126
|
|
|
113
127
|
|
|
114
128
|
def otel_records(conditions: Sequence[ConditionRecord], ids: Sequence[IdRecord], stream_id: str) -> list[LogRecord]:
|
|
@@ -147,14 +161,14 @@ class ObservationHealth:
|
|
|
147
161
|
|
|
148
162
|
Keys identify conditions, not individual records. A caller must reuse the same key for
|
|
149
163
|
recovery. Inputs are SDK-owned scalar facts and finite sequences, never application objects.
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
164
|
+
Every change of state waits in order and goes out on the next pass, so a failure that clears
|
|
165
|
+
before it was sent is sent and then recovered; an unchanged active one is restated only on the
|
|
166
|
+
heartbeat. Cleared entries retire only after an emit attempt. The bounded, best-effort stream
|
|
167
|
+
is not a durable transition journal or fleet census.
|
|
154
168
|
"""
|
|
155
169
|
|
|
156
170
|
def __init__(
|
|
157
|
-
self, provider: Optional[LoggerProvider] = None, *, logger: Any = None,
|
|
171
|
+
self, provider: Optional[api.LoggerProvider] = None, *, logger: Any = None,
|
|
158
172
|
limits: HealthLimits = HealthLimits(),
|
|
159
173
|
config_client: Optional[ObservationConfigClient] = None,
|
|
160
174
|
clock: Callable[[], float] = time.monotonic,
|
|
@@ -184,6 +198,8 @@ class ObservationHealth:
|
|
|
184
198
|
self._stop = threading.Event()
|
|
185
199
|
self._thread: Optional[threading.Thread] = None
|
|
186
200
|
self._entries: dict[str, _Entry] = {}
|
|
201
|
+
self._transitions: list[_Transition] = []
|
|
202
|
+
self._transition_bytes = 0
|
|
187
203
|
self._emitting: tuple[_Condition, ...] = ()
|
|
188
204
|
self._overflow = 0
|
|
189
205
|
self._emission_failures = 0
|
|
@@ -196,20 +212,35 @@ class ObservationHealth:
|
|
|
196
212
|
with self._lock:
|
|
197
213
|
self._sink = sink
|
|
198
214
|
|
|
199
|
-
def _state_bytes(self,
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
return sys.getsizeof(
|
|
215
|
+
def _state_bytes(self, conditions: Mapping[str, _Condition]) -> int:
|
|
216
|
+
held = list(conditions.values())
|
|
217
|
+
held.extend(item for item in self._emitting if all(item is not kept for kept in held))
|
|
218
|
+
return sys.getsizeof(conditions) + sum(item.charge() for item in held)
|
|
203
219
|
|
|
204
|
-
def _store(self, condition: _Condition, now: float) ->
|
|
205
|
-
|
|
206
|
-
|
|
220
|
+
def _store(self, condition: _Condition, now: float) -> None:
|
|
221
|
+
"""Keep a condition's new state and queue the change, or count it in overflow when the
|
|
222
|
+
table can't hold it."""
|
|
223
|
+
candidate = {key: entry.condition for key, entry in self._entries.items()}
|
|
224
|
+
candidate[condition.key] = condition
|
|
207
225
|
count = len(candidate) + sum(item.key not in candidate for item in self._emitting)
|
|
208
226
|
if count > self._limits.max_conditions or self._state_bytes(candidate) > self._limits.max_bytes:
|
|
209
227
|
self._overflow = min(_MAX_INT, self._overflow + 1)
|
|
210
|
-
return
|
|
211
|
-
self._entries
|
|
212
|
-
|
|
228
|
+
return
|
|
229
|
+
entry = self._entries.get(condition.key)
|
|
230
|
+
if entry is None:
|
|
231
|
+
entry = self._entries[condition.key] = _Entry(condition, now)
|
|
232
|
+
else:
|
|
233
|
+
entry.condition = condition
|
|
234
|
+
charge = condition.charge()
|
|
235
|
+
if len(self._transitions) >= MAX_TRANSITIONS or self._transition_bytes + charge > self._limits.max_bytes:
|
|
236
|
+
self._overflow = min(_MAX_INT, self._overflow + 1)
|
|
237
|
+
entry.dropped = True
|
|
238
|
+
entry.due = now
|
|
239
|
+
return
|
|
240
|
+
entry.dropped = False
|
|
241
|
+
entry.queued += 1
|
|
242
|
+
self._transitions.append(_Transition(entry, condition))
|
|
243
|
+
self._transition_bytes += charge
|
|
213
244
|
|
|
214
245
|
def _allowed(self) -> bool:
|
|
215
246
|
# Check PID before touching any inherited locks. A re-armed child builds its own reporter.
|
|
@@ -240,10 +271,7 @@ class ObservationHealth:
|
|
|
240
271
|
previous = self._entries.get(condition_key)
|
|
241
272
|
if previous is not None and previous.condition == condition:
|
|
242
273
|
return
|
|
243
|
-
|
|
244
|
-
if previous is not None and previous.due <= now:
|
|
245
|
-
self._overflow = min(_MAX_INT, self._overflow + 1)
|
|
246
|
-
self._store(condition, now)
|
|
274
|
+
self._store(condition, self._clock())
|
|
247
275
|
core._contain_logged(update, site="observations.health.report")
|
|
248
276
|
|
|
249
277
|
def recover(self, condition_key: str) -> None:
|
|
@@ -253,10 +281,7 @@ class ObservationHealth:
|
|
|
253
281
|
with self._lock:
|
|
254
282
|
previous = self._entries.get(condition_key)
|
|
255
283
|
if previous is not None and not previous.condition.cleared:
|
|
256
|
-
|
|
257
|
-
if previous.due <= now:
|
|
258
|
-
self._overflow = min(_MAX_INT, self._overflow + 1)
|
|
259
|
-
self._store(replace(previous.condition, cleared=True), now)
|
|
284
|
+
self._store(replace(previous.condition, cleared=True), self._clock())
|
|
260
285
|
core._contain_logged(update, site="observations.health.recover")
|
|
261
286
|
|
|
262
287
|
def record_config(self, status: ConfigClientStatus) -> None:
|
|
@@ -296,11 +321,13 @@ class ObservationHealth:
|
|
|
296
321
|
self.report(condition_key, code=code, reason=reason, observation_ids=observation_ids)
|
|
297
322
|
|
|
298
323
|
def collect(self) -> None:
|
|
299
|
-
"""One bounded background pass: every
|
|
300
|
-
|
|
301
|
-
|
|
324
|
+
"""One bounded background pass: every change of state waiting, in order, then every
|
|
325
|
+
condition due on its heartbeat or owed its latest state after a dropped change, goes to the
|
|
326
|
+
sink as one record, with one record per representative ID, in a single call. May be called
|
|
327
|
+
manually by an integration's scheduler."""
|
|
302
328
|
if not self._allowed() or not self._collect_lock.acquire(blocking=False):
|
|
303
329
|
return
|
|
330
|
+
in_flight = 0
|
|
304
331
|
try:
|
|
305
332
|
if self._client is not None:
|
|
306
333
|
self.record_config(self._client.status)
|
|
@@ -309,29 +336,55 @@ class ObservationHealth:
|
|
|
309
336
|
with self._lock:
|
|
310
337
|
sink = self._sink
|
|
311
338
|
now = self._clock()
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
339
|
+
# The latest state of each condition sent, retiring ones included, by identity.
|
|
340
|
+
due: dict[int, _Condition] = {}
|
|
341
|
+
|
|
342
|
+
def send(item: _Condition) -> None:
|
|
316
343
|
self._sequence = min(_MAX_INT, self._sequence + 1)
|
|
317
|
-
|
|
318
|
-
due.append(item)
|
|
319
|
-
if item.cleared or item.reason in {"stopped", "expired"}:
|
|
320
|
-
del self._entries[key]
|
|
321
|
-
else:
|
|
322
|
-
entry.due = now + self._limits.repeat_seconds
|
|
344
|
+
sequence = self._sequence
|
|
323
345
|
conditions.append((item.observation_id, item.key, "recovered" if item.cleared else item.reason,
|
|
324
346
|
item.code, sequence, self._overflow))
|
|
325
347
|
ids.extend((item.key, sequence, identifier) for identifier in item.ids)
|
|
326
|
-
|
|
327
|
-
|
|
348
|
+
|
|
349
|
+
# Changes in flight stay on the queue's byte charge until the sink returns.
|
|
350
|
+
transitions, self._transitions = self._transitions, []
|
|
351
|
+
in_flight = sum(transition.condition.charge() for transition in transitions)
|
|
352
|
+
for transition in transitions:
|
|
353
|
+
transition.entry.queued -= 1
|
|
354
|
+
if transition.entry.queued == 0:
|
|
355
|
+
self._settle(transition.entry, now)
|
|
356
|
+
due[id(transition.entry.condition)] = transition.entry.condition
|
|
357
|
+
send(transition.condition)
|
|
358
|
+
for entry in tuple(self._entries.values()):
|
|
359
|
+
if entry.queued or entry.due > now:
|
|
360
|
+
continue
|
|
361
|
+
entry.dropped = False
|
|
362
|
+
self._settle(entry, now)
|
|
363
|
+
due[id(entry.condition)] = entry.condition
|
|
364
|
+
send(entry.condition)
|
|
365
|
+
# Records in flight still count against the bounds until the sink returns: each
|
|
366
|
+
# condition's latest state against the table's, its changes against the queue's.
|
|
367
|
+
self._emitting = tuple(due.values())
|
|
328
368
|
if conditions:
|
|
329
369
|
self._emit(sink, conditions, ids)
|
|
330
370
|
finally:
|
|
331
371
|
with self._lock:
|
|
332
372
|
self._emitting = ()
|
|
373
|
+
self._transition_bytes -= in_flight
|
|
333
374
|
self._collect_lock.release()
|
|
334
375
|
|
|
376
|
+
def _settle(self, entry: _Entry, now: float) -> None:
|
|
377
|
+
"""Once a condition's last waiting change is taken: a cleared or one-shot one retires; one
|
|
378
|
+
with a dropped change stays due for its latest state; any other waits for its heartbeat."""
|
|
379
|
+
item = entry.condition
|
|
380
|
+
if entry.dropped:
|
|
381
|
+
entry.due = now
|
|
382
|
+
elif item.cleared or item.reason in {"stopped", "expired"}:
|
|
383
|
+
if self._entries.get(item.key) is entry:
|
|
384
|
+
del self._entries[item.key]
|
|
385
|
+
else:
|
|
386
|
+
entry.due = now + self._limits.repeat_seconds
|
|
387
|
+
|
|
335
388
|
def _emit(self, sink: Optional[HealthSink], conditions: list[ConditionRecord], ids: list[IdRecord]) -> None:
|
|
336
389
|
records = len(conditions) + len(ids)
|
|
337
390
|
|
|
@@ -393,5 +446,5 @@ class ObservationHealth:
|
|
|
393
446
|
if os.getpid() != self._pid:
|
|
394
447
|
return HealthStats(0, 0, 0, 0, 0, True)
|
|
395
448
|
with self._lock:
|
|
396
|
-
return HealthStats(len(self._entries), self._state_bytes(self._entries),
|
|
449
|
+
return HealthStats(len(self._entries), self._state_bytes({key: entry.condition for key, entry in self._entries.items()}),
|
|
397
450
|
self._overflow, self._emission_failures, self._sequence, self._stop.is_set())
|
|
@@ -63,7 +63,7 @@ from struct_sdk._observations.config import (
|
|
|
63
63
|
)
|
|
64
64
|
from struct_sdk._observations.identity import client_identity_headers, sdk_version
|
|
65
65
|
from struct_sdk._event_loop import _call_if_alive
|
|
66
|
-
from struct_sdk._fork_safe_http import environment_settings, fork_safe_session
|
|
66
|
+
from struct_sdk._fork_safe_http import DDTRACE_UNTRACED_HEADERS, environment_settings, fork_safe_session
|
|
67
67
|
|
|
68
68
|
logger = logging.getLogger("struct_sdk")
|
|
69
69
|
|
|
@@ -493,6 +493,7 @@ class ObservationConfigClient:
|
|
|
493
493
|
"Authorization": f"Bearer {self._api_key}",
|
|
494
494
|
"Accept-Encoding": "identity",
|
|
495
495
|
"User-Agent": _USER_AGENT,
|
|
496
|
+
**DDTRACE_UNTRACED_HEADERS,
|
|
496
497
|
**self._identity,
|
|
497
498
|
}
|
|
498
499
|
return headers
|
|
@@ -31,7 +31,7 @@ from typing import Any, Optional
|
|
|
31
31
|
|
|
32
32
|
from opentelemetry.sdk.trace import Span as SdkSpan
|
|
33
33
|
from opentelemetry.sdk.trace import SpanProcessor
|
|
34
|
-
from opentelemetry.trace import StatusCode
|
|
34
|
+
from opentelemetry.trace import NonRecordingSpan, StatusCode, set_span_in_context
|
|
35
35
|
|
|
36
36
|
from struct_sdk._genai_content import truncate_and_serialize
|
|
37
37
|
from struct_sdk.core import _contain_logged
|
|
@@ -94,7 +94,7 @@ if hasattr(os, "register_at_fork"):
|
|
|
94
94
|
def _log_record_has_event_name() -> bool:
|
|
95
95
|
import inspect
|
|
96
96
|
|
|
97
|
-
from
|
|
97
|
+
from struct_sdk._otel_logs import LogRecord
|
|
98
98
|
|
|
99
99
|
try:
|
|
100
100
|
return "event_name" in inspect.signature(LogRecord.__init__).parameters
|
|
@@ -243,7 +243,7 @@ class OperationDetailsProcessor(SpanProcessor):
|
|
|
243
243
|
"gen_ai.input.messages" in content or "gen_ai.output.messages" in content
|
|
244
244
|
):
|
|
245
245
|
return
|
|
246
|
-
from
|
|
246
|
+
from struct_sdk._otel_logs import LogRecord, SeverityNumber
|
|
247
247
|
|
|
248
248
|
span_attributes = dict(span.attributes or {})
|
|
249
249
|
attributes: dict[str, Any] = {"event.name": OPERATION_DETAILS_EVENT}
|
|
@@ -260,12 +260,9 @@ class OperationDetailsProcessor(SpanProcessor):
|
|
|
260
260
|
attributes.setdefault("error.type", _error_type(span, status))
|
|
261
261
|
attributes.update(content)
|
|
262
262
|
|
|
263
|
-
context = span.get_span_context()
|
|
264
263
|
record: dict[str, Any] = {
|
|
265
264
|
"timestamp": span.end_time,
|
|
266
|
-
"
|
|
267
|
-
"span_id": context.span_id,
|
|
268
|
-
"trace_flags": context.trace_flags,
|
|
265
|
+
"context": set_span_in_context(NonRecordingSpan(span.get_span_context())),
|
|
269
266
|
"severity_text": "DEBUG",
|
|
270
267
|
"severity_number": SeverityNumber.DEBUG,
|
|
271
268
|
"body": OPERATION_DETAILS_EVENT, # Struct's readers match the body
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""OpenTelemetry's logs API and SDK, from where the installed release keeps them.
|
|
2
|
+
|
|
3
|
+
OpenTelemetry 1.46.0 moved both out of ``opentelemetry._logs`` and
|
|
4
|
+
``opentelemetry.sdk._logs``, which it keeps as deprecated aliases, and removed
|
|
5
|
+
``LogExportResult``, ``LogExporter`` and the SDK's ``LoggingHandler``. Older
|
|
6
|
+
releases have only the private modules, and only from 1.39 ``LogRecordExportResult``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from opentelemetry import _logs as api
|
|
13
|
+
from opentelemetry.sdk._logs import LoggerProvider, LogRecordProcessor
|
|
14
|
+
from opentelemetry.sdk._logs.export import (
|
|
15
|
+
BatchLogRecordProcessor,
|
|
16
|
+
LogRecordExportResult,
|
|
17
|
+
)
|
|
18
|
+
else:
|
|
19
|
+
try:
|
|
20
|
+
from opentelemetry import logs as api
|
|
21
|
+
except ImportError:
|
|
22
|
+
from opentelemetry import _logs as api
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
from opentelemetry.sdk.logs import LoggerProvider, LogRecordProcessor
|
|
26
|
+
from opentelemetry.sdk.logs.export import (
|
|
27
|
+
BatchLogRecordProcessor,
|
|
28
|
+
LogRecordExportResult,
|
|
29
|
+
)
|
|
30
|
+
except ImportError:
|
|
31
|
+
from opentelemetry.sdk._logs import LoggerProvider, LogRecordProcessor
|
|
32
|
+
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
from opentelemetry.sdk._logs.export import LogRecordExportResult
|
|
36
|
+
except ImportError:
|
|
37
|
+
from opentelemetry.sdk._logs.export import (
|
|
38
|
+
LogExportResult as LogRecordExportResult,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
LogRecord = api.LogRecord
|
|
42
|
+
SeverityNumber = api.SeverityNumber
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"BatchLogRecordProcessor",
|
|
46
|
+
"LogRecord",
|
|
47
|
+
"LogRecordExportResult",
|
|
48
|
+
"LogRecordProcessor",
|
|
49
|
+
"LoggerProvider",
|
|
50
|
+
"SeverityNumber",
|
|
51
|
+
"api",
|
|
52
|
+
]
|
|
@@ -45,15 +45,11 @@ from typing import (
|
|
|
45
45
|
|
|
46
46
|
from opentelemetry import context as _otel_context
|
|
47
47
|
from opentelemetry import trace
|
|
48
|
-
from opentelemetry._logs import LogRecord
|
|
49
48
|
from opentelemetry.context import create_key
|
|
50
49
|
from opentelemetry.context.context import Context as _OtelContext
|
|
51
50
|
from opentelemetry.exporter.otlp.proto.http import _OTLP_HTTP_HEADERS, Compression
|
|
52
|
-
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
|
53
51
|
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
|
54
52
|
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
|
55
|
-
from opentelemetry.sdk._logs import LoggerProvider
|
|
56
|
-
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor, LogExportResult # ty: ignore[deprecated] — supported older OTel releases lack LogRecordExportResult
|
|
57
53
|
from opentelemetry.sdk.metrics import (
|
|
58
54
|
Counter,
|
|
59
55
|
Histogram,
|
|
@@ -82,9 +78,17 @@ import requests
|
|
|
82
78
|
from requests.adapters import HTTPAdapter
|
|
83
79
|
|
|
84
80
|
from struct_sdk._fork_safe_http import fork_safe_session
|
|
81
|
+
from struct_sdk._otel_logs import BatchLogRecordProcessor, LoggerProvider, LogRecord, LogRecordExportResult
|
|
85
82
|
|
|
86
83
|
if TYPE_CHECKING:
|
|
84
|
+
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
|
85
|
+
|
|
87
86
|
from struct_sdk._auto import FullAppState
|
|
87
|
+
else:
|
|
88
|
+
try:
|
|
89
|
+
from opentelemetry.exporter.otlp.proto.http.log_exporter import OTLPLogExporter
|
|
90
|
+
except ImportError:
|
|
91
|
+
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
|
88
92
|
|
|
89
93
|
logger = logging.getLogger("struct_sdk")
|
|
90
94
|
# A library must not configure logging on the host's behalf. Attach a NullHandler
|
|
@@ -539,24 +543,37 @@ def _exception_type_name(exc: BaseException) -> str:
|
|
|
539
543
|
|
|
540
544
|
|
|
541
545
|
def _record_span_error(
|
|
542
|
-
span: Any,
|
|
546
|
+
span: Any,
|
|
547
|
+
exc: BaseException,
|
|
548
|
+
sdk: Any,
|
|
549
|
+
site: str,
|
|
550
|
+
*,
|
|
551
|
+
error_type: Optional[str] = None,
|
|
552
|
+
description: Optional[str] = None,
|
|
543
553
|
) -> None:
|
|
544
554
|
"""Mark ``span`` failed by ``exc`` (SDK-PY-47): ``error.type`` and status ERROR always.
|
|
545
555
|
In span-content modes the status description is ``str(exc)`` and ``record_exception``
|
|
546
556
|
adds the message and stack trace; otherwise the description is the type name and the
|
|
547
557
|
``exception`` event carries only ``exception.type``. Each step is contained on its own,
|
|
548
558
|
BaseException included: these run on the host's error path, where a hostile ``__str__``
|
|
549
|
-
must not replace the host's exception (SDK-PY-19).
|
|
559
|
+
must not replace the host's exception (SDK-PY-19). A given ``description`` replaces the status
|
|
560
|
+
description: OpenTelemetry 1.46.0 keeps the first description an ERROR status gets."""
|
|
550
561
|
type_name = _exception_type_name(exc)
|
|
551
562
|
err_type = error_type or type_name
|
|
552
563
|
_contain_logged(lambda: span.set_attribute("error.type", err_type), site=f"{site}.error_type")
|
|
553
564
|
if _error_text_on_spans(sdk):
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
565
|
+
text = [type_name] # kept when ``str(exc)`` raises
|
|
566
|
+
if description is None:
|
|
567
|
+
_contain_logged(lambda: text.__setitem__(0, str(exc)), site=f"{site}.error_text")
|
|
568
|
+
else:
|
|
569
|
+
text[0] = description
|
|
570
|
+
_contain_logged(lambda: span.set_status(StatusCode.ERROR, text[0]), site=f"{site}.error_status")
|
|
557
571
|
_contain_logged(lambda: span.record_exception(exc), site=f"{site}.record_exception")
|
|
558
572
|
return
|
|
559
|
-
_contain_logged(
|
|
573
|
+
_contain_logged(
|
|
574
|
+
lambda: span.set_status(StatusCode.ERROR, type_name if description is None else description),
|
|
575
|
+
site=f"{site}.error_status",
|
|
576
|
+
)
|
|
560
577
|
_contain_logged(
|
|
561
578
|
lambda: span.add_event("exception", {"exception.type": _exception_type(exc)}),
|
|
562
579
|
site=f"{site}.record_exception",
|
|
@@ -625,6 +642,7 @@ _BATCH_PROCESSOR_LOGGERS = (
|
|
|
625
642
|
"opentelemetry.sdk._shared_internal",
|
|
626
643
|
"opentelemetry.sdk.trace.export",
|
|
627
644
|
"opentelemetry.sdk._logs._internal.export",
|
|
645
|
+
"opentelemetry.sdk.logs._internal.export",
|
|
628
646
|
)
|
|
629
647
|
# Where the metrics SDK reports a collection: a callback that raised, a reader
|
|
630
648
|
# shut down twice or never registered.
|
|
@@ -976,7 +994,7 @@ class _StructSpanExporter(_InStructExportScope, OTLPSpanExporter):
|
|
|
976
994
|
|
|
977
995
|
|
|
978
996
|
class _StructLogExporter(_InStructExportScope, OTLPLogExporter):
|
|
979
|
-
_FAILURE =
|
|
997
|
+
_FAILURE = LogRecordExportResult.FAILURE
|
|
980
998
|
|
|
981
999
|
def export(self, batch: Any, *args: Any, **kwargs: Any) -> Any:
|
|
982
1000
|
if _redact_patterns or any(
|
|
@@ -2580,17 +2598,21 @@ def _tool_error_status_message(result: Any) -> str:
|
|
|
2580
2598
|
|
|
2581
2599
|
|
|
2582
2600
|
# An integration whose own call a Struct execute_tool span also records (MCP:
|
|
2583
|
-
# SDK-PY-57) stores that call's outcome on the span, as
|
|
2601
|
+
# SDK-PY-57) stores that call's outcome on the span, as private fields (state
|
|
2584
2602
|
# on the object Struct created): the call's exception, or True for a failed
|
|
2585
|
-
# result. A struct.tool() scope's exit
|
|
2586
|
-
#
|
|
2603
|
+
# result, and the function that records it. A struct.tool() scope's exit runs
|
|
2604
|
+
# that function unless a different exception ends the scope, so the span's
|
|
2605
|
+
# status is set once: OpenTelemetry 1.46.0 keeps the first ERROR description.
|
|
2587
2606
|
_INNER_OUTCOME = "_struct_inner_outcome"
|
|
2607
|
+
_INNER_RECORD = "_struct_inner_record"
|
|
2588
2608
|
_NO_INNER_OUTCOME = object()
|
|
2589
2609
|
|
|
2590
2610
|
|
|
2591
|
-
def _record_inner_outcome(span: Any, outcome: Any) -> None:
|
|
2592
|
-
"""Mark ``span``'s outcome as set by an inner call: its exception, or True
|
|
2611
|
+
def _record_inner_outcome(span: Any, outcome: Any, record: Callable[[], object]) -> None:
|
|
2612
|
+
"""Mark ``span``'s outcome as set by an inner call: its exception, or True, and
|
|
2613
|
+
``record``, which the enclosing scope's exit runs to write that outcome."""
|
|
2593
2614
|
setattr(span, _INNER_OUTCOME, outcome)
|
|
2615
|
+
setattr(span, _INNER_RECORD, record)
|
|
2594
2616
|
|
|
2595
2617
|
|
|
2596
2618
|
def _inner_outcome(span: Any) -> Any:
|
|
@@ -2600,6 +2622,12 @@ def _inner_outcome(span: Any) -> Any:
|
|
|
2600
2622
|
return _NO_INNER_OUTCOME
|
|
2601
2623
|
|
|
2602
2624
|
|
|
2625
|
+
def _run_inner_record(span: Any) -> None:
|
|
2626
|
+
record = getattr(span, _INNER_RECORD, None)
|
|
2627
|
+
if record is not None:
|
|
2628
|
+
_contain_logged(record, site="tool.end_span.inner_outcome")
|
|
2629
|
+
|
|
2630
|
+
|
|
2603
2631
|
class _ToolContext:
|
|
2604
2632
|
"""Creates an ``execute_tool {name}`` span per the OTel GenAI spec."""
|
|
2605
2633
|
|
|
@@ -2702,7 +2730,7 @@ class _ToolContext:
|
|
|
2702
2730
|
if span is not None:
|
|
2703
2731
|
inner = _inner_outcome(span)
|
|
2704
2732
|
if exc_val and exc_val is inner:
|
|
2705
|
-
|
|
2733
|
+
_run_inner_record(span) # the inner call's exception: its code and status
|
|
2706
2734
|
elif exc_val:
|
|
2707
2735
|
_record_span_error(span, exc_val, self._sdk, "tool.end_span")
|
|
2708
2736
|
elif self._result_is_error:
|
|
@@ -2711,7 +2739,7 @@ class _ToolContext:
|
|
|
2711
2739
|
_safe(lambda: span.set_status(StatusCode.ERROR, self._result_error_message),
|
|
2712
2740
|
site="tool.end_span.tool_error_status")
|
|
2713
2741
|
elif inner is not _NO_INNER_OUTCOME:
|
|
2714
|
-
|
|
2742
|
+
_run_inner_record(span) # the inner call failed; its ERROR, not OK
|
|
2715
2743
|
else:
|
|
2716
2744
|
_safe(lambda: span.set_status(StatusCode.OK),
|
|
2717
2745
|
site="tool.end_span.set_ok")
|
|
@@ -27,8 +27,9 @@ Owner per span: when a Struct ``execute_tool`` span is current and has no MCP
|
|
|
27
27
|
call yet (``struct.tool()``), the MCP conventions say not to add a second span;
|
|
28
28
|
that span gets the MCP attributes and the call's outcome (``error.type``,
|
|
29
29
|
``rpc.response.status_code``, status) and is propagated instead. The outcome
|
|
30
|
-
is
|
|
31
|
-
|
|
30
|
+
is handed to the span (``core._record_inner_outcome``) and the scope's exit
|
|
31
|
+
records it, unless a different exception ends the scope: the span's status is
|
|
32
|
+
set once, as OpenTelemetry 1.46.0 keeps the first ERROR description. mcp 2.x also creates its own ``MCP send ...`` transport span (through
|
|
32
33
|
the global tracer provider); it nests under Struct's span.
|
|
33
34
|
|
|
34
35
|
Auto-applied by ``struct.init()`` when the ``mcp`` package is installed.
|
|
@@ -186,7 +187,7 @@ def _call_tool_telemetry(
|
|
|
186
187
|
) -> Generator:
|
|
187
188
|
"""Telemetry around one ``call_tool``. ``f, args, kwargs = yield`` marks the
|
|
188
189
|
host call; ``kwargs`` may carry the injected ``meta``."""
|
|
189
|
-
from struct_sdk.core import _record_inner_outcome, _safe
|
|
190
|
+
from struct_sdk.core import _record_inner_outcome, _safe, _tool_result_signals_error
|
|
190
191
|
|
|
191
192
|
# call_tool(self, name, arguments=None, ...); ``meta`` is keyword-only.
|
|
192
193
|
session = args[0] if args else None
|
|
@@ -211,8 +212,11 @@ def _call_tool_telemetry(
|
|
|
211
212
|
exc = e # ``except ... as e`` unbinds ``e`` before the closure runs
|
|
212
213
|
|
|
213
214
|
def record_failure() -> None:
|
|
214
|
-
|
|
215
|
-
|
|
215
|
+
# Read now: the caller can change the error before the scope ends.
|
|
216
|
+
code, description = _error_outcome(exc, sdk)
|
|
217
|
+
if code is not None:
|
|
218
|
+
outer.set_attribute("rpc.response.status_code", str(code))
|
|
219
|
+
_record_inner_outcome(outer, exc, lambda: _write_error(outer, exc, sdk, code, description))
|
|
216
220
|
|
|
217
221
|
# On the host's error path, and stringifying a hostile exception
|
|
218
222
|
# can raise anything: ``_contain``, not ``_safe``.
|
|
@@ -220,8 +224,9 @@ def _call_tool_telemetry(
|
|
|
220
224
|
raise
|
|
221
225
|
|
|
222
226
|
def outcome() -> None:
|
|
223
|
-
if
|
|
224
|
-
|
|
227
|
+
if _tool_result_signals_error(result):
|
|
228
|
+
message = _tool_error_message(sdk, result) # the result is the caller's to change
|
|
229
|
+
_record_inner_outcome(outer, True, lambda: _mark_tool_error(outer, message))
|
|
225
230
|
|
|
226
231
|
_safe(outcome, site="mcp.call_tool.outer_result")
|
|
227
232
|
return result # noqa: B901
|
|
@@ -345,34 +350,49 @@ def _record_result(span: trace.Span, sdk: StructSDK, result: Any) -> None:
|
|
|
345
350
|
|
|
346
351
|
def _record_tool_error(span: trace.Span, sdk: StructSDK, result: Any) -> bool:
|
|
347
352
|
"""Mark ``span`` as a tool error when ``result`` has ``isError`` set."""
|
|
348
|
-
from struct_sdk.core import
|
|
353
|
+
from struct_sdk.core import _tool_result_signals_error
|
|
349
354
|
|
|
350
355
|
if not _tool_result_signals_error(result):
|
|
351
356
|
return False
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
)
|
|
357
|
+
_mark_tool_error(span, _tool_error_message(sdk, result))
|
|
358
|
+
return True
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _tool_error_message(sdk: StructSDK, result: Any) -> str:
|
|
362
|
+
"""The status description for an error result. It is content on a span (the
|
|
363
|
+
tool's error text): only the span-content modes carry it, as for struct.tool()."""
|
|
364
|
+
from struct_sdk.core import _tool_error_status_message
|
|
365
|
+
|
|
366
|
+
return _tool_error_status_message(result) if sdk.emit_span_content else "tool returned is_error=true"
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _mark_tool_error(span: trace.Span, message: str) -> None:
|
|
359
370
|
span.set_attribute("error.type", "tool_error")
|
|
360
371
|
span.set_status(StatusCode.ERROR, message)
|
|
361
|
-
return True
|
|
362
372
|
|
|
363
373
|
|
|
364
374
|
def _record_error(span: trace.Span, exc: BaseException, sdk: Any) -> None:
|
|
365
375
|
"""A failed call: a JSON-RPC error's code as ``error.type``, else the exception's type.
|
|
366
376
|
Its text (the server's error message, the exception's message and stack trace) reaches
|
|
367
377
|
the span only in span-content modes (SDK-PY-47): it can quote the tool's arguments."""
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
378
|
+
_write_error(span, exc, sdk, *_error_outcome(exc, sdk))
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _error_outcome(exc: BaseException, sdk: Any) -> tuple[Optional[int], Optional[str]]:
|
|
382
|
+
"""A JSON-RPC error's code and status description, else (None, None)."""
|
|
383
|
+
code = getattr(getattr(exc, "error", None), "code", None)
|
|
384
|
+
if not isinstance(code, int) or isinstance(code, bool):
|
|
385
|
+
return None, None
|
|
386
|
+
message = getattr(getattr(exc, "error", None), "message", None)
|
|
387
|
+
return code, span_error_description(sdk, message, str(code)) if isinstance(message, str) else None
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _write_error(
|
|
391
|
+
span: trace.Span, exc: BaseException, sdk: Any, code: Optional[int], description: Optional[str]
|
|
392
|
+
) -> None:
|
|
393
|
+
if code is not None:
|
|
371
394
|
span.set_attribute("rpc.response.status_code", str(code))
|
|
372
|
-
|
|
373
|
-
record_span_error(span, exc, sdk, "mcp.error", error_type=str(code))
|
|
374
|
-
if isinstance(message, str):
|
|
375
|
-
span.set_status(StatusCode.ERROR, span_error_description(sdk, message, str(code)))
|
|
395
|
+
record_span_error(span, exc, sdk, "mcp.error", error_type=str(code), description=description)
|
|
376
396
|
else:
|
|
377
397
|
record_span_error(span, exc, sdk, "mcp.error")
|
|
378
398
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|