struct-sdk 0.5.11__tar.gz → 0.5.23__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.
Files changed (44) hide show
  1. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/PKG-INFO +15 -7
  2. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/README.md +12 -4
  3. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/pyproject.toml +10 -8
  4. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/_auto.py +3 -3
  5. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/_distro.py +4 -2
  6. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/_event_loop.py +1 -1
  7. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/_fork_safe_http.py +1 -0
  8. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/_genai_content.py +4 -3
  9. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/_metrics.py +29 -9
  10. struct_sdk-0.5.23/src/struct_sdk/_observations/__init__.py +4 -0
  11. {struct_sdk-0.5.11/src/struct_sdk/_dynamic_instrumentation → struct_sdk-0.5.23/src/struct_sdk/_observations}/config.py +54 -1
  12. {struct_sdk-0.5.11/src/struct_sdk/_dynamic_instrumentation → struct_sdk-0.5.23/src/struct_sdk/_observations}/export.py +74 -14
  13. struct_sdk-0.5.23/src/struct_sdk/_observations/health.py +330 -0
  14. struct_sdk-0.5.23/src/struct_sdk/_observations/identity.py +56 -0
  15. {struct_sdk-0.5.11/src/struct_sdk/_dynamic_instrumentation → struct_sdk-0.5.23/src/struct_sdk/_observations}/otlp_sender.py +9 -5
  16. struct_sdk-0.5.23/src/struct_sdk/_observations/outputs.py +825 -0
  17. {struct_sdk-0.5.11/src/struct_sdk/_dynamic_instrumentation → struct_sdk-0.5.23/src/struct_sdk/_observations}/poller.py +78 -16
  18. struct_sdk-0.5.23/src/struct_sdk/_observations/providers.py +81 -0
  19. struct_sdk-0.5.23/src/struct_sdk/_observations/runtime.py +640 -0
  20. struct_sdk-0.5.23/src/struct_sdk/_observations/self_metrics.py +79 -0
  21. {struct_sdk-0.5.11/src/struct_sdk/_dynamic_instrumentation → struct_sdk-0.5.23/src/struct_sdk/_observations}/snapshot.py +15 -6
  22. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/_pool.py +1 -1
  23. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/ag2.py +12 -7
  24. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/anthropic.py +23 -23
  25. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/autogen.py +9 -3
  26. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/claude_agent.py +2 -2
  27. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/core.py +443 -158
  28. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/crewai.py +6 -1
  29. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/gcp.py +7 -7
  30. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/google_genai.py +3 -3
  31. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/langchain.py +17 -13
  32. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/litellm.py +9 -4
  33. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/llamaindex.py +7 -3
  34. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/mcp.py +7 -4
  35. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/openai.py +13 -11
  36. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/openai_agents.py +1 -1
  37. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/pydantic_ai.py +23 -8
  38. struct_sdk-0.5.11/src/struct_sdk/_dynamic_instrumentation/__init__.py +0 -4
  39. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/.gitignore +0 -0
  40. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/LICENSE +0 -0
  41. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/__init__.py +0 -0
  42. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/_container.py +0 -0
  43. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/src/struct_sdk/_operation_details.py +0 -0
  44. {struct_sdk-0.5.11 → struct_sdk-0.5.23}/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.11
3
+ Version: 0.5.23
4
4
  Summary: Struct agent observability SDK — auto-instruments AI agent frameworks with OpenTelemetry
5
5
  Project-URL: Homepage, https://struct.ai
6
6
  Project-URL: Documentation, https://struct.ai/docs
@@ -24,7 +24,7 @@ Requires-Python: >=3.10
24
24
  Requires-Dist: opentelemetry-api>=1.45.1
25
25
  Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27.0
26
26
  Requires-Dist: opentelemetry-sdk>=1.27.0
27
- Requires-Dist: struct-sdk-native<0.2,>=0.1.0
27
+ Requires-Dist: struct-sdk-native<0.2,>=0.1.13
28
28
  Requires-Dist: wrapt>=1.16.0
29
29
  Provides-Extra: anthropic
30
30
  Requires-Dist: anthropic>=0.30.0; extra == 'anthropic'
@@ -87,10 +87,10 @@ Requires-Dist: langchain>=1.3.9; extra == 'demo'
87
87
  Requires-Dist: langgraph>=0.2.0; extra == 'demo'
88
88
  Requires-Dist: python-dotenv>=1.0.0; extra == 'demo'
89
89
  Provides-Extra: dev
90
- Requires-Dist: mypy>=1.10; extra == 'dev'
91
90
  Requires-Dist: pytest-asyncio>=1.3.0; extra == 'dev'
92
91
  Requires-Dist: pytest>=9.0.3; extra == 'dev'
93
92
  Requires-Dist: ruff>=0.5; extra == 'dev'
93
+ Requires-Dist: ty==0.0.100; extra == 'dev'
94
94
  Provides-Extra: exceptions
95
95
  Requires-Dist: opentelemetry-instrumentation-exceptions; extra == 'exceptions'
96
96
  Provides-Extra: google-genai
@@ -819,10 +819,18 @@ it is. It includes a
819
819
  `service.instance.id` so replicas stay distinguishable; an ID from
820
820
  `OTEL_RESOURCE_ATTRIBUTES` is preserved.
821
821
 
822
- In pre-fork servers (for example `gunicorn --preload`), call `struct.init()` in
823
- each worker (gunicorn's `post_fork` hook), not in the parent: forked workers
824
- would otherwise share the parent's instance id. A worker that exports after
825
- being forked from an initialized parent logs one INFO line saying so.
822
+ In pre-fork servers (for example `gunicorn --preload`), create host OpenTelemetry
823
+ providers and call `struct.init()` inside each worker (`post_fork`). Alternatively,
824
+ save options with `struct.init(..., defer_start=True)` in the master and call
825
+ `struct.start()` in each worker, after its host OTel setup. Deferred configuration
826
+ creates no telemetry resources; repeated `init()` does not activate it. Call
827
+ `struct.shutdown()` from the worker's exit hook. Preloaded agent/tool decorators
828
+ activate when the worker starts.
829
+
830
+ Forking an already-active telemetry pipeline is not a supported recovery mode:
831
+ child `init()`/`start()` leaves Observations inactive and does not repair inherited
832
+ host provider locks. Active inherited frames can retain objects until exit. The
833
+ first ordinary export from an inherited provider keeps its existing INFO diagnostic.
826
834
 
827
835
  ### Redaction
828
836
 
@@ -702,10 +702,18 @@ it is. It includes a
702
702
  `service.instance.id` so replicas stay distinguishable; an ID from
703
703
  `OTEL_RESOURCE_ATTRIBUTES` is preserved.
704
704
 
705
- In pre-fork servers (for example `gunicorn --preload`), call `struct.init()` in
706
- each worker (gunicorn's `post_fork` hook), not in the parent: forked workers
707
- would otherwise share the parent's instance id. A worker that exports after
708
- being forked from an initialized parent logs one INFO line saying so.
705
+ In pre-fork servers (for example `gunicorn --preload`), create host OpenTelemetry
706
+ providers and call `struct.init()` inside each worker (`post_fork`). Alternatively,
707
+ save options with `struct.init(..., defer_start=True)` in the master and call
708
+ `struct.start()` in each worker, after its host OTel setup. Deferred configuration
709
+ creates no telemetry resources; repeated `init()` does not activate it. Call
710
+ `struct.shutdown()` from the worker's exit hook. Preloaded agent/tool decorators
711
+ activate when the worker starts.
712
+
713
+ Forking an already-active telemetry pipeline is not a supported recovery mode:
714
+ child `init()`/`start()` leaves Observations inactive and does not repair inherited
715
+ host provider locks. Active inherited frames can retain objects until exit. The
716
+ first ordinary export from an inherited provider keeps its existing INFO diagnostic.
709
717
 
710
718
  ### Redaction
711
719
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "struct-sdk"
7
- version = "0.5.11"
7
+ version = "0.5.23"
8
8
  description = "Struct agent observability SDK — auto-instruments AI agent frameworks with OpenTelemetry"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -33,7 +33,7 @@ dependencies = [
33
33
  "wrapt>=1.16.0",
34
34
  # Native capture runtime. Always installs: platforms without a native build
35
35
  # get its pure py3-none-any wheel, which reports the capability unavailable.
36
- "struct-sdk-native>=0.1.0,<0.2",
36
+ "struct-sdk-native>=0.1.13,<0.2",
37
37
  ]
38
38
 
39
39
  [project.urls]
@@ -147,7 +147,7 @@ demo = [
147
147
  dev = [
148
148
  "pytest>=9.0.3",
149
149
  "pytest-asyncio>=1.3.0",
150
- "mypy>=1.10",
150
+ "ty==0.0.100",
151
151
  "ruff>=0.5",
152
152
  ]
153
153
 
@@ -159,7 +159,7 @@ dev = [
159
159
  test = [
160
160
  "pytest>=9.0.3",
161
161
  "pytest-asyncio>=1.3.0",
162
- "mypy>=1.10",
162
+ "ty==0.0.100",
163
163
  "ruff>=0.5",
164
164
  # Provider clients are exercised for real with HTTP mocked at the httpx
165
165
  # transport boundary.
@@ -278,10 +278,6 @@ markers = [
278
278
  "integration: real-model integration tests (requires ANTHROPIC_API_KEY / OPENAI_API_KEY; skipped in default CI)",
279
279
  ]
280
280
 
281
- [tool.mypy]
282
- [[tool.mypy.overrides]]
283
- module = ["agents", "agents.*", "anthropic", "anthropic.*", "pydantic_ai", "pydantic_ai.*", "claude_agent_sdk", "claude_agent_sdk.*", "langchain_core", "langchain_core.*", "langchain", "langchain.*", "langgraph", "langgraph.*", "openai", "openai.*", "opentelemetry.instrumentation.*", "azure.core.*", "temporalio", "temporalio.*", "requests", "requests.*", "opentelemetry.resource.*", "ddtrace", "ddtrace.*", "wrapt", "wrapt.*", "mcp", "mcp.*", "google.genai", "google.genai.*", "google.adk", "google.adk.*", "litellm", "litellm.*", "llama_index", "llama_index.*", "crewai", "crewai.*", "autogen_core", "autogen_core.*", "autogen_ext", "autogen_ext.*", "autogen_agentchat", "autogen_agentchat.*", "autogen", "autogen.*", "ag2", "ag2.*", "grpc", "grpc.*"]
284
- ignore_missing_imports = true
285
281
 
286
282
  [tool.hatch.build.targets.wheel]
287
283
  packages = ["src/struct_sdk"]
@@ -293,3 +289,9 @@ include = [
293
289
  "LICENSE",
294
290
  "pyproject.toml",
295
291
  ]
292
+
293
+ [tool.ty.environment]
294
+ python-version = "3.10"
295
+
296
+ [tool.ty.analysis]
297
+ allowed-unresolved-imports = ["ag2.**", "agents.**", "anthropic.**", "autogen.**", "autogen_agentchat.**", "autogen_core.**", "autogen_ext.**", "azure.core.**", "claude_agent_sdk.**", "crewai.**", "ddtrace.**", "google.adk.**", "google.genai.**", "grpc.**", "langchain.**", "langchain_core.**", "langgraph.**", "litellm.**", "llama_index.**", "mcp.**", "openai.**", "opentelemetry.instrumentation.**", "opentelemetry.resource.**", "pydantic_ai.**", "requests.**", "temporalio.**", "wrapt.**"]
@@ -585,7 +585,7 @@ def _quiet_aws_instrumentor(instrumentor: Any) -> None:
585
585
  instrumentor.__dict__.pop("uninstrument", None)
586
586
  # contrib's uninstrument() unwraps the outermost request hook, and
587
587
  # this instrumentor no longer has one: put back what was there.
588
- Endpoint.prepare_request = kept
588
+ setattr(Endpoint, "prepare_request", kept)
589
589
 
590
590
  instrumentor.uninstrument = uninstrument_keeping_request_hooks
591
591
 
@@ -926,7 +926,7 @@ class _ExportPathFilteringLogProcessor(LogRecordProcessor):
926
926
  # opentelemetry-sdk releases before on_emit call emit(log_data).
927
927
  def emit(self, log_data: Any) -> None:
928
928
  if not self._skip(log_data):
929
- _safe(lambda: self._inner.emit(log_data), site="auto.host_logs.emit") # type: ignore[attr-defined]
929
+ _safe(lambda: self._inner.emit(log_data), site="auto.host_logs.emit") # type: ignore[attr-defined] # ty: ignore[missing-attribute]
930
930
 
931
931
  def shutdown(self) -> None:
932
932
  _shut_down_within(self._inner, self._budget_seconds)
@@ -970,7 +970,7 @@ def _keep_through_logging_config(handler: logging.Handler) -> Callable[[], None]
970
970
  def configure_without_bridge(*args: Any, **kwargs: Any) -> Any:
971
971
  # The same reentrant lock basicConfig/dictConfig use: removing the
972
972
  # bridge, configuring, and restoring it are one configuration step.
973
- with logging._lock: # type: ignore[attr-defined] # CPython's configuration RLock.
973
+ with logging._lock: # type: ignore[attr-defined] # CPython's configuration RLock. # ty: ignore[missing-attribute]
974
974
  root = logging.getLogger()
975
975
  hidden = handler in root.handlers
976
976
  if hidden:
@@ -14,8 +14,10 @@ import os
14
14
  from importlib.metadata import EntryPoint
15
15
  from typing import Any, Optional
16
16
 
17
- # distro.py is marked "# type: ignore" upstream, so mypy sees no attributes.
18
- from opentelemetry.instrumentation.distro import BaseDistro # type: ignore[attr-defined]
17
+ # distro.py is marked with a file-wide typing suppression upstream, so mypy sees no attributes.
18
+ from opentelemetry.instrumentation.distro import (
19
+ BaseDistro, # type: ignore[attr-defined]
20
+ )
19
21
 
20
22
  from struct_sdk.core import DEFAULT_ENDPOINT
21
23
 
@@ -41,7 +41,7 @@ PROBE_INTERVAL_SECONDS = 1.0
41
41
  DELAY_METRIC = "struct.asyncio.eventloop.delay.max"
42
42
 
43
43
 
44
- def _call_if_alive(method: "weakref.WeakMethod[Callable[[], None]]") -> None:
44
+ def _call_if_alive(method: Callable[[], Optional[Callable[[], None]]]) -> None:
45
45
  bound = method()
46
46
  if bound is not None:
47
47
  bound()
@@ -22,6 +22,7 @@ import threading
22
22
  import weakref
23
23
 
24
24
  import requests
25
+ import requests.cookies
25
26
 
26
27
  logger = logging.getLogger("struct_sdk")
27
28
 
@@ -28,8 +28,9 @@ import contextlib
28
28
  import json
29
29
  import logging
30
30
  import sys
31
+ from collections.abc import Generator
31
32
  from contextvars import ContextVar, Token
32
- from typing import Any, Callable, Iterator, Optional
33
+ from typing import Any, Callable, Mapping, Optional, cast
33
34
  from urllib.parse import urlparse
34
35
 
35
36
  from opentelemetry import trace
@@ -210,7 +211,7 @@ def _contain(fn: Any, site: str) -> None:
210
211
  def guarded_client_span(
211
212
  tracer: Any, span_name: str, *, keep_open: Optional[Callable[[], bool]] = None,
212
213
  end_on_success: bool = True,
213
- ) -> Iterator[Any]:
214
+ ) -> Generator[Any, None, None]:
214
215
  """Explicit CLIENT span with ``_safe``-guarded start and end.
215
216
 
216
217
  ``keep_open`` hands the span's END to another owner: when it returns True at
@@ -545,7 +546,7 @@ def propagate_user_prompt_to_parent(last_user_parts: Optional[list[dict[str, Any
545
546
  # Only set once — the first chat call within an invoke_agent scope wins.
546
547
  existing = None
547
548
  if hasattr(agent_span, "attributes"):
548
- existing = agent_span.attributes.get("gen_ai.input.messages") # type: ignore[union-attr]
549
+ existing = cast("Mapping[str, Any]", agent_span.attributes).get("gen_ai.input.messages")
549
550
  if existing:
550
551
  return
551
552
  agent_span.set_attribute(
@@ -27,7 +27,14 @@ from opentelemetry.sdk.trace import SpanProcessor
27
27
  from struct_sdk._container import ContainerMetrics, ContainerReader
28
28
  from struct_sdk._event_loop import EventLoopDelay
29
29
  from struct_sdk._pool import PoolMetrics
30
- from struct_sdk.core import DEFAULT_ENDPOINT, _contain_logged, _metric_reader, _new_metric_reader, _struct_export_scope
30
+ from struct_sdk.core import (
31
+ DEFAULT_ENDPOINT,
32
+ _contain_logged,
33
+ _metric_reader,
34
+ _new_metric_reader,
35
+ _StructMetricReader,
36
+ _struct_export_scope,
37
+ )
31
38
 
32
39
  logger = logging.getLogger("struct_sdk.metrics")
33
40
 
@@ -95,12 +102,16 @@ def provider_readers(provider: MeterProvider) -> list[Any]:
95
102
  return readers
96
103
 
97
104
 
98
- def attach_host_reader(host: Any, endpoint: str, headers: dict[str, str]) -> Optional[MetricReader]:
105
+ def attach_host_reader(host: Any, endpoint: str, headers: dict[str, str], *, restart_after_fork: bool = True) -> Optional[MetricReader]:
99
106
  """Add a Struct reader to the host's SDK ``MeterProvider``; ``None`` when none was added."""
100
107
  if not isinstance(host, MeterProvider):
101
108
  return None
102
109
  metrics_endpoint = f"{endpoint.rstrip('/')}/v1/metrics"
103
- if any(exports_to_struct(reader, metrics_endpoint) for reader in provider_readers(host)):
110
+ if any(
111
+ exports_to_struct(reader, metrics_endpoint)
112
+ and not (isinstance(reader, _StructMetricReader) and reader._abandoned)
113
+ for reader in provider_readers(host)
114
+ ):
104
115
  logger.debug("The host's meter provider already exports to Struct; adding no reader")
105
116
  return None
106
117
  add = getattr(host, "add_metric_reader", None)
@@ -111,7 +122,7 @@ def attach_host_reader(host: Any, endpoint: str, headers: dict[str, str]) -> Opt
111
122
  "Pass struct_sdk.metric_reader(ingest_key=...) in the provider's metric_readers to send them."
112
123
  )
113
124
  return None
114
- with _new_metric_reader(endpoint, headers) as reader:
125
+ with _new_metric_reader(endpoint, headers, restart_after_fork=restart_after_fork) as reader:
115
126
  add(reader)
116
127
  return reader
117
128
 
@@ -158,12 +169,21 @@ def shut_down_once(provider: MeterProvider, timeout_millis: int) -> None:
158
169
  OpenTelemetry's "shutdown can only be called once" warning then moves to
159
170
  DEBUG under ``struct_sdk``."""
160
171
  with _struct_export_scope():
161
- provider.shutdown(timeout_millis=timeout_millis)
162
-
163
-
164
- def struct_meter_provider(resource: Resource, endpoint: str, headers: dict[str, str]) -> MeterProvider:
172
+ try:
173
+ provider.shutdown(timeout_millis=timeout_millis)
174
+ finally:
175
+ # OTel consumes its provider's one-shot shutdown before checking the
176
+ # deadline; at zero budget it never calls the readers. Explicitly stop
177
+ # any remaining Struct reader without a final collection/export.
178
+ for reader in provider_readers(provider):
179
+ if isinstance(reader, _StructMetricReader) and not reader._shutdown:
180
+ reader._abandoned = True
181
+ _contain_logged(lambda: reader.shutdown(timeout_millis=0), site="metrics.private_reader.abandon")
182
+
183
+
184
+ def struct_meter_provider(resource: Resource, endpoint: str, headers: dict[str, str], *, restart_after_fork: bool = True) -> MeterProvider:
165
185
  """The provider for Struct's own instruments, in either mode; never installed globally."""
166
- with _new_metric_reader(endpoint, headers) as reader:
186
+ with _new_metric_reader(endpoint, headers, restart_after_fork=restart_after_fork) as reader:
167
187
  return MeterProvider(
168
188
  resource=resource,
169
189
  metric_readers=[reader],
@@ -0,0 +1,4 @@
1
+ """Observation configuration received from the Struct API.
2
+
3
+ ``struct.init()`` starts the client in a later change.
4
+ """
@@ -21,7 +21,7 @@ import time
21
21
  import zlib
22
22
  from dataclasses import dataclass
23
23
  from datetime import datetime
24
- from typing import Any, Callable, Iterator, Mapping, Optional
24
+ from typing import Any, Callable, Iterator, Mapping, Optional, Union
25
25
 
26
26
  FORMAT = "struct-config/1"
27
27
  DEFINITION_FORMAT = "sil-definition/1"
@@ -236,6 +236,55 @@ def _artifact_ref(value: Any) -> ArtifactRef:
236
236
  return ArtifactRef(revision=_count(record, "revision"), artifact_id=artifact_id)
237
237
 
238
238
 
239
+ @dataclass(frozen=True)
240
+ class Disabled:
241
+ """An authenticated policy withdrawal (STR-7297): this client may hold no configuration.
242
+
243
+ It arrives as a ``struct-config/1`` descriptor of kind ``disabled`` on a 200, so it can only come
244
+ from the endpoint the key authenticated with. Failures of any status never produce one.
245
+ """
246
+
247
+ tenant_id: str
248
+ code: str
249
+ message: str
250
+ server_now: datetime
251
+
252
+
253
+ DISABLED_KIND = "disabled"
254
+ _MAX_DISABLED_MESSAGE = 512
255
+
256
+
257
+ def parse_config_response(
258
+ raw: bytes, *, service: str, environment: str, limits: ConfigLimits
259
+ ) -> Union[Descriptor, Disabled]:
260
+ """Parse a 200 from the config route: a package descriptor, or a policy withdrawal."""
261
+ record = _strict_json(raw)
262
+ if not isinstance(record, dict):
263
+ raise _invalid("invalid_descriptor")
264
+ if record.get("format") != FORMAT:
265
+ raise _invalid("unsupported_format")
266
+ if record.get("kind") == DISABLED_KIND:
267
+ return _parse_disabled(record, service=service, environment=environment)
268
+ return _parse_descriptor(record, service=service, environment=environment, limits=limits)
269
+
270
+
271
+ def _parse_disabled(record: dict[str, Any], *, service: str, environment: str) -> Disabled:
272
+ try:
273
+ scope_record = _object(record.get("scope"))
274
+ reason = _object(record.get("reason"))
275
+ disabled = Disabled(
276
+ tenant_id=_text(scope_record, "tenantId"),
277
+ code=_text(reason, "code"),
278
+ message=_text(reason, "message")[:_MAX_DISABLED_MESSAGE],
279
+ server_now=_time(record.get("serverNow")),
280
+ )
281
+ if _text(scope_record, "service") != service or _text(scope_record, "environment") != environment:
282
+ raise _invalid("wrong_scope")
283
+ except ConfigRejected as exc:
284
+ raise _invalid(exc.code if exc.code == "wrong_scope" else "invalid_descriptor") from exc
285
+ return disabled
286
+
287
+
239
288
  def parse_descriptor(raw: bytes, *, service: str, environment: str, limits: ConfigLimits) -> Descriptor:
240
289
  """Check a descriptor on its own, before any payload is downloaded."""
241
290
  record = _strict_json(raw)
@@ -243,6 +292,10 @@ def parse_descriptor(raw: bytes, *, service: str, environment: str, limits: Conf
243
292
  raise _invalid("invalid_descriptor")
244
293
  if record.get("format") != FORMAT:
245
294
  raise _invalid("unsupported_format")
295
+ return _parse_descriptor(record, service=service, environment=environment, limits=limits)
296
+
297
+
298
+ def _parse_descriptor(record: dict[str, Any], *, service: str, environment: str, limits: ConfigLimits) -> Descriptor:
246
299
  try:
247
300
  scope_record = _object(record.get("scope"))
248
301
  scope = ConfigScope(
@@ -20,8 +20,8 @@ Nothing here blocks or raises into the host. The hot path takes one short lock a
20
20
  The lock is reentrant because garbage collection can run an instrumented ``__del__`` on a thread
21
21
  already inside it. Only ``struct.capture`` records enter, so ordinary telemetry is unchanged.
22
22
 
23
- Nothing attaches these processors yet. ``struct.init()`` wiring does that in a later change, and it
24
- must also keep ``struct.capture`` records out of the ordinary Struct processors, or they'd export twice.
23
+ Public initialization attaches these processors through ``ObservationRuntime``; ordinary Struct
24
+ processors exclude capture records to prevent duplicate export.
25
25
  """
26
26
 
27
27
  from __future__ import annotations
@@ -36,12 +36,15 @@ from dataclasses import dataclass
36
36
  from typing import Any, Callable, Optional, Protocol, Sequence
37
37
 
38
38
  from opentelemetry import context as otel_context
39
- from opentelemetry.context import _SUPPRESS_HTTP_INSTRUMENTATION_KEY, _SUPPRESS_INSTRUMENTATION_KEY
39
+ from opentelemetry.context import (
40
+ _SUPPRESS_HTTP_INSTRUMENTATION_KEY,
41
+ _SUPPRESS_INSTRUMENTATION_KEY,
42
+ )
40
43
  from opentelemetry.sdk._logs import LogRecordProcessor, ReadWriteLogRecord
41
44
  from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor
42
45
 
43
46
  from struct_sdk import core
44
- from struct_sdk._dynamic_instrumentation.otlp_sender import (
47
+ from struct_sdk._observations.otlp_sender import (
45
48
  SIGNAL_LOGS,
46
49
  SIGNAL_TRACES,
47
50
  OtlpHttpSender,
@@ -49,11 +52,18 @@ from struct_sdk._dynamic_instrumentation.otlp_sender import (
49
52
  SendStatus,
50
53
  debug,
51
54
  )
52
- from struct_sdk._dynamic_instrumentation.snapshot import CAPTURE_SCOPE_NAME, is_capture_scope, log_parts
53
- from struct_sdk._dynamic_instrumentation.snapshot import FieldLimits, LogSnapshot, OverBudget, Snapshot, SpanSnapshot
55
+ from struct_sdk._observations.snapshot import (
56
+ CAPTURE_SCOPE_NAME,
57
+ FieldLimits,
58
+ LogSnapshot,
59
+ OverBudget,
60
+ Snapshot,
61
+ SpanSnapshot,
62
+ is_capture_scope,
63
+ log_parts,
64
+ )
54
65
  from struct_sdk._event_loop import _call_if_alive
55
66
 
56
-
57
67
  # Dynamic records are recognized by their instrumentation scope.
58
68
  CAPTURE_SCOPE = CAPTURE_SCOPE_NAME
59
69
 
@@ -136,6 +146,9 @@ class BranchStats:
136
146
  outcomes: dict[tuple[str, str], int]
137
147
  # (signal, note) -> records. These records are also counted in ``outcomes``.
138
148
  notes: dict[tuple[str, str], int]
149
+ # Standard SDK-metric boundaries: processor handoff/refusal and final export operation.
150
+ processed: dict[tuple[str, str], int]
151
+ exported: dict[tuple[str, str], int]
139
152
 
140
153
 
141
154
  def _usable(limits: BranchLimits) -> BranchLimits:
@@ -192,7 +205,7 @@ class Sender(Protocol):
192
205
 
193
206
  class _Batch:
194
207
  # ``maybe_delivered``: an attempt is on the wire now, or an earlier one may have reached ingest.
195
- __slots__ = ("signal", "records", "charge", "first_seq", "finished", "maybe_delivered")
208
+ __slots__ = ("signal", "records", "charge", "first_seq", "finished", "maybe_delivered", "export_started", "last_error_type")
196
209
 
197
210
  def __init__(self, signal: str, records: list[Snapshot]) -> None:
198
211
  self.signal = signal
@@ -201,6 +214,34 @@ class _Batch:
201
214
  self.first_seq = records[0].seq
202
215
  self.finished = False
203
216
  self.maybe_delivered = False
217
+ self.export_started = False
218
+ self.last_error_type = ""
219
+
220
+
221
+ _TRANSPORT_METRIC_ERRORS = {
222
+ **{name: f"requests.exceptions.{name}" for name in (
223
+ "ReadTimeout", "ConnectTimeout", "Timeout", "ConnectionError", "ProxyError",
224
+ "SSLError", "ChunkedEncodingError", "RequestException",
225
+ )},
226
+ **{name: f"urllib3.exceptions.{name}" for name in (
227
+ "ReadTimeoutError", "ConnectTimeoutError", "NewConnectionError", "ProtocolError", "MaxRetryError",
228
+ )},
229
+ **{name: f"builtins.{name}" for name in (
230
+ "TimeoutError", "ConnectionRefusedError", "ConnectionResetError", "OSError",
231
+ )},
232
+ }
233
+
234
+
235
+ def _export_error_type(detail: str) -> str:
236
+ """Bounded metric causes, never arbitrary diagnostics or exception messages."""
237
+ if len(detail) == 8 and detail.startswith("http_") and detail[5:].isascii() and detail[5:].isdigit():
238
+ if 100 <= int(detail[5:]) <= 599:
239
+ return detail[5:]
240
+ if detail.startswith("invalid_request_"):
241
+ return "invalid_request"
242
+ if detail == "closed":
243
+ return "already_shutdown"
244
+ return _TRANSPORT_METRIC_ERRORS.get(detail, "other" if detail else "")
204
245
 
205
246
 
206
247
  class BoundedExportBranch:
@@ -245,6 +286,8 @@ class BoundedExportBranch:
245
286
  self._notes = {
246
287
  (s, n): 0 for s in signals for n in (NOTE_ACCEPTANCE_UNKNOWN, NOTE_REJECTION_UNKNOWN, NOTE_TRUNCATED)
247
288
  }
289
+ self._processed = {(s, o): 0 for s in signals for o in ADMISSION_OUTCOMES | TERMINAL_OUTCOMES | {""}}
290
+ self._exported = {(s, o): 0 for s in signals for o in TERMINAL_OUTCOMES}
248
291
  self._workers: list[threading.Thread] = []
249
292
  self._starting = 0
250
293
  self._detaching = False
@@ -412,7 +455,7 @@ class BoundedExportBranch:
412
455
  try:
413
456
  self._starting = before + 1
414
457
  thread = threading.Thread(
415
- target=self._run, name=f"struct-sdk-dynamic-export-{len(self._workers)}", daemon=True
458
+ target=self._run, name=f"struct-sdk-observation-export-{len(self._workers)}", daemon=True
416
459
  )
417
460
  # Listed before it starts: a signal can interrupt start() after the OS thread exists
418
461
  # but before Python knows it, and that thread is ours and counts toward the limit
@@ -423,7 +466,7 @@ class BoundedExportBranch:
423
466
  except BaseException: # noqa: BLE001 - interpreter exit, or a signal while start() waits
424
467
  if not self._worker_failure_logged:
425
468
  self._worker_failure_logged = True
426
- debug("Struct SDK could not start a dynamic export worker", exc_info=True)
469
+ debug("Struct SDK could not start an observation export worker", exc_info=True)
427
470
  return
428
471
  finally:
429
472
  self._starting = before
@@ -459,7 +502,7 @@ class BoundedExportBranch:
459
502
  if batch is None:
460
503
  return
461
504
  except Exception: # noqa: BLE001 - this thread must outlive any fault
462
- debug("Struct SDK dynamic export worker fault", exc_info=True)
505
+ debug("Struct SDK observation export worker fault", exc_info=True)
463
506
  time.sleep(0.1)
464
507
  continue
465
508
  self._deliver(batch)
@@ -551,6 +594,11 @@ class BoundedExportBranch:
551
594
  def _deliver(self, batch: _Batch) -> None:
552
595
  token = None
553
596
  try:
597
+ with self._lock:
598
+ if batch.finished:
599
+ return
600
+ batch.export_started = True
601
+ self._processed[batch.signal, ""] += len(batch.records)
554
602
  scope = otel_context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True)
555
603
  scope = otel_context.set_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY, True, scope)
556
604
  token = otel_context.attach(scope)
@@ -561,7 +609,7 @@ class BoundedExportBranch:
561
609
  except BaseException: # noqa: BLE001 - every admitted record still gets its one outcome
562
610
  # BaseException too: a host object can raise KeyboardInterrupt while it's encoded, and
563
611
  # this worker must live on with its batch settled. An earlier attempt may have delivered.
564
- debug("Struct SDK dynamic export fault", exc_info=True)
612
+ debug("Struct SDK observation export fault", exc_info=True)
565
613
  self._finish(batch, OUTCOME_INTERNAL_ERROR, maybe_delivered=batch.maybe_delivered)
566
614
  finally:
567
615
  if token is not None:
@@ -625,6 +673,7 @@ class BoundedExportBranch:
625
673
  batch.maybe_delivered = True
626
674
  result = self._sender.send(batch.signal, body, timeout)
627
675
  attempt += 1
676
+ batch.last_error_type = _export_error_type(result.detail)
628
677
  maybe_delivered = maybe_delivered or result.maybe_delivered
629
678
  batch.maybe_delivered = maybe_delivered
630
679
  if result.status is SendStatus.ACCEPTED:
@@ -689,8 +738,10 @@ class BoundedExportBranch:
689
738
  refused = max(0, min(result.rejected_records, len(batch.records)))
690
739
  if refused:
691
740
  self._count(batch.signal, OUTCOME_REJECTED, refused)
741
+ self._exported[batch.signal, OUTCOME_REJECTED] += refused
692
742
  if len(batch.records) - refused:
693
743
  self._count(batch.signal, OUTCOME_ACCEPTED, len(batch.records) - refused)
744
+ self._exported[batch.signal, OUTCOME_ACCEPTED] += len(batch.records) - refused
694
745
  finally:
695
746
  self._release(batch)
696
747
 
@@ -705,6 +756,10 @@ class BoundedExportBranch:
705
756
  key, records = (batch.signal, NOTE_ACCEPTANCE_UNKNOWN), len(batch.records)
706
757
  self._notes[key] += records
707
758
  self._count(batch.signal, outcome, len(batch.records))
759
+ counters = self._exported if batch.export_started else self._processed
760
+ cause = batch.last_error_type if batch.export_started and outcome in {OUTCOME_RETRY_EXHAUSTED, OUTCOME_REJECTED} else ""
761
+ key = (batch.signal, cause or outcome)
762
+ counters[key] = counters.get(key, 0) + len(batch.records)
708
763
  finally:
709
764
  self._release(batch)
710
765
 
@@ -734,6 +789,7 @@ class BoundedExportBranch:
734
789
  self._outstanding_records -= dropped
735
790
  self._outstanding_bytes -= charge
736
791
  self._count(batch.signal, OUTCOME_ENCODE_FAILED, dropped)
792
+ self._exported[batch.signal, OUTCOME_ENCODE_FAILED] += dropped
737
793
  self._cond.notify_all()
738
794
 
739
795
  # --- Lifecycle and reporting. ---
@@ -756,7 +812,7 @@ class BoundedExportBranch:
756
812
  self._cond.wait(_bounded(remaining))
757
813
  return True
758
814
  except Exception: # noqa: BLE001 - nothing may reach the host from here
759
- debug("Struct SDK dynamic export flush fault", exc_info=True)
815
+ debug("Struct SDK observation export flush fault", exc_info=True)
760
816
  return False
761
817
 
762
818
  def _oldest_unfinished_seq(self) -> float:
@@ -793,7 +849,7 @@ class BoundedExportBranch:
793
849
  self._abandon_everything()
794
850
  self._sender.close()
795
851
  except Exception: # noqa: BLE001 - nothing may reach the host from here
796
- debug("Struct SDK dynamic export shutdown fault", exc_info=True)
852
+ debug("Struct SDK observation export shutdown fault", exc_info=True)
797
853
 
798
854
  def _abandon_everything(self) -> None:
799
855
  if self._detaching:
@@ -808,6 +864,7 @@ class BoundedExportBranch:
808
864
  self._outstanding_records -= held
809
865
  self._outstanding_bytes -= charge
810
866
  self._count(signal, OUTCOME_SHUTDOWN_ABANDONED, held)
867
+ self._processed[signal, OUTCOME_SHUTDOWN_ABANDONED] += held
811
868
  for batch in list(self._in_flight):
812
869
  self._finish(batch, OUTCOME_SHUTDOWN_ABANDONED, maybe_delivered=batch.maybe_delivered)
813
870
  self._cond.notify_all()
@@ -821,6 +878,9 @@ class BoundedExportBranch:
821
878
  in_flight_batches=len(self._in_flight),
822
879
  outcomes={key: n for key, n in self._outcomes.items() if n},
823
880
  notes={key: n for key, n in self._notes.items() if n},
881
+ processed={key: n for key in self._processed
882
+ if (n := self._outcomes[key] if key[1] in ADMISSION_OUTCOMES else self._processed[key])},
883
+ exported={key: n for key, n in self._exported.items() if n},
824
884
  )
825
885
 
826
886