struct-sdk 0.5.29__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.
Files changed (44) hide show
  1. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/PKG-INFO +1 -1
  2. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/README.md +3 -1
  3. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/pyproject.toml +1 -1
  4. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_fork_safe_http.py +31 -2
  5. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_observations/health.py +91 -38
  6. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_observations/poller.py +2 -1
  7. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/.gitignore +0 -0
  8. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/LICENSE +0 -0
  9. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/PYPI.md +0 -0
  10. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/__init__.py +0 -0
  11. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_auto.py +0 -0
  12. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_container.py +0 -0
  13. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_distro.py +0 -0
  14. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_event_loop.py +0 -0
  15. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_genai_content.py +0 -0
  16. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_metrics.py +0 -0
  17. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_observations/__init__.py +0 -0
  18. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_observations/config.py +0 -0
  19. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_observations/identity.py +0 -0
  20. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_observations/native_events.py +0 -0
  21. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_observations/outputs.py +0 -0
  22. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_observations/routing.py +0 -0
  23. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_observations/runtime.py +0 -0
  24. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_observations/self_metrics.py +0 -0
  25. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_observations/uwsgi.py +0 -0
  26. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_operation_details.py +0 -0
  27. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_otel_logs.py +0 -0
  28. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/_pool.py +0 -0
  29. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/ag2.py +0 -0
  30. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/anthropic.py +0 -0
  31. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/autogen.py +0 -0
  32. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/claude_agent.py +0 -0
  33. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/core.py +0 -0
  34. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/crewai.py +0 -0
  35. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/gcp.py +0 -0
  36. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/google_genai.py +0 -0
  37. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/langchain.py +0 -0
  38. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/litellm.py +0 -0
  39. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/llamaindex.py +0 -0
  40. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/mcp.py +0 -0
  41. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/openai.py +0 -0
  42. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/openai_agents.py +0 -0
  43. {struct_sdk-0.5.29 → struct_sdk-0.5.30}/src/struct_sdk/pydantic_ai.py +0 -0
  44. {struct_sdk-0.5.29 → 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.29
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
@@ -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. With `DD_TRACE_OTEL_ENABLED=true`,
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.29"
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"
@@ -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. Every session the SDK owns uses this."""
153
- session = requests.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
 
@@ -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,10 +161,10 @@ 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
- A new or changed condition goes out on the next pass; an unchanged active one is restated only
151
- on the heartbeat. Cleared entries retire only after an emit attempt.
152
- Repeated pending transitions retain the latest state, with superseded transitions counted in
153
- overflow. The bounded, best-effort stream is not a durable transition journal or fleet census.
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__(
@@ -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, entries: Mapping[str, _Entry]) -> int:
200
- conditions = [entry.condition for entry in entries.values()]
201
- conditions.extend(item for item in self._emitting if all(item is not kept for kept in conditions))
202
- return sys.getsizeof(entries) + sum(item.charge() for item in conditions)
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) -> bool:
205
- candidate = dict(self._entries)
206
- candidate[condition.key] = _Entry(condition, now)
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 False
211
- self._entries = candidate
212
- return True
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
- now = self._clock()
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
- now = self._clock()
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 due condition goes to the sink as one record, with
300
- one record per representative ID, in a single call. May be called manually by an
301
- integration's scheduler."""
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
- due: list[_Condition] = []
313
- for key, entry in tuple(self._entries.items()):
314
- if entry.due > now:
315
- continue
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
- item, sequence = entry.condition, self._sequence
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
- # Records in flight still count against the bounds until the sink returns.
327
- self._emitting = tuple(due)
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
File without changes
File without changes
File without changes