struct-sdk 0.5.17__tar.gz → 0.5.25__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 (43) hide show
  1. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/PKG-INFO +14 -6
  2. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/README.md +12 -4
  3. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/pyproject.toml +2 -2
  4. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_metrics.py +22 -8
  5. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_observations/config.py +54 -1
  6. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_observations/export.py +2 -2
  7. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_observations/health.py +3 -0
  8. struct_sdk-0.5.25/src/struct_sdk/_observations/identity.py +56 -0
  9. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_observations/outputs.py +98 -22
  10. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_observations/poller.py +57 -5
  11. struct_sdk-0.5.25/src/struct_sdk/_observations/runtime.py +640 -0
  12. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/core.py +424 -146
  13. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/.gitignore +0 -0
  14. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/LICENSE +0 -0
  15. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/__init__.py +0 -0
  16. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_auto.py +0 -0
  17. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_container.py +0 -0
  18. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_distro.py +0 -0
  19. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_event_loop.py +0 -0
  20. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_fork_safe_http.py +0 -0
  21. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_genai_content.py +0 -0
  22. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_observations/__init__.py +0 -0
  23. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_observations/otlp_sender.py +0 -0
  24. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_observations/providers.py +0 -0
  25. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_observations/self_metrics.py +0 -0
  26. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_observations/snapshot.py +0 -0
  27. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_operation_details.py +0 -0
  28. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/_pool.py +0 -0
  29. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/ag2.py +0 -0
  30. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/anthropic.py +0 -0
  31. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/autogen.py +0 -0
  32. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/claude_agent.py +0 -0
  33. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/crewai.py +0 -0
  34. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/gcp.py +0 -0
  35. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/google_genai.py +0 -0
  36. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/langchain.py +0 -0
  37. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/litellm.py +0 -0
  38. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/llamaindex.py +0 -0
  39. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/mcp.py +0 -0
  40. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/openai.py +0 -0
  41. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/openai_agents.py +0 -0
  42. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/src/struct_sdk/pydantic_ai.py +0 -0
  43. {struct_sdk-0.5.17 → struct_sdk-0.5.25}/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.17
3
+ Version: 0.5.25
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'
@@ -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.17"
7
+ version = "0.5.25"
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]
@@ -32,6 +32,7 @@ from struct_sdk.core import (
32
32
  _contain_logged,
33
33
  _metric_reader,
34
34
  _new_metric_reader,
35
+ _StructMetricReader,
35
36
  _struct_export_scope,
36
37
  )
37
38
 
@@ -101,12 +102,16 @@ def provider_readers(provider: MeterProvider) -> list[Any]:
101
102
  return readers
102
103
 
103
104
 
104
- 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]:
105
106
  """Add a Struct reader to the host's SDK ``MeterProvider``; ``None`` when none was added."""
106
107
  if not isinstance(host, MeterProvider):
107
108
  return None
108
109
  metrics_endpoint = f"{endpoint.rstrip('/')}/v1/metrics"
109
- 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
+ ):
110
115
  logger.debug("The host's meter provider already exports to Struct; adding no reader")
111
116
  return None
112
117
  add = getattr(host, "add_metric_reader", None)
@@ -117,7 +122,7 @@ def attach_host_reader(host: Any, endpoint: str, headers: dict[str, str]) -> Opt
117
122
  "Pass struct_sdk.metric_reader(ingest_key=...) in the provider's metric_readers to send them."
118
123
  )
119
124
  return None
120
- with _new_metric_reader(endpoint, headers) as reader:
125
+ with _new_metric_reader(endpoint, headers, restart_after_fork=restart_after_fork) as reader:
121
126
  add(reader)
122
127
  return reader
123
128
 
@@ -164,12 +169,21 @@ def shut_down_once(provider: MeterProvider, timeout_millis: int) -> None:
164
169
  OpenTelemetry's "shutdown can only be called once" warning then moves to
165
170
  DEBUG under ``struct_sdk``."""
166
171
  with _struct_export_scope():
167
- provider.shutdown(timeout_millis=timeout_millis)
168
-
169
-
170
- 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:
171
185
  """The provider for Struct's own instruments, in either mode; never installed globally."""
172
- with _new_metric_reader(endpoint, headers) as reader:
186
+ with _new_metric_reader(endpoint, headers, restart_after_fork=restart_after_fork) as reader:
173
187
  return MeterProvider(
174
188
  resource=resource,
175
189
  metric_readers=[reader],
@@ -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
@@ -10,6 +10,7 @@ import os
10
10
  import sys
11
11
  import threading
12
12
  import time
13
+ from uuid import uuid4
13
14
  from dataclasses import dataclass, replace
14
15
  from itertools import islice
15
16
  from typing import Any, Callable, Mapping, Optional, Sequence
@@ -100,6 +101,7 @@ class ObservationHealth:
100
101
  clock: Callable[[], float] = time.monotonic,
101
102
  ) -> None:
102
103
  self._pid = os.getpid()
104
+ self._lifetime_id = uuid4().hex
103
105
  self._logger = provider.get_logger("struct.capture")
104
106
  self._limits = HealthLimits(
105
107
  max(1, min(128, limits.max_conditions)), max(1024, min(256 * 1024, limits.max_bytes)),
@@ -270,6 +272,7 @@ class ObservationHealth:
270
272
  def _emit(self, item: _Condition, sequence: int, desired: Optional[int], received: Optional[int], generation: int, overflow: int) -> None:
271
273
  def emit() -> None:
272
274
  attrs: dict[str, Any] = {
275
+ "lifetime_id": self._lifetime_id,
273
276
  "condition_key": item.key, "process_sequence": sequence, "installation_generation": generation,
274
277
  "phase": item.phase, "reason": "recovered" if item.cleared else item.reason, "code": item.code,
275
278
  "condition_state": "recovered" if item.cleared else "active", "affected_count": item.affected,
@@ -0,0 +1,56 @@
1
+ """What this SDK tells the config route about itself (STR-7297).
2
+
3
+ The server's approved-client policy reads these on every config and artifact request. Capability
4
+ tokens name what this code implements; a version number never stands in for them.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from importlib.metadata import PackageNotFoundError, version
10
+
11
+
12
+ CLIENT_HEADER = "X-Struct-Client"
13
+ NATIVE_HEADER = "X-Struct-Native"
14
+ CAPABILITIES_HEADER = "X-Struct-Capabilities"
15
+
16
+ CLIENT_NAME = "struct-sdk-python"
17
+ NATIVE_NAME = "struct-sdk-native"
18
+ # Protocols, artifact formats and features this poller and runtime implement.
19
+ CAPABILITIES = (
20
+ "config:struct-config/1",
21
+ "artifact:sil-definition/1",
22
+ "package:full",
23
+ "package:changes",
24
+ "capture:ordinary-functions",
25
+ "remote-disable",
26
+ )
27
+ # Sent only when the native module loaded and this interpreter can capture.
28
+ NATIVE_CAPABILITY = "native:cpython312"
29
+
30
+
31
+ def sdk_version() -> str:
32
+ try:
33
+ return version("struct-sdk")
34
+ except PackageNotFoundError:
35
+ return "unknown"
36
+
37
+
38
+ def client_identity_headers() -> dict[str, str]:
39
+ """Never raises: a missing native package simply reports no native header or capability."""
40
+ headers = {CLIENT_HEADER: f"{CLIENT_NAME}/{sdk_version()}"}
41
+ capabilities = list(CAPABILITIES)
42
+ try:
43
+ from struct_sdk_native import capability_report
44
+
45
+ report = capability_report()
46
+ except Exception: # noqa: BLE001 - identity must not fail a poll, and neither may a host log handler
47
+ report = None
48
+ if report is not None and report.package_version:
49
+ native = f"{NATIVE_NAME}/{report.package_version}"
50
+ if report.native_version:
51
+ native += f"; module={report.native_version}"
52
+ headers[NATIVE_HEADER] = native
53
+ if report.available:
54
+ capabilities.append(NATIVE_CAPABILITY)
55
+ headers[CAPABILITIES_HEADER] = " ".join(capabilities)
56
+ return headers
@@ -1,14 +1,15 @@
1
1
  """SIL runtime outputs -> standard OTel APIs, after native admission and safe reads.
2
2
 
3
3
  Internal S2 interface: bind verified sil-definition/1 artifacts and selected code before
4
- activating Lifecycle; pass consume as its sink. Unbind retired dispatch keys after activation;
5
- admitted invocations retain their original binding. Close/drain Lifecycle before discarding us.
4
+ activating Lifecycle; pass consume as its sink. Retire dispatch aliases only after native
5
+ fences removed definitions and admitted deliveries drain. Paired invocations retain their binding. Close/drain Lifecycle before discarding us.
6
6
  This module neither compiles SIL nor owns polling, fork/shutdown, exporters or init wiring.
7
7
  """
8
8
 
9
9
  from __future__ import annotations
10
10
 
11
11
  import json
12
+ from contextvars import Token
12
13
  from contextlib import nullcontext
13
14
  from dataclasses import dataclass, field
14
15
  from threading import RLock, get_ident
@@ -32,7 +33,8 @@ from opentelemetry.trace import (
32
33
  from struct_sdk.core import _contain_logged
33
34
 
34
35
  if TYPE_CHECKING:
35
- from struct_sdk_native._native import LifecycleRecord, LoadedTarget
36
+ from struct_sdk_native._native import LifecycleRecord
37
+ from struct_sdk_native.selection import TargetFacts
36
38
 
37
39
  SCOPE = "struct.capture"
38
40
  PREFIX = SCOPE + "."
@@ -97,6 +99,7 @@ class _Invocation:
97
99
  binding: OutputBinding
98
100
  span: Any = None
99
101
  token: Any = None
102
+ attached_span: Any = None
100
103
  thread: int = field(default_factory=get_ident)
101
104
  terminal: Any = None
102
105
  creator: _Action | None = None
@@ -167,6 +170,10 @@ class OutputAdapter:
167
170
  self._max_series_bytes = max_series_bytes
168
171
  self._series_bytes = 0
169
172
  self._bindings: dict[BindingKey, OutputBinding] = {}
173
+ # Generations can share an unchanged immutable binding. Dispatch aliases
174
+ # stay bounded while callbacks acquire their own binding ownership.
175
+ self._dispatch: dict[BindingKey, OutputBinding] = {}
176
+ self._binding_dispatch_counts: dict[BindingKey, int] = {}
170
177
  self._retired: set[BindingKey] = set()
171
178
  self._binding_users: dict[BindingKey, int] = {}
172
179
  self._pending: dict[int, _Invocation] = {}
@@ -181,6 +188,47 @@ class OutputAdapter:
181
188
  self._faults
182
189
  ) = self._invalid_contexts = 0
183
190
 
191
+ def release_after_fork(self, surviving_thread: int) -> bool:
192
+ """Restore inherited current-thread context without exporting parent spans.
193
+
194
+ Explicit child init calls this after native disarming. No inherited lock is
195
+ acquired and no foreign thread's token is reset.
196
+ """
197
+ for invocation in reversed(tuple(self._pending.values())):
198
+ token = invocation.token
199
+ if (
200
+ isinstance(token, Token)
201
+ and invocation.thread == get_ident()
202
+ and trace.get_current_span() is invocation.attached_span
203
+ ):
204
+ previous = token.old_value
205
+ parent = (
206
+ trace.INVALID_SPAN
207
+ if previous is Token.MISSING
208
+ else trace.get_current_span(previous)
209
+ )
210
+ restored = trace.set_span_in_context(parent, context.get_current())
211
+ try:
212
+ # OTel's public detach logs before swallowing a foreign-Context
213
+ # reset. The standard ContextVar API detects affinity quietly.
214
+ token.var.reset(token)
215
+ except ValueError:
216
+ # A copied Context owns no resettable token; retain the original.
217
+ pass
218
+ else:
219
+ invocation.token = None
220
+ # Preserve baggage added since attachment, including in the original
221
+ # Context. A currently active host span is never replaced above.
222
+ context.attach(restored)
223
+ # Vanished threads have no live Context to restore. Keep only affine tokens
224
+ # hidden by a newer host span or temporarily entered copied Context.
225
+ self._pending = {
226
+ key: value
227
+ for key, value in self._pending.items()
228
+ if value.thread == surviving_thread and value.token is not None
229
+ }
230
+ return not self._pending
231
+
184
232
  def status(self) -> OutputStatus:
185
233
  """Bounded aggregate snapshot for S5; this is not a second health producer."""
186
234
  with self._lock:
@@ -200,13 +248,14 @@ class OutputAdapter:
200
248
  def bind(
201
249
  self,
202
250
  artifact: Mapping[str, Any],
203
- target: LoadedTarget,
251
+ target: TargetFacts,
204
252
  *,
205
253
  generation: int,
206
254
  observation_id: str,
207
255
  membership_token: str,
256
+ reuse: BindingKey | None = None,
208
257
  ) -> OutputBinding | None:
209
- """Bind only verified artifacts and Discovery's selected LoadedTarget; no app inspection.
258
+ """Bind only verified artifacts and Discovery's selected target facts; no app inspection.
210
259
 
211
260
  JSON ownership, action pointers and code.* are resolved here, never in the callback.
212
261
  A refused binding is not a value-time version fallback.
@@ -215,7 +264,12 @@ class OutputAdapter:
215
264
  self._safe(
216
265
  lambda: result.append(
217
266
  self._bind(
218
- artifact, target, generation, observation_id, membership_token
267
+ artifact,
268
+ target,
269
+ generation,
270
+ observation_id,
271
+ membership_token,
272
+ reuse,
219
273
  )
220
274
  )
221
275
  )
@@ -224,19 +278,39 @@ class OutputAdapter:
224
278
  def _bind(
225
279
  self,
226
280
  artifact: Mapping[str, Any],
227
- target: LoadedTarget,
281
+ target: TargetFacts,
228
282
  generation: int,
229
283
  observation: str,
230
284
  member: str,
285
+ reuse: BindingKey | None,
231
286
  ) -> OutputBinding | None:
232
287
  raw = _json(artifact)
233
288
  size = len(raw.encode())
234
289
  owned = json.loads(raw)
235
290
  definition = owned["definition"]
236
291
  key = (generation, observation, member)
292
+ code = {
293
+ "code.function.name": definition["target"]["module"] + "." + target.qualname
294
+ }
295
+ if target.filename is not None:
296
+ code["code.file.path"] = target.filename
297
+ if target.first_line is not None:
298
+ code["code.line.number"] = target.first_line
237
299
  with self._lock:
238
- if key in self._bindings:
239
- return self._bindings[key]
300
+ if key in self._dispatch:
301
+ return self._dispatch[key]
302
+ if len(self._dispatch) >= 2 * self._max_bindings:
303
+ self._binding_refused += 1
304
+ return None
305
+ previous = self._dispatch.get(reuse) if reuse is not None else None
306
+ if (
307
+ previous is not None
308
+ and previous.definition_id == owned["definition_id"]
309
+ and previous.code == code
310
+ ):
311
+ self._dispatch[key] = previous
312
+ self._binding_dispatch_counts[previous.key] += 1
313
+ return previous
240
314
  if (
241
315
  len(self._bindings) >= self._max_bindings
242
316
  or self._binding_bytes + size > self._max_binding_bytes
@@ -259,26 +333,27 @@ class OutputAdapter:
259
333
  actions[path] = _Action(
260
334
  output["output_id"], kind, node, prefix, instrument
261
335
  )
262
- code = {
263
- "code.function.name": definition["target"]["module"]
264
- + "."
265
- + target.qualname
266
- }
267
- if target.filename is not None:
268
- code["code.file.path"] = target.filename
269
- if target.first_line is not None:
270
- code["code.line.number"] = target.first_line
271
336
  binding = OutputBinding(key, owned["definition_id"], code, actions, size)
272
337
  self._bindings[key] = binding
338
+ self._dispatch[key] = binding
339
+ self._binding_dispatch_counts[key] = 1
273
340
  self._binding_bytes += size
274
341
  return binding
275
342
 
276
343
  def unbind(self, key: BindingKey) -> None:
277
344
  with self._lock:
278
- if self._binding_users.get(key, 0):
279
- self._retired.add(key)
345
+ binding = self._dispatch.pop(key, None)
346
+ if binding is None:
347
+ return
348
+ canonical = binding.key
349
+ self._binding_dispatch_counts[canonical] -= 1
350
+ if self._binding_dispatch_counts[canonical]:
351
+ return
352
+ del self._binding_dispatch_counts[canonical]
353
+ if self._binding_users.get(canonical, 0):
354
+ self._retired.add(canonical)
280
355
  else:
281
- self._remove_binding(key)
356
+ self._remove_binding(canonical)
282
357
 
283
358
  def _remove_binding(self, key: BindingKey) -> None:
284
359
  binding = self._bindings.pop(key, None)
@@ -347,7 +422,7 @@ class OutputAdapter:
347
422
  binding = (
348
423
  invocation.binding
349
424
  if invocation
350
- else self._bindings.get(
425
+ else self._dispatch.get(
351
426
  (record.generation, record.observation_id, record.membership_token)
352
427
  )
353
428
  )
@@ -491,6 +566,7 @@ class OutputAdapter:
491
566
  if invocation.terminal is not None:
492
567
  self._end(invocation, invocation.terminal)
493
568
  else:
569
+ invocation.attached_span = span
494
570
  invocation.token = context.attach(
495
571
  trace.set_span_in_context(span, context.get_current())
496
572
  )