telemetry-dev-bedrock 0.2.2__tar.gz → 0.2.4__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-bedrock
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: AWS Bedrock integration for telemetry.dev Python SDK
5
5
  Keywords: telemetry,opentelemetry,bedrock,aws,boto3,genai,tracing
6
6
  Author: telemetry.dev
@@ -108,7 +108,7 @@ Global instrumentation wraps `botocore.client.BaseClient._make_api_call` and fil
108
108
  | --- | --- | --- | --- |
109
109
  | `capture_agent_trace` | `False` | Agent Runtime streams | Aggregates trace usage and counts by default. When enabled, also attaches trace events as `td.metadata.agent_trace`, filtered as described below. |
110
110
 
111
- `td.metadata.agent_trace` is truncated but never passed to your `mask`, so each trace event is rebuilt from an explicit allowlist instead:
111
+ `td.metadata.agent_trace` is metadata, which is cut at `max_attribute_length` when you set one (at 65,536 characters by default with `telemetry-dev` 0.3.2 or earlier) but never passed to your `mask`, so each trace event is rebuilt from an explicit allowlist instead:
112
112
 
113
113
  - Envelope fields: `agentId`, `agentAliasId`, `agentVersion`, `sessionId`, `collaboratorName`, `eventTime`, and the alias ARNs in `callerChain`.
114
114
  - Content the agent sends to a model, tool, or guardrail (`modelInvocationInput`, `invocationInput`, `inputAssessments`) is kept as received when `capture_input` is on.
@@ -117,7 +117,7 @@ Global instrumentation wraps `botocore.client.BaseClient._make_api_call` and fil
117
117
  - When a `mask` is set, all of this content is withheld.
118
118
  - Withheld content and the trace structure around it keep only trace ids, step types, the foundation model, guardrail action, failure code, and the usage, timings, and `clientRequestId` from AWS's trace `metadata`.
119
119
 
120
- Any other field, including unknown trace types and the AWS SDK's `$unknown` union member, is omitted even when both capture options are on; a content part that is kept is exported whole, including any fields inside it that are not listed here. Errors are not covered by this filtering: AWS exceptions, including errors raised inside the stream, still record the provider's error message on the span.
120
+ Any other field, including unknown trace types and the AWS SDK's `$unknown` union member, is omitted even when both capture options are on; a content part that is kept is exported whole, including any fields inside it that are not listed here. Errors are not covered by this filtering: an AWS exception, including one raised inside the stream, records the provider's error message on the span when both `capture_input` and `capture_output` are on, and the message passes through `mask`.
121
121
 
122
122
  ```py
123
123
  agent = wrap_bedrock(
@@ -160,16 +160,16 @@ Converse messages follow the OpenTelemetry GenAI non-normative LLM-call examples
160
160
  - image/document/video/audio bytes become blob parts without byte content
161
161
  - S3/URI sources become `{ "type": "uri", "uri", "modality" }`
162
162
 
163
- InvokeModel captures provider-native JSON bodies verbatim. Non-JSON bodies are not captured.
163
+ InvokeModel captures provider-native JSON bodies verbatim. A body whose content type is not JSON is not captured, and that is not a failure. A JSON-typed or untyped body that is not UTF-8 or not valid JSON records no output, sets `telemetry.dev.capture.truncated`, and is reported to `on_error` (see below); a blank body records no output and is not a failure.
164
164
 
165
165
  ## Semantics and guarantees
166
166
 
167
167
  - Provider is emitted as `amazon-bedrock`. This intentionally differs from the OpenTelemetry registry value `aws.bedrock` so telemetry.dev pricing keys match Bedrock model IDs exactly. The raw caller `modelId`, `modelArn`, or `foundationModel` is emitted as the model.
168
- - Instrumentation is fail-open. Normalization, span updates, and span endings are guarded so telemetry failures do not break caller code.
168
+ - Instrumentation is fail-open. Normalization, span updates, and span endings are guarded so telemetry failures do not break caller code. When the response of a successful non-streamed call (such as `Converse`, `ApplyGuardrail`, `Rerank`, `Retrieve`, or `RetrieveAndGenerate`) fails to map, the failure is reported to `on_error` and the span ends with the AWS response metadata, without output, and with `telemetry.dev.capture.truncated`; it is not marked failed. When a stream response's own fields fail to map, the failure is reported and the stream still records its output from its events.
169
169
  - Requests are never modified.
170
170
  - Streams end spans exactly once. Exhaustion records full output and finish reason; early `break`, `close()`, `GeneratorExit`, or stream errors record partial output and set `telemetry.dev.capture.truncated`.
171
- - Event-stream reconstruction retains up to 48 KiB and 1,000 items. `InvokeModel` bodies and `Rerank` inputs and results are retained up to 64 KiB and 1,024 items; a body over that bound records no output and sets `telemetry.dev.capture.truncated`. The configured `max_attribute_length` does not shrink these retention bounds; the core applies it to the exported attribute after the mask runs.
172
- - A stream cut at its retention bound, closed early, or failed sets `telemetry.dev.capture.truncated`. An `InvokeModel` body that is closed before it is fully read, or whose read fails, records no output and sets the attribute too. With a mask configured, incomplete reconstructed output is omitted because the mask cannot inspect the complete value. Agent trace events share the bound, but dropping them only sets the attribute; Agent text is omitted only when a text chunk was dropped or the stream was closed early or failed. A normally exhausted Agent stream that returned control keeps its complete `returnControl` output even if earlier text or trace metadata passed the bound; an early close or failure still omits the output when a mask is configured.
171
+ - Event-stream reconstruction and streamed `InvokeModel` bodies are kept up to 16 MiB, and all streams in flight share the `max_stream_bytes` bound of the core (64 MiB by default). These bounds need a `telemetry-dev` core with `max_stream_bytes`; with an older core, each stream keeps up to 64 KiB and 1,024 items. `InvokeModel` bodies and `Rerank` inputs and results are retained up to 16 MiB each; a body over that bound records no output and sets `telemetry.dev.capture.truncated`. The configured `max_attribute_length` does not shrink these retention bounds; the core applies it to the exported attribute after the mask runs.
172
+ - A stream cut at its retention bound, closed early, or failed sets `telemetry.dev.capture.truncated`. An event that fails to map, or a failure while the time to first chunk or an output-chunk timestamp is recorded, is reported to `on_error`; only the first such failure of a stream is reported. A failure before the event's output is kept also sets the attribute, and no later text or content is kept; so does an `InvokeModel` stream chunk that is not UTF-8 or not JSON (a blank chunk holds no output and is skipped). Agent text is decoded across chunks, so a character split between two chunks is kept whole; Agent text that is not UTF-8, or a stream that ends inside a character, loses that text like a failed event and is reported; an Agent `returnControl` that arrives later still replaces the text output whole, also with a mask configured. A failure in the event's usage, metrics, or Agent trace summaries loses only that metadata and does not set the attribute, and so does a timing failure. A failure while Agent trace content is captured (`capture_agent_trace`) loses that trace and sets the attribute, but later text is still kept, also with a mask configured. A stream whose output fails to map when it ends records no output and sets the attribute. An `InvokeModel` body that is closed before it is fully read, whose read fails, or that fails to map (for example, a body that is not UTF-8 or not JSON) records no output and sets the attribute too; a mapping failure is reported to `on_error`. With a mask configured, incomplete reconstructed output is omitted because the mask cannot inspect the complete value. Agent trace events share the bound, but dropping them only sets the attribute; Agent text is omitted only when a text chunk was dropped or failed to map, or the stream was closed early or failed. A normally exhausted Agent stream that returned control keeps its complete `returnControl` output even if earlier text or trace metadata passed the bound; an early close or failure still omits the output when a mask is configured.
173
173
  - boto3 has no async client. `aiobotocore` is a separate package and is out of scope.
174
174
 
175
175
  ## Coverage gaps
@@ -85,7 +85,7 @@ Global instrumentation wraps `botocore.client.BaseClient._make_api_call` and fil
85
85
  | --- | --- | --- | --- |
86
86
  | `capture_agent_trace` | `False` | Agent Runtime streams | Aggregates trace usage and counts by default. When enabled, also attaches trace events as `td.metadata.agent_trace`, filtered as described below. |
87
87
 
88
- `td.metadata.agent_trace` is truncated but never passed to your `mask`, so each trace event is rebuilt from an explicit allowlist instead:
88
+ `td.metadata.agent_trace` is metadata, which is cut at `max_attribute_length` when you set one (at 65,536 characters by default with `telemetry-dev` 0.3.2 or earlier) but never passed to your `mask`, so each trace event is rebuilt from an explicit allowlist instead:
89
89
 
90
90
  - Envelope fields: `agentId`, `agentAliasId`, `agentVersion`, `sessionId`, `collaboratorName`, `eventTime`, and the alias ARNs in `callerChain`.
91
91
  - Content the agent sends to a model, tool, or guardrail (`modelInvocationInput`, `invocationInput`, `inputAssessments`) is kept as received when `capture_input` is on.
@@ -94,7 +94,7 @@ Global instrumentation wraps `botocore.client.BaseClient._make_api_call` and fil
94
94
  - When a `mask` is set, all of this content is withheld.
95
95
  - Withheld content and the trace structure around it keep only trace ids, step types, the foundation model, guardrail action, failure code, and the usage, timings, and `clientRequestId` from AWS's trace `metadata`.
96
96
 
97
- Any other field, including unknown trace types and the AWS SDK's `$unknown` union member, is omitted even when both capture options are on; a content part that is kept is exported whole, including any fields inside it that are not listed here. Errors are not covered by this filtering: AWS exceptions, including errors raised inside the stream, still record the provider's error message on the span.
97
+ Any other field, including unknown trace types and the AWS SDK's `$unknown` union member, is omitted even when both capture options are on; a content part that is kept is exported whole, including any fields inside it that are not listed here. Errors are not covered by this filtering: an AWS exception, including one raised inside the stream, records the provider's error message on the span when both `capture_input` and `capture_output` are on, and the message passes through `mask`.
98
98
 
99
99
  ```py
100
100
  agent = wrap_bedrock(
@@ -137,16 +137,16 @@ Converse messages follow the OpenTelemetry GenAI non-normative LLM-call examples
137
137
  - image/document/video/audio bytes become blob parts without byte content
138
138
  - S3/URI sources become `{ "type": "uri", "uri", "modality" }`
139
139
 
140
- InvokeModel captures provider-native JSON bodies verbatim. Non-JSON bodies are not captured.
140
+ InvokeModel captures provider-native JSON bodies verbatim. A body whose content type is not JSON is not captured, and that is not a failure. A JSON-typed or untyped body that is not UTF-8 or not valid JSON records no output, sets `telemetry.dev.capture.truncated`, and is reported to `on_error` (see below); a blank body records no output and is not a failure.
141
141
 
142
142
  ## Semantics and guarantees
143
143
 
144
144
  - Provider is emitted as `amazon-bedrock`. This intentionally differs from the OpenTelemetry registry value `aws.bedrock` so telemetry.dev pricing keys match Bedrock model IDs exactly. The raw caller `modelId`, `modelArn`, or `foundationModel` is emitted as the model.
145
- - Instrumentation is fail-open. Normalization, span updates, and span endings are guarded so telemetry failures do not break caller code.
145
+ - Instrumentation is fail-open. Normalization, span updates, and span endings are guarded so telemetry failures do not break caller code. When the response of a successful non-streamed call (such as `Converse`, `ApplyGuardrail`, `Rerank`, `Retrieve`, or `RetrieveAndGenerate`) fails to map, the failure is reported to `on_error` and the span ends with the AWS response metadata, without output, and with `telemetry.dev.capture.truncated`; it is not marked failed. When a stream response's own fields fail to map, the failure is reported and the stream still records its output from its events.
146
146
  - Requests are never modified.
147
147
  - Streams end spans exactly once. Exhaustion records full output and finish reason; early `break`, `close()`, `GeneratorExit`, or stream errors record partial output and set `telemetry.dev.capture.truncated`.
148
- - Event-stream reconstruction retains up to 48 KiB and 1,000 items. `InvokeModel` bodies and `Rerank` inputs and results are retained up to 64 KiB and 1,024 items; a body over that bound records no output and sets `telemetry.dev.capture.truncated`. The configured `max_attribute_length` does not shrink these retention bounds; the core applies it to the exported attribute after the mask runs.
149
- - A stream cut at its retention bound, closed early, or failed sets `telemetry.dev.capture.truncated`. An `InvokeModel` body that is closed before it is fully read, or whose read fails, records no output and sets the attribute too. With a mask configured, incomplete reconstructed output is omitted because the mask cannot inspect the complete value. Agent trace events share the bound, but dropping them only sets the attribute; Agent text is omitted only when a text chunk was dropped or the stream was closed early or failed. A normally exhausted Agent stream that returned control keeps its complete `returnControl` output even if earlier text or trace metadata passed the bound; an early close or failure still omits the output when a mask is configured.
148
+ - Event-stream reconstruction and streamed `InvokeModel` bodies are kept up to 16 MiB, and all streams in flight share the `max_stream_bytes` bound of the core (64 MiB by default). These bounds need a `telemetry-dev` core with `max_stream_bytes`; with an older core, each stream keeps up to 64 KiB and 1,024 items. `InvokeModel` bodies and `Rerank` inputs and results are retained up to 16 MiB each; a body over that bound records no output and sets `telemetry.dev.capture.truncated`. The configured `max_attribute_length` does not shrink these retention bounds; the core applies it to the exported attribute after the mask runs.
149
+ - A stream cut at its retention bound, closed early, or failed sets `telemetry.dev.capture.truncated`. An event that fails to map, or a failure while the time to first chunk or an output-chunk timestamp is recorded, is reported to `on_error`; only the first such failure of a stream is reported. A failure before the event's output is kept also sets the attribute, and no later text or content is kept; so does an `InvokeModel` stream chunk that is not UTF-8 or not JSON (a blank chunk holds no output and is skipped). Agent text is decoded across chunks, so a character split between two chunks is kept whole; Agent text that is not UTF-8, or a stream that ends inside a character, loses that text like a failed event and is reported; an Agent `returnControl` that arrives later still replaces the text output whole, also with a mask configured. A failure in the event's usage, metrics, or Agent trace summaries loses only that metadata and does not set the attribute, and so does a timing failure. A failure while Agent trace content is captured (`capture_agent_trace`) loses that trace and sets the attribute, but later text is still kept, also with a mask configured. A stream whose output fails to map when it ends records no output and sets the attribute. An `InvokeModel` body that is closed before it is fully read, whose read fails, or that fails to map (for example, a body that is not UTF-8 or not JSON) records no output and sets the attribute too; a mapping failure is reported to `on_error`. With a mask configured, incomplete reconstructed output is omitted because the mask cannot inspect the complete value. Agent trace events share the bound, but dropping them only sets the attribute; Agent text is omitted only when a text chunk was dropped or failed to map, or the stream was closed early or failed. A normally exhausted Agent stream that returned control keeps its complete `returnControl` output even if earlier text or trace metadata passed the bound; an early close or failure still omits the output when a mask is configured.
150
150
  - boto3 has no async client. `aiobotocore` is a separate package and is out of scope.
151
151
 
152
152
  ## Coverage gaps
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev-bedrock"
3
- version = "0.2.2"
3
+ version = "0.2.4"
4
4
  description = "AWS Bedrock integration for telemetry.dev Python SDK"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev-bedrock"
3
- version = "0.2.2"
3
+ version = "0.2.4"
4
4
  description = "AWS Bedrock integration for telemetry.dev Python SDK"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -2,6 +2,6 @@ from __future__ import annotations
2
2
 
3
3
  from ._instrument import instrument_bedrock, uninstrument_bedrock, wrap_bedrock
4
4
 
5
- __version__ = "0.2.2"
5
+ __version__ = "0.2.4"
6
6
 
7
7
  __all__ = ["__version__", "instrument_bedrock", "uninstrument_bedrock", "wrap_bedrock"]
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import os
3
4
  import threading
4
5
  import time
5
6
  from collections.abc import Callable
@@ -13,7 +14,12 @@ from botocore.response import StreamingBody
13
14
  from ._fields import error_fields, merge_fields, metadata_fields
14
15
  from ._invoke_model import parse_body
15
16
  from ._registry import OperationSpec, lookup_operation
16
- from ._streams import InstrumentedEventStream
17
+ from ._streams import (
18
+ InstrumentedEventStream,
19
+ release_budget,
20
+ stream_capture_budget,
21
+ stream_span_reporter,
22
+ )
17
23
 
18
24
  _T = TypeVar("_T", bound=BaseClient)
19
25
  _SUPPORTED_SERVICES = frozenset({"bedrock-runtime", "bedrock-agent-runtime"})
@@ -21,11 +27,26 @@ _WRAPPED_ATTR = "_telemetry_dev_bedrock_wrapped"
21
27
 
22
28
  _original_api_call: Callable[..., Any] | None = None
23
29
  _patched_api_call: Callable[..., Any] | None = None
24
- _LOCK = threading.Lock()
30
+ _install_lock = threading.Lock()
31
+
32
+
33
+ def _reset_install_lock_in_child() -> None:
34
+ """A thread of the parent can hold the lock at a fork, and only this thread exists here."""
35
+ global _install_lock
36
+ _install_lock = threading.Lock()
37
+
38
+
39
+ # A hook is enough: a fork that runs no hooks, as uWSGI's fork of its workers by default,
40
+ # starts from its master, which serves no requests. os.register_at_fork cannot remove a hook,
41
+ # and importlib.reload runs this module again with the same globals, so the hook of the first
42
+ # run stays. Windows has no fork.
43
+ if hasattr(os, "register_at_fork") and "_install_fork_hook" not in globals():
44
+ _install_fork_hook = True
45
+ os.register_at_fork(after_in_child=_reset_install_lock_in_child)
25
46
 
26
47
 
27
48
  def wrap_bedrock(client: _T, *, capture_agent_trace: bool = False) -> _T:
28
- with _LOCK:
49
+ with _install_lock:
29
50
  if getattr(client, _WRAPPED_ATTR, False):
30
51
  return client
31
52
  mapping = getattr(client.meta, "method_to_api_mapping", {})
@@ -50,7 +71,7 @@ def wrap_bedrock(client: _T, *, capture_agent_trace: bool = False) -> _T:
50
71
 
51
72
 
52
73
  def instrument_bedrock(*, capture_agent_trace: bool = False) -> None:
53
- with _LOCK:
74
+ with _install_lock:
54
75
  global _original_api_call, _patched_api_call
55
76
  if _original_api_call is not None:
56
77
  return
@@ -73,7 +94,7 @@ def instrument_bedrock(*, capture_agent_trace: bool = False) -> None:
73
94
 
74
95
 
75
96
  def uninstrument_bedrock() -> None:
76
- with _LOCK:
97
+ with _install_lock:
77
98
  global _original_api_call, _patched_api_call
78
99
  if _original_api_call is None or _patched_api_call is None:
79
100
  return
@@ -137,7 +158,7 @@ def _call_with_span(
137
158
  return response
138
159
 
139
160
  if operation_name == "InvokeModel" and isinstance(response.get("body"), StreamingBody):
140
- return _handle_streaming_body(spec, api_params, response, end)
161
+ return _handle_streaming_body(spec, api_params, response, end, handle)
141
162
 
142
163
  stream_key = spec.stream_key
143
164
  if stream_key is not None and response.get(stream_key) is not None:
@@ -146,30 +167,41 @@ def _call_with_span(
146
167
  end(**metadata_fields(response))
147
168
  return response
148
169
  state = state_factory(capture_agent_trace)
170
+ report_error = stream_span_reporter(handle)
149
171
  try:
150
172
  base_fields = merge_fields(
151
173
  metadata_fields(response), spec.response_fields(api_params, response)
152
174
  )
153
- except Exception:
175
+ except Exception as exc:
176
+ # The stream's own output and metadata are still recorded from its events.
177
+ report_error(exc)
154
178
  base_fields = metadata_fields(response)
155
179
 
156
180
  def finish(fields: dict[str, Any]) -> None:
157
181
  if fields.keys() == {"time_to_first_chunk_ms"}:
158
182
  try:
159
183
  handle.update(**fields)
160
- except Exception:
161
- pass
184
+ except Exception as exc:
185
+ report_error(exc)
162
186
  return
163
187
  end(**merge_fields(base_fields, fields))
164
188
 
165
189
  return {
166
190
  **response,
167
191
  stream_key: InstrumentedEventStream(
168
- response[stream_key], state, finish, started_at, handle
192
+ response[stream_key], state, finish, started_at, handle, report_error
169
193
  ),
170
194
  }
171
195
 
172
- end(**merge_fields(metadata_fields(response), spec.response_fields(api_params, response)))
196
+ try:
197
+ fields = merge_fields(metadata_fields(response), spec.response_fields(api_params, response))
198
+ except Exception as exc:
199
+ # The call succeeded, so it is not failed; its output and response fields are lost.
200
+ stream_span_reporter(handle)(exc)
201
+ fields = merge_fields(
202
+ metadata_fields(response), {"attributes": {"telemetry.dev.capture.truncated": True}}
203
+ )
204
+ end(**fields)
173
205
  return response
174
206
 
175
207
 
@@ -318,8 +350,8 @@ class _InstrumentedStreamingBody(StreamingBody):
318
350
  super().__init__(body, getattr(body, "_content_length", None))
319
351
  self._body = body
320
352
  self._finish_callback = finish
321
- # Fixed retention bound; the core applies max_attribute_length after the mask.
322
- self._budget = telemetry_dev.CaptureBudget()
353
+ # The core applies max_attribute_length after the mask.
354
+ self._budget = stream_capture_budget()
323
355
  self._captured = bytearray()
324
356
  self._ended = False
325
357
 
@@ -403,9 +435,12 @@ class _InstrumentedStreamingBody(StreamingBody):
403
435
  if self._ended:
404
436
  return
405
437
  self._ended = True
406
- captured = bytes(self._captured) if complete and not self._budget.truncated else None
407
- # A body closed early, failed, or cut at the bound exports no output and is flagged.
408
- self._finish_callback(captured, error, not complete or self._budget.truncated)
438
+ try:
439
+ captured = bytes(self._captured) if complete and not self._budget.truncated else None
440
+ # A body closed early, failed, or cut at the bound exports no output and is flagged.
441
+ self._finish_callback(captured, error, not complete or self._budget.truncated)
442
+ finally:
443
+ release_budget(self._budget)
409
444
 
410
445
 
411
446
  def _handle_streaming_body(
@@ -413,23 +448,29 @@ def _handle_streaming_body(
413
448
  params: dict[str, Any],
414
449
  response: dict[str, Any],
415
450
  end: Callable[..., None],
451
+ handle: Any,
416
452
  ) -> dict[str, Any]:
417
453
  body = cast(StreamingBody, response["body"])
418
454
  base_fields = metadata_fields(response)
455
+ report_error = stream_span_reporter(handle)
419
456
 
420
457
  def finish(raw: bytes | None, error: BaseException | None, truncated: bool) -> None:
421
458
  fields = base_fields
422
459
  if raw is not None:
423
- parsed = parse_body(raw, response.get("contentType"))
424
- response_for_fields = {**response, "_telemetry_dev_parsed_body": parsed}
425
460
  try:
461
+ # A JSON body that fails to decode lost its output, so it fails here; a body whose
462
+ # content type is not JSON returns None.
463
+ parsed = parse_body(raw, response.get("contentType"), strict=True)
464
+ response_for_fields = {**response, "_telemetry_dev_parsed_body": parsed}
426
465
  fields = merge_fields(
427
466
  base_fields, spec.response_fields(params, response_for_fields)
428
467
  )
429
- except Exception:
430
- fields = base_fields
468
+ except Exception as exc:
469
+ report_error(exc)
470
+ truncated = True
431
471
  if truncated:
432
- # An incomplete body cannot be parsed, so no output is exported.
472
+ # An incomplete body cannot be parsed, and a body that failed to map lost its
473
+ # output, so no output is exported.
433
474
  fields = merge_fields(fields, {"attributes": {"telemetry.dev.capture.truncated": True}})
434
475
  if error is not None:
435
476
  fields = merge_fields(fields, error_fields(error))
@@ -46,7 +46,10 @@ def claude_usage_fields(usage: dict[str, Any]) -> dict[str, Any]:
46
46
  return fields
47
47
 
48
48
 
49
- def parse_body(body: Any, content_type: Any = "application/json") -> Any:
49
+ def parse_body(body: Any, content_type: Any = "application/json", *, strict: bool = False) -> Any:
50
+ """Decodes a JSON body. Returns None when the content type is not JSON, or the body is
51
+ blank, unreadable, or not bytes, str, or a seekable stream. A body that is not UTF-8
52
+ raises. A body that is not valid JSON returns None, or raises with ``strict``."""
50
53
  if isinstance(content_type, str) and "json" not in content_type:
51
54
  return None
52
55
  if isinstance(body, bytes | bytearray):
@@ -79,6 +82,8 @@ def parse_body(body: Any, content_type: Any = "application/json") -> Any:
79
82
  try:
80
83
  return json.loads(raw)
81
84
  except Exception:
85
+ if strict and raw.strip():
86
+ raise
82
87
  return None
83
88
 
84
89
 
@@ -266,7 +266,8 @@ def _bounded_capture(value: Any, capture: Literal["input", "output"]) -> tuple[A
266
266
  )
267
267
  if not enabled:
268
268
  return None, False
269
- # Fixed retention bound; the core applies max_attribute_length after the mask.
269
+ # A value past the record bound (MAX_RECORD_BYTES) is not kept; the core applies
270
+ # max_attribute_length after the mask.
270
271
  budget = telemetry_dev.CaptureBudget()
271
272
  return (value if budget.accept(value) else None), budget.truncated
272
273
 
@@ -1,10 +1,14 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import codecs
3
4
  import json
5
+ import os
6
+ import threading
4
7
  import time
5
8
  from collections.abc import Callable, Iterator
6
9
  from dataclasses import dataclass
7
10
  from datetime import datetime
11
+ from io import StringIO
8
12
  from typing import Any, cast
9
13
 
10
14
  import telemetry_dev
@@ -13,15 +17,93 @@ from ._fields import clean, error_fields, merge_fields, usage_from_converse
13
17
  from ._invoke_model import claude_usage_fields, usage_number
14
18
  from ._messages import normalize_content_block
15
19
 
16
- # Retention uses fixed bounds; the core applies max_attribute_length after the mask.
17
- _STREAM_CAPTURE_MAX_BYTES = 48 * 1024
18
- _STREAM_CAPTURE_MAX_ITEMS = 1000
20
+ # The core applies max_attribute_length after the mask.
19
21
  _CAPTURE_TRUNCATED_ATTRIBUTE = "telemetry.dev.capture.truncated"
20
22
  _OMIT = object()
21
23
 
22
24
 
23
25
  def stream_capture_budget() -> telemetry_dev.CaptureBudget:
24
- return telemetry_dev.CaptureBudget(_STREAM_CAPTURE_MAX_BYTES, _STREAM_CAPTURE_MAX_ITEMS)
26
+ # Older cores have no for_stream and bound each budget at 64 KiB on its own.
27
+ for_stream = getattr(telemetry_dev.CaptureBudget, "for_stream", None)
28
+ budget = for_stream() if callable(for_stream) else telemetry_dev.CaptureBudget()
29
+ return cast(telemetry_dev.CaptureBudget, budget)
30
+
31
+
32
+ def release_budget(budget: telemetry_dev.CaptureBudget) -> None:
33
+ release = getattr(budget, "release", None)
34
+ if callable(release):
35
+ release()
36
+
37
+
38
+ # On Python 3.10 and 3.11, StringIO keeps up to 100,000 written strings in a list before it
39
+ # joins them, about 60 bytes each that the stream bound does not charge: 15 bytes a character
40
+ # for 4-character deltas. Deltas are joined 256 at a time, so that those waiting hold under
41
+ # about 22 KB, onto a string that is written once it has 4,096 characters, so that what is
42
+ # written costs about 1.5% more than its text. Python 3.12 dropped the list.
43
+ _DELTA_BATCH = 256
44
+ _WRITE_CHARS = 4096
45
+
46
+
47
+ class _DeltaBuffer:
48
+ # A write takes several steps, unlike one StringIO call, so without the lock a read on
49
+ # another thread, such as one that closes the stream, could copy a batch twice or drop it.
50
+ # A fork copies the lock held if another thread was writing, and that thread does not run
51
+ # in the child to release it. Every fork, also one that runs no at-fork hooks, changes the
52
+ # process ID, so a child takes a new lock. The check is inline because it runs per delta.
53
+ # A signal handler runs on the thread it interrupts, so one that reads the stream, such as
54
+ # one that closes it, can read inside a write. So the lock is reentrant, and each step takes
55
+ # the deltas and the tail out of the buffer before it joins or writes them, so that a read
56
+ # inside the step does not write them as well; that read returns a prefix, which can leave
57
+ # out the deltas being joined. A handler that writes inside a step is not supported. An
58
+ # exception inside a step, such as KeyboardInterrupt from a handler, puts back the text the
59
+ # step took unless the StringIO has it, so that a later read still has every delta.
60
+ __slots__ = ("_buffer", "_lock", "_pending", "_pid", "_tail")
61
+
62
+ def __init__(self) -> None:
63
+ self._buffer = StringIO()
64
+ self._lock = threading.RLock()
65
+ self._pid = os.getpid()
66
+ self._pending: list[str] = []
67
+ self._tail = ""
68
+
69
+ def write(self, text: str) -> None:
70
+ pid = os.getpid()
71
+ if self._pid != pid:
72
+ self._lock = threading.RLock()
73
+ self._pid = pid
74
+ with self._lock:
75
+ self._pending.append(text)
76
+ if len(self._pending) >= _DELTA_BATCH:
77
+ self._join(_WRITE_CHARS)
78
+
79
+ def getvalue(self) -> str:
80
+ pid = os.getpid()
81
+ if self._pid != pid:
82
+ self._lock = threading.RLock()
83
+ self._pid = pid
84
+ with self._lock:
85
+ self._join(1)
86
+ return self._buffer.getvalue()
87
+
88
+ def _join(self, write_at: int) -> None:
89
+ if not self._pending and len(self._tail) < write_at:
90
+ return
91
+ written = self._buffer.tell()
92
+ pending: list[str] = []
93
+ tail = ""
94
+ try:
95
+ pending, self._pending = self._pending, []
96
+ tail, self._tail = self._tail, ""
97
+ joined = "".join([tail, *pending])
98
+ if len(joined) >= write_at:
99
+ self._buffer.write(joined)
100
+ else:
101
+ self._tail = joined
102
+ except BaseException:
103
+ if self._buffer.tell() == written:
104
+ self._pending[:0] = pending
105
+ self._tail = tail + self._tail
106
+ raise
25
107
 
26
108
 
27
109
  def capture_masked(handle: Any) -> bool:
@@ -39,8 +121,32 @@ def mark_capture_incomplete(fields: dict[str, Any], mask_output: bool) -> dict[s
39
121
  return marked
40
122
 
41
123
 
124
+ def stream_span_reporter(handle: Any) -> Callable[[BaseException], None]:
125
+ reported = False
126
+
127
+ # One report per stream: a mapper that fails on one event likely fails on each one after it.
128
+ def report(cause: BaseException) -> None:
129
+ nonlocal reported
130
+ if reported:
131
+ return
132
+ reported = True
133
+ try:
134
+ handle.report_error(cause)
135
+ except Exception:
136
+ return
137
+
138
+ return report
139
+
140
+
42
141
  class StreamState:
43
142
  budget: telemetry_dev.CaptureBudget
143
+ # feed() sets it once the output of the event is kept, so a failure after it loses only
144
+ # metadata. A state that does not set it has every failure count as lost output.
145
+ output_recorded = False
146
+ # Set when kept metadata is lost: it flags the capture without cutting the output.
147
+ metadata_lost = False
148
+ # The stream that feeds the state sets it, for failures that feed() handles itself.
149
+ report_error: Callable[[BaseException], None]
44
150
 
45
151
  def feed(self, event: Any) -> bool | None:
46
152
  raise NotImplementedError
@@ -98,12 +204,30 @@ class ConverseStreamState(StreamState):
98
204
  def __init__(self) -> None:
99
205
  self.budget = stream_capture_budget()
100
206
  self.role = "assistant"
101
- self.blocks: dict[int, dict[str, Any]] = {}
207
+ self._blocks: dict[int, dict[str, Any]] = {}
208
+ # Appended text waits here and is joined when the blocks are read: adding each delta
209
+ # to the string copies all the text before it, which is quadratic in a long stream.
210
+ self._appended: dict[tuple[int, str], _DeltaBuffer] = {}
102
211
  self.stop_reason: str | None = None
103
212
  self.usage: dict[str, int] | None = None
104
213
  self.metadata: dict[str, Any] = {}
105
214
  self.response_model: str | None = None
106
215
 
216
+ @property
217
+ def blocks(self) -> dict[int, dict[str, Any]]:
218
+ for (index, key), parts in self._appended.items():
219
+ block = self._blocks[index]
220
+ block[key] = block[key] + parts.getvalue()
221
+ self._appended.clear()
222
+ return self._blocks
223
+
224
+ def _append(self, index: int, block: dict[str, Any], key: str, text: str) -> None:
225
+ parts = self._appended.get((index, key))
226
+ if parts is None:
227
+ block.setdefault(key, "")
228
+ parts = self._appended[(index, key)] = _DeltaBuffer()
229
+ parts.write(text)
230
+
107
231
  def feed(self, event: Any) -> None:
108
232
  if not isinstance(event, dict):
109
233
  return
@@ -161,16 +285,16 @@ class ConverseStreamState(StreamState):
161
285
  idx = index if isinstance(index, int) else 0
162
286
  delta = delta_event.get("delta") if isinstance(delta_event.get("delta"), dict) else {}
163
287
  if self.budget.accept(delta):
164
- block = self.blocks.setdefault(idx, {"kind": "text", "text": ""})
288
+ block = self._blocks.setdefault(idx, {"kind": "text", "text": ""})
165
289
  if isinstance(delta.get("text"), str):
166
290
  block["kind"] = "text"
167
- block["text"] = f"{block.get('text', '')}{delta['text']}"
291
+ self._append(idx, block, "text", delta["text"])
168
292
  tool_delta = (
169
293
  delta.get("toolUse") if isinstance(delta.get("toolUse"), dict) else None
170
294
  )
171
295
  if tool_delta and isinstance(tool_delta.get("input"), str):
172
296
  block["kind"] = "tool"
173
- block["input"] = f"{block.get('input', '')}{tool_delta['input']}"
297
+ self._append(idx, block, "input", tool_delta["input"])
174
298
  reasoning = (
175
299
  delta.get("reasoningContent")
176
300
  if isinstance(delta.get("reasoningContent"), dict)
@@ -181,7 +305,7 @@ class ConverseStreamState(StreamState):
181
305
  text = reasoning.get("text") if isinstance(reasoning.get("text"), str) else ""
182
306
  if not text and reasoning.get("redactedContent") is not None:
183
307
  text = "[redacted]"
184
- block["text"] = f"{block.get('text', '')}{text}"
308
+ self._append(idx, block, "text", text)
185
309
  image = delta.get("image")
186
310
  if isinstance(image, dict):
187
311
  content_value = block.get("content")
@@ -207,17 +331,17 @@ class ConverseStreamState(StreamState):
207
331
  current_content: list[Any] = (
208
332
  current_content_value if isinstance(current_content_value, list) else []
209
333
  )
334
+ current_content.extend(tool_result)
210
335
  block["kind"] = "content"
211
- block["content"] = {
212
- "toolResult": {**current, "content": [*current_content, *tool_result]}
213
- }
336
+ block["content"] = {"toolResult": {**current, "content": current_content}}
214
337
  citation = delta.get("citation")
215
338
  if isinstance(citation, dict):
216
339
  citations_value = block.get("citations")
217
- citations: list[Any] = (
218
- citations_value if isinstance(citations_value, list) else []
219
- )
220
- block["citations"] = [*citations, citation]
340
+ if isinstance(citations_value, list):
341
+ cast(list[Any], citations_value).append(citation)
342
+ else:
343
+ block["citations"] = [citation]
344
+ self.output_recorded = True
221
345
  stop = event.get("messageStop")
222
346
  if isinstance(stop, dict) and isinstance(stop.get("stopReason"), str):
223
347
  self.stop_reason = stop["stopReason"]
@@ -307,10 +431,18 @@ class InvokeModelStreamState(StreamState):
307
431
  return False
308
432
  try:
309
433
  parsed = json.loads(text)
310
- except json.JSONDecodeError:
311
- return bool(text)
434
+ except json.JSONDecodeError as exc:
435
+ # A blank chunk carries no output.
436
+ if not text.strip():
437
+ return False
438
+ # The chunk's output is lost. Handled here, not raised, so the chunk-timing fallback
439
+ # does not decode it again; the truncated budget keeps no later chunk.
440
+ self.budget.truncated = True
441
+ self.report_error(exc)
442
+ return True
312
443
  if self.budget.accept(parsed):
313
444
  self.chunks.append(parsed)
445
+ self.output_recorded = True
314
446
  if isinstance(parsed, dict):
315
447
  self._collect_anthropic_usage(parsed)
316
448
  if isinstance(parsed.get("amazon-bedrock-invocationMetrics"), dict):
@@ -429,7 +561,10 @@ class AgentStreamState(StreamState):
429
561
  def __init__(self, *, capture_trace: bool = False) -> None:
430
562
  self.budget = stream_capture_budget()
431
563
  self.capture_trace = capture_trace
432
- self.text = ""
564
+ self.text_fragments = _DeltaBuffer()
565
+ # AWS does not document that a chunk ends on a character boundary, so the text is
566
+ # decoded as one stream. Bytes that are not UTF-8 still raise.
567
+ self._decoder = codecs.getincrementaldecoder("utf-8")()
433
568
  # Trace metadata shares the budget but does not make the text incomplete.
434
569
  self.text_rejected = False
435
570
  self.usage: dict[str, int] = {}
@@ -456,10 +591,10 @@ class AgentStreamState(StreamState):
456
591
  return
457
592
  chunk = event.get("chunk") if isinstance(event.get("chunk"), dict) else {}
458
593
  raw = chunk.get("bytes")
459
- piece = bytes(raw).decode("utf-8") if isinstance(raw, bytes | bytearray) else raw
594
+ piece = self._decoder.decode(bytes(raw)) if isinstance(raw, bytes | bytearray) else raw
460
595
  if isinstance(piece, str) and piece:
461
596
  if self.budget.accept(piece):
462
- self.text += piece
597
+ self.text_fragments.write(piece)
463
598
  else:
464
599
  self.text_rejected = True
465
600
  return_control = (
@@ -467,26 +602,42 @@ class AgentStreamState(StreamState):
467
602
  )
468
603
  if return_control is not None:
469
604
  self.saw_return_control = True
470
- # Return control replaces the text output, so it gets its own fresh bound and
471
- # survives text that already spent the shared budget; one that alone does not fit
472
- # is dropped and the capture is marked incomplete.
473
- if stream_capture_budget().accept(return_control):
605
+ # Return control replaces the text output, so it gets its own record-sized bound
606
+ # and survives text that already spent the stream budget; it is the decoded event
607
+ # itself, not a copy, so it is not counted there. One that alone does not fit is
608
+ # dropped and the capture is marked incomplete.
609
+ if telemetry_dev.CaptureBudget().accept(return_control):
474
610
  self.return_control = return_control
475
611
  else:
476
612
  self.return_control = None
477
613
  self.return_control_rejected = True
478
614
  self.budget.truncated = True
615
+ self.output_recorded = True
479
616
  trace = event.get("trace") if isinstance(event.get("trace"), dict) else None
480
617
  if trace:
481
618
  self.trace_count += 1
482
619
  if self.capture_trace:
483
- retained = _project_trace(trace, _TRACE_PART, self.trace_capture)
620
+ try:
621
+ retained = _project_trace(trace, _TRACE_PART, self.trace_capture)
622
+ except Exception:
623
+ # The trace content is lost, as a trace dropped by the bound is, but no
624
+ # text is, so later text is still kept.
625
+ self.metadata_lost = True
626
+ raise
484
627
  if self.budget.accept(retained):
485
628
  self.traces.append(retained)
486
629
  self._collect_trace(trace)
487
630
 
488
631
  def finish(self, *, partial: bool) -> dict[str, Any]:
489
- del partial
632
+ # A stream cut short may stop inside a character; that is already an incomplete capture.
633
+ if not partial:
634
+ try:
635
+ self._decoder.decode(b"", final=True)
636
+ except UnicodeDecodeError as exc:
637
+ # The stream ended inside a character, so its last text is lost.
638
+ self.report_error(exc)
639
+ self.text_rejected = True
640
+ self.budget.truncated = True
490
641
  metadata = clean(
491
642
  {
492
643
  "trace_event_count": self.trace_count or None,
@@ -499,10 +650,11 @@ class AgentStreamState(StreamState):
499
650
  }
500
651
  )
501
652
  output: Any = None
653
+ text = self.text_fragments.getvalue()
502
654
  if self.return_control is not None:
503
655
  output = {"returnControl": self.return_control}
504
- elif self.text:
505
- output = [{"role": "assistant", "parts": [{"type": "text", "content": self.text}]}]
656
+ elif text:
657
+ output = [{"role": "assistant", "parts": [{"type": "text", "content": text}]}]
506
658
  return clean({"output": output, "usage": self.usage or None, "metadata": metadata or None})
507
659
 
508
660
  def output_truncated(self) -> bool:
@@ -560,7 +712,7 @@ class AgentStreamState(StreamState):
560
712
  class RagStreamState(StreamState):
561
713
  def __init__(self) -> None:
562
714
  self.budget = stream_capture_budget()
563
- self.text = ""
715
+ self.text_fragments = _DeltaBuffer()
564
716
  self.citation_count = 0
565
717
  self.guardrail_action: str | None = None
566
718
 
@@ -569,7 +721,7 @@ class RagStreamState(StreamState):
569
721
  return
570
722
  output = event.get("output") if isinstance(event.get("output"), dict) else {}
571
723
  if isinstance(output.get("text"), str) and self.budget.accept(output["text"]):
572
- self.text += output["text"]
724
+ self.text_fragments.write(output["text"])
573
725
  if "citation" in event:
574
726
  self.citation_count += 1
575
727
  guard = event.get("guardrail") if isinstance(event.get("guardrail"), dict) else {}
@@ -578,10 +730,11 @@ class RagStreamState(StreamState):
578
730
 
579
731
  def finish(self, *, partial: bool) -> dict[str, Any]:
580
732
  del partial
733
+ text = self.text_fragments.getvalue()
581
734
  return clean(
582
735
  {
583
- "output": [{"role": "assistant", "parts": [{"type": "text", "content": self.text}]}]
584
- if self.text
736
+ "output": [{"role": "assistant", "parts": [{"type": "text", "content": text}]}]
737
+ if text
585
738
  else None,
586
739
  "metadata": clean(
587
740
  {
@@ -640,6 +793,7 @@ class InstrumentedEventStream:
640
793
  finish: Callable[[dict[str, Any]], None],
641
794
  started_at: float,
642
795
  handle: Any,
796
+ report_error: Callable[[BaseException], None],
643
797
  ) -> None:
644
798
  self._stream = stream
645
799
  self._state = state
@@ -650,6 +804,8 @@ class InstrumentedEventStream:
650
804
  self._first = False
651
805
  self._track_output_chunks = isinstance(state, ConverseStreamState | InvokeModelStreamState)
652
806
  self._mask_output_when_incomplete = capture_masked(handle)
807
+ self._report_error = report_error
808
+ state.report_error = self._report_error
653
809
 
654
810
  def __iter__(self) -> Iterator[Any]:
655
811
  completed = False
@@ -661,19 +817,35 @@ class InstrumentedEventStream:
661
817
  self._finish_callback(
662
818
  {"time_to_first_chunk_ms": (received_at - self._started_at) * 1000}
663
819
  )
820
+ self._state.output_recorded = False
664
821
  try:
665
822
  state_has_output = self._state.feed(event)
666
- except Exception:
823
+ except Exception as exc:
824
+ self._report_error(exc)
825
+ if not self._state.output_recorded:
826
+ # The event may have carried output that is now lost. The truncated
827
+ # budget keeps no later output, so the output stays a prefix.
828
+ self._state.budget.truncated = True
829
+ if isinstance(self._state, AgentStreamState):
830
+ # The lost event may have carried text. Return control still
831
+ # replaces it.
832
+ self._state.text_rejected = True
667
833
  state_has_output = None
668
- if self._track_output_chunks and (
669
- state_has_output if state_has_output is not None else _event_has_output(event)
670
- ):
834
+ if self._track_output_chunks:
835
+ # Chunk timing must not reach the caller. A failure loses only the timing;
836
+ # when feed() already failed, the fallback can fail the same way and the
837
+ # reporter drops the repeat.
671
838
  try:
672
- record_output_chunk = getattr(self._handle, "record_output_chunk", None)
673
- if callable(record_output_chunk):
674
- record_output_chunk(received_at * 1000)
675
- except Exception:
676
- pass
839
+ if (
840
+ state_has_output
841
+ if state_has_output is not None
842
+ else _event_has_output(event)
843
+ ):
844
+ record_output_chunk = getattr(self._handle, "record_output_chunk", None)
845
+ if callable(record_output_chunk):
846
+ record_output_chunk(received_at * 1000)
847
+ except Exception as exc:
848
+ self._report_error(exc)
677
849
  yield event
678
850
  completed = True
679
851
  except GeneratorExit:
@@ -702,15 +874,26 @@ class InstrumentedEventStream:
702
874
  if self._ended:
703
875
  return
704
876
  self._ended = True
705
- fields = self._state.finish(partial=partial)
706
- if partial or self._state.budget.truncated:
707
- fields = mark_capture_incomplete(
708
- fields,
709
- self._mask_output_when_incomplete and (partial or self._state.output_truncated()),
710
- )
711
- if error is not None:
712
- fields = merge_fields(fields, error_fields(error))
713
- self._finish_callback(fields)
877
+ # The output is read before the release, which fixes the stream's bound.
878
+ try:
879
+ try:
880
+ fields = self._state.finish(partial=partial)
881
+ except Exception as exc:
882
+ # The output that the stream kept is lost.
883
+ self._report_error(exc)
884
+ self._state.budget.truncated = True
885
+ fields = {}
886
+ if partial or self._state.budget.truncated or self._state.metadata_lost:
887
+ fields = mark_capture_incomplete(
888
+ fields,
889
+ self._mask_output_when_incomplete
890
+ and (partial or self._state.output_truncated()),
891
+ )
892
+ if error is not None:
893
+ fields = merge_fields(fields, error_fields(error))
894
+ self._finish_callback(fields)
895
+ finally:
896
+ release_budget(self._state.budget)
714
897
 
715
898
 
716
899
  @dataclass(frozen=True)