telemetry-dev 0.2.7__tar.gz → 0.2.9__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: telemetry-dev
3
- Version: 0.2.7
3
+ Version: 0.2.9
4
4
  Summary: telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics
5
5
  Keywords: telemetry,opentelemetry,llm,genai,tracing,observability
6
6
  Author: telemetry.dev
@@ -159,14 +159,19 @@ the core SDK with provider integrations to enable the new metric.
159
159
  | `log_level` | `"warn"` | SDK diagnostics level: `debug`/`info`/`warn`/`error`/`silent`. |
160
160
  | `capture_input`, `capture_output` | `True` | Global content-capture defaults. |
161
161
  | `mask` | `None` | `Callable[[Any, MaskContext], Any]` redaction hook, runs before JSON serialization on input/output/log messages (`MaskContext.key` is the attribute being written). Not applied to correlation identifiers. |
162
- | `max_attribute_length` | `65536` | Per-content-attribute cap; truncated values get an ASCII `...[truncated]` marker appended. |
162
+ | `max_attribute_length` | `65536` | Non-negative integer per-content-attribute cap. Invalid values call `on_error`, do not raise into application code, and install a disabled client; truncated values use the ASCII `...[truncated]` marker, or its prefix when the cap is shorter than the marker. The cap also applies, with the marker, to string metadata and log attributes; any other string attribute is cut at the cap without a marker, except that a cap of `0` leaves those at 65536. |
163
163
  | `span_filter` | `None` | Export predicate `Callable[[ReadableSpan], bool]`. |
164
164
  | `sampler` | OTel environment configuration | OTel `Sampler` that overrides environment settings. Session roots use its root policy. Real parents keep their sampling decisions. |
165
- | `on_error` | `None` | Receives every internal SDK error; the SDK never raises. |
165
+ | `on_error` | `None` | Receives internal SDK errors; repeated instrumentation failures from one stream may be coalesced into one report. The SDK never raises them into application code. |
166
166
  | `disable_atexit` | `False` | Skip the automatic atexit shutdown. |
167
167
  | `timeout` | `10.0` | OTLP HTTP timeout in seconds. |
168
168
  | `span_exporter`, `log_exporter`, `metric_reader` | `None` | Test seams / offline mode; any of them enables the client without an API key. |
169
169
 
170
+ `capture_input=False` and `capture_output=False` omit captured content. Provider integrations may
171
+ still record non-content metadata such as response IDs and models, finish reasons, usage, timing,
172
+ and errors. Capture flags do not gate stop sequences, tool descriptions and definitions (`gen_ai.tool.description`, `gen_ai.tool.definitions`), caller-supplied metadata or raw attributes,
173
+ or exception messages and stack traces; redact those separately when needed.
174
+
170
175
  Session roots share trace IDs from the API key and session ID. The hash matches the TypeScript SDK.
171
176
  The SDK uses the configured OTel sampling policy, not the synthetic parent's flags.
172
177
  For example, `init(sampler=ParentBased(TraceIdRatioBased(0.1)))` samples sessions with OTel's ratio sampler.
@@ -135,14 +135,19 @@ the core SDK with provider integrations to enable the new metric.
135
135
  | `log_level` | `"warn"` | SDK diagnostics level: `debug`/`info`/`warn`/`error`/`silent`. |
136
136
  | `capture_input`, `capture_output` | `True` | Global content-capture defaults. |
137
137
  | `mask` | `None` | `Callable[[Any, MaskContext], Any]` redaction hook, runs before JSON serialization on input/output/log messages (`MaskContext.key` is the attribute being written). Not applied to correlation identifiers. |
138
- | `max_attribute_length` | `65536` | Per-content-attribute cap; truncated values get an ASCII `...[truncated]` marker appended. |
138
+ | `max_attribute_length` | `65536` | Non-negative integer per-content-attribute cap. Invalid values call `on_error`, do not raise into application code, and install a disabled client; truncated values use the ASCII `...[truncated]` marker, or its prefix when the cap is shorter than the marker. The cap also applies, with the marker, to string metadata and log attributes; any other string attribute is cut at the cap without a marker, except that a cap of `0` leaves those at 65536. |
139
139
  | `span_filter` | `None` | Export predicate `Callable[[ReadableSpan], bool]`. |
140
140
  | `sampler` | OTel environment configuration | OTel `Sampler` that overrides environment settings. Session roots use its root policy. Real parents keep their sampling decisions. |
141
- | `on_error` | `None` | Receives every internal SDK error; the SDK never raises. |
141
+ | `on_error` | `None` | Receives internal SDK errors; repeated instrumentation failures from one stream may be coalesced into one report. The SDK never raises them into application code. |
142
142
  | `disable_atexit` | `False` | Skip the automatic atexit shutdown. |
143
143
  | `timeout` | `10.0` | OTLP HTTP timeout in seconds. |
144
144
  | `span_exporter`, `log_exporter`, `metric_reader` | `None` | Test seams / offline mode; any of them enables the client without an API key. |
145
145
 
146
+ `capture_input=False` and `capture_output=False` omit captured content. Provider integrations may
147
+ still record non-content metadata such as response IDs and models, finish reasons, usage, timing,
148
+ and errors. Capture flags do not gate stop sequences, tool descriptions and definitions (`gen_ai.tool.description`, `gen_ai.tool.definitions`), caller-supplied metadata or raw attributes,
149
+ or exception messages and stack traces; redact those separately when needed.
150
+
146
151
  Session roots share trace IDs from the API key and session ID. The hash matches the TypeScript SDK.
147
152
  The SDK uses the configured OTel sampling policy, not the synthetic parent's flags.
148
153
  For example, `init(sampler=ParentBased(TraceIdRatioBased(0.1)))` samples sessions with OTel's ratio sampler.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev"
3
- version = "0.2.7"
3
+ version = "0.2.9"
4
4
  description = "telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev"
3
- version = "0.2.7"
3
+ version = "0.2.9"
4
4
  description = "telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -2,7 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from collections.abc import Iterable
5
+ import re
6
+ from collections.abc import Iterable, Mapping, Sequence
6
7
  from itertools import chain
7
8
  from typing import Final, cast
8
9
 
@@ -11,6 +12,36 @@ _DEFAULT_MAX_ITEMS: Final = 1024
11
12
  _MAX_DEPTH: Final = 32
12
13
  _BASE_ITEM_BYTES: Final = 16
13
14
 
15
+ # Code points whose JSON form is longer than their UTF-8 form, mapped to the extra bytes.
16
+ _SHORT_ESCAPE_EXTRA: Final = 1 # '"', '\\', \b \t \n \f \r: 1 byte raw, 2 escaped
17
+ _CONTROL_ESCAPE_EXTRA: Final = 5 # other code points below 0x20: 1 byte raw, 6 as \u00XX
18
+ _SURROGATE_ESCAPE_EXTRA: Final = 3 # a surrogate code point: 3 bytes raw, 6 as \uXXXX
19
+ _JSON_ESCAPED: Final = re.compile('["\\\\\x00-\x1f\ud800-\udfff]')
20
+ _JSON_STRING_CHUNK: Final = 4096
21
+
22
+
23
+ def _escape_extra(character: str) -> int:
24
+ code = ord(character)
25
+ if character in '"\\\b\t\n\f\r':
26
+ return _SHORT_ESCAPE_EXTRA
27
+ if code < 0x20:
28
+ return _CONTROL_ESCAPE_EXTRA
29
+ return _SURROGATE_ESCAPE_EXTRA
30
+
31
+
32
+ def _json_string_bytes(value: str, limit: int | None) -> int:
33
+ # Every code point costs at least one byte, so a string longer than the limit needs no scan.
34
+ if limit is not None and len(value) > limit:
35
+ return len(value)
36
+ size = 0
37
+ for start in range(0, len(value), _JSON_STRING_CHUNK):
38
+ chunk = value[start : start + _JSON_STRING_CHUNK]
39
+ size += len(chunk.encode("utf-8", "surrogatepass"))
40
+ size += sum(_escape_extra(match.group()) for match in _JSON_ESCAPED.finditer(chunk))
41
+ if limit is not None and size > limit:
42
+ return size
43
+ return size
44
+
14
45
 
15
46
  class CaptureBudget:
16
47
  """Track a hard byte and item budget before retaining streamed provider data."""
@@ -32,6 +63,18 @@ class CaptureBudget:
32
63
  max_bytes=client.max_attribute_length if client is not None else _DEFAULT_MAX_BYTES
33
64
  )
34
65
 
66
+ @staticmethod
67
+ def json_string_bytes(value: str, limit: int | None = None) -> int:
68
+ """Return the UTF-8 bytes ``value`` occupies inside a JSON string, without the quotes.
69
+
70
+ Matches the TypeScript SDK's measure: ``"``, ``\\``, and ``\\b \\t \\n \\f \\r`` cost 2
71
+ bytes, other control characters cost 6 (``\\u00XX``), and every surrogate code point
72
+ costs 6 (``\\uXXXX``); anything else costs its UTF-8 width. The budget charges a string
73
+ this plus its per-item cost, which covers the quotes and separators. Counting stops
74
+ once the total passes ``limit``, so a result above ``limit`` is only a lower bound.
75
+ """
76
+ return _json_string_bytes(value, limit)
77
+
35
78
  @property
36
79
  def remaining_bytes(self) -> int:
37
80
  """Return bytes still available for retained capture state."""
@@ -98,20 +141,9 @@ class CaptureBudget:
98
141
  if value is None or isinstance(value, bool | int | float):
99
142
  return byte_count, item_count
100
143
  if isinstance(value, str):
101
- for character in value:
102
- codepoint = ord(character)
103
- byte_count += (
104
- 1
105
- if codepoint <= 0x7F
106
- else 2
107
- if codepoint <= 0x7FF
108
- else 3
109
- if codepoint <= 0xFFFF
110
- else 4
111
- )
112
- if byte_count > remaining_bytes:
113
- return None
114
- return byte_count, item_count
144
+ # Mapping keys come through here too, so they are charged at their escaped size.
145
+ byte_count += _json_string_bytes(value, remaining_bytes - byte_count)
146
+ return (byte_count, item_count) if byte_count <= remaining_bytes else None
115
147
  if isinstance(value, bytes | bytearray | memoryview):
116
148
  length = value.nbytes if isinstance(value, memoryview) else len(value)
117
149
  # Structured attributes serialize binary values as base64 text.
@@ -123,16 +155,18 @@ class CaptureBudget:
123
155
  return byte_count, item_count
124
156
  seen.add(value_id)
125
157
  try:
126
- mapping: dict[object, object] | None = None
158
+ mapping: Mapping[object, object] | None = None
127
159
  children: Iterable[object] = ()
128
- if isinstance(value, dict):
129
- mapping = cast("dict[object, object]", value)
130
- elif isinstance(value, list | tuple | set | frozenset):
160
+ if isinstance(value, Mapping):
161
+ mapping = cast("Mapping[object, object]", value)
162
+ elif isinstance(value, Sequence) and not isinstance(value, str | bytes | bytearray):
163
+ children = cast("Iterable[object]", value)
164
+ elif isinstance(value, set | frozenset):
131
165
  children = cast("Iterable[object]", value)
132
166
  else:
133
167
  attributes = getattr(value, "__dict__", None)
134
- if isinstance(attributes, dict):
135
- mapping = cast("dict[object, object]", attributes)
168
+ if isinstance(attributes, Mapping):
169
+ mapping = cast("Mapping[object, object]", attributes)
136
170
 
137
171
  if mapping is not None:
138
172
  children = chain.from_iterable(mapping.items())
@@ -49,7 +49,7 @@ from ._metrics import (
49
49
  )
50
50
  from ._processor import ExportMode, StampingSpanProcessor
51
51
  from ._semconv import SCOPE_NAME
52
- from ._serialize import Mask, serialize_content
52
+ from ._serialize import DEFAULT_MAX_ATTRIBUTE_LENGTH, Mask, serialize_content
53
53
 
54
54
  _lock = threading.RLock()
55
55
  _client: Client | None = None
@@ -182,14 +182,16 @@ class Client:
182
182
  )
183
183
 
184
184
  # The funnel keeps capped content (marker included) within max_attribute_length, so
185
- # the backstop can use the same cap for raw attributes set outside the funnel.
185
+ # the backstop can use the same cap for raw attributes set outside the funnel. A zero
186
+ # cap only drops content; as a backstop it would blank every string attribute.
187
+ backstop_length = max_attribute_length or DEFAULT_MAX_ATTRIBUTE_LENGTH
186
188
  self._tracer_provider = TracerProvider(
187
189
  resource=resource,
188
190
  sampler=sampler,
189
191
  shutdown_on_exit=False,
190
192
  span_limits=SpanLimits(
191
- max_attribute_length=max_attribute_length,
192
- max_span_attribute_length=max_attribute_length,
193
+ max_attribute_length=backstop_length,
194
+ max_span_attribute_length=backstop_length,
193
195
  ),
194
196
  )
195
197
  self._tracer_provider.sampler = SessionSampler(self._tracer_provider.sampler)
@@ -365,6 +367,14 @@ def init(
365
367
  try:
366
368
  if session_mode not in ("explicit", "process"):
367
369
  raise ValueError(f"invalid session_mode: {session_mode!r}")
370
+ raw_max_attribute_length: Any = max_attribute_length
371
+ if (
372
+ isinstance(raw_max_attribute_length, bool)
373
+ or not isinstance(raw_max_attribute_length, int)
374
+ or raw_max_attribute_length < 0
375
+ ):
376
+ raise ValueError("max_attribute_length must be a non-negative integer")
377
+ max_attribute_length = raw_max_attribute_length
368
378
  client = Client(
369
379
  config=config,
370
380
  enabled=effective_enabled,
@@ -31,9 +31,9 @@ def truncate(text: str, max_len: int) -> str:
31
31
  encoded = text.encode("utf-16-le")
32
32
  if len(encoded) <= max_len * 2:
33
33
  return text
34
- # Total stays within max_len so the provider's attribute_value_length_limit backstop,
35
- # set to the same cap, never slices the marker off.
36
- head = encoded[: max(max_len - len(TRUNCATION_MARKER), 0) * 2]
34
+ if max_len < len(TRUNCATION_MARKER):
35
+ return TRUNCATION_MARKER[: max(max_len, 0)]
36
+ head = encoded[: (max_len - len(TRUNCATION_MARKER)) * 2]
37
37
  try:
38
38
  return head.decode("utf-16-le") + TRUNCATION_MARKER
39
39
  except UnicodeDecodeError:
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import math
4
+ import sys
4
5
  import threading
5
6
  import time
6
7
  import traceback
@@ -267,7 +268,7 @@ def _fields_to_attributes(
267
268
  for key, value in raw.items():
268
269
  attr = coerce_attr_value(
269
270
  value,
270
- max_len=client.max_attribute_length,
271
+ max_len=sys.maxsize,
271
272
  key=key,
272
273
  on_error=client.on_error,
273
274
  )
@@ -379,6 +380,22 @@ class SpanHandle:
379
380
  self._context_token: Token[Context] | None = None
380
381
  self._ended = False
381
382
 
383
+ @property
384
+ def capture_output(self) -> bool:
385
+ return self._state.capture_output if self._state is not None else False
386
+
387
+ @property
388
+ def capture_masked(self) -> bool:
389
+ return self._client is not None and self._client.mask is not None
390
+
391
+ @property
392
+ def max_attribute_length(self) -> int:
393
+ return self._client.max_attribute_length if self._client is not None else 0
394
+
395
+ def report_error(self, cause: BaseException) -> None:
396
+ if self._client is not None:
397
+ self._client.report("provider instrumentation failed", cause)
398
+
382
399
  def _recording(self) -> bool:
383
400
  return (
384
401
  self._client is not None
File without changes