diff --git a/src/rius/_serde.py b/src/rius/_serde.py index 5d84b4e..db0caab 100644 --- a/src/rius/_serde.py +++ b/src/rius/_serde.py @@ -349,21 +349,57 @@ def serialize(value: Any) -> str: return f"" -def _bounded_dumps(value: Any) -> str: +def json_text(value: Any) -> str: + """``value`` as JSON text in the one encoding, neither stripped nor cut. + + For a value another instrumentation set structured where the conventions + also allow its JSON text: the text is then read and stripped exactly as + that string would be, so it is not cut at the attribute cap here, where + ``serialize`` would. Past the strip budget it is cut as a string that long + is (see ``_cut_past_budget``). Never raises: a value the encoder refuses + (a cycle, a key that is no string or number) is its repr, its byte + objects markers, for the strip to read. A byte object already written as + a string (a blob's base64) is a bare string in that repr, which the strip + does not read as media: a caller that converts bytes before encoding uses + :func:`strict_json_text` and falls back to this on the value as it came. + """ + text = strict_json_text(value) + if text is not None: + return text + try: + return safe_repr(value) + except Exception: + return f"" + + +def strict_json_text(value: Any) -> str | None: + """``value`` as JSON text as :func:`json_text` writes it, or None when the + encoder refuses it (a cycle, a key that is no string or number).""" + try: + return _bounded_dumps(value, _unchanged) + except Exception: + return None + + +def _unchanged(text: str) -> str: + return text + + +def _bounded_dumps(value: Any, finish: Callable[[str], str] = truncate) -> str: # A lone non-finite number is its name, as the TypeScript SDK writes a # number with String(); inside a value it is null (see _finite). if isinstance(value, float) and not math.isfinite(value): return _non_finite_name(value) try: - return _encode_within_budget(value) + return _encode_within_budget(value, finish) except ValueError: # The encoder refuses NaN and the infinities (allow_nan=False). Only # then is the value walked to replace them; a cycle raises again and # serialize falls back to repr, as it always has. - return _encode_within_budget(_finite(value)) + return _encode_within_budget(_finite(value), finish) -def _encode_within_budget(value: Any) -> str: +def _encode_within_budget(value: Any, finish: Callable[[str], str]) -> str: # iterencode without _one_shot takes the pure-Python path, which yields # chunks lazily as it walks the value; the C encoder renders everything # first. A small payload costs a few extra microseconds this way; a large @@ -386,4 +422,4 @@ def _encode_within_budget(value: Any) -> str: if size > MAX_STRIP_CHARS: kept = "".join(chunks)[:MAX_ATTR_CHARS] return _cut_past_budget(LONE_SURROGATE.sub(_escape_surrogate, kept)) - return truncate("".join(chunks)) + return finish("".join(chunks)) diff --git a/src/rius/normalization.py b/src/rius/normalization.py index 3df8e6f..b8779cd 100644 --- a/src/rius/normalization.py +++ b/src/rius/normalization.py @@ -87,6 +87,10 @@ reasons: the flattened ``llm.input_messages.N.message.*`` and ``llm.output_messages.N.message.*`` families become ``gen_ai.input.messages`` and ``gen_ai.output.messages``, which are content. +``structured_content_as_json`` comes first of all: the conventions now ask for +the content keys as maps and arrays rather than JSON strings, and every pass +after it reads them as JSON text, so a structured value is written as that +text before any of them runs. ``drop_embedding_vectors`` removes the indexed ``embedding.embeddings.N.embedding.vector`` family, which is never exported. @@ -98,6 +102,7 @@ from __future__ import annotations +import base64 import copy import json import logging @@ -120,12 +125,15 @@ from ._provider_compaction import ProviderCompactions, compactions_in_response from ._provider_response import response_json from ._serde import ( + BYTE_OBJECTS, LONE_SURROGATE, UNREADABLE, attribute_value, + json_text, loads_json, loads_object, serialize, + strict_json_text, strip_within_budget, ) from .aggregated_usage import WrappedCallTracker, move_aggregated_usage @@ -1195,6 +1203,99 @@ def compactions_from_output_value(attributes: Mapping[str, Any] | None) -> Provi return compactions_in_response(raw) +#: The content keys the GenAI conventions ask for as structured values (maps +#: and arrays) rather than JSON strings. OpenTelemetry Python keeps such a +#: value on a span from 1.45. +_STRUCTURED_CONTENT_KEYS = ( + GEN_AI_INPUT_MESSAGES, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_DEFINITIONS, +) + + +def structured_content_as_json(attributes: Mapping[str, Any] | None) -> dict[str, Any] | None: + """The content keys set as structured values, each written as its JSON text. + + Returns the rebuilt attribute dict, or None when nothing changes. Every + pass after this one, the media rebuild and the strip included, reads these + keys as JSON text, as the conventions used to define them and as this SDK + still writes them. A mapping or an array is written as that text (the one + JSON encoding, see ``_serde``), and from then on it is that string: a + span carrying the structured value and a span carrying its JSON text + export the same attributes. A string, a scalar or a lone byte object is + not structured, and is left to the passes as it is. + + A blob part's byte content (``{"type": "blob", "content": b"..."}``) is + written as its base64, as the JSON text of a blob part carries it, so the + part is rebuilt with its size and the bytes stripped like any other blob. + A byte object anywhere else is the marker, as everywhere this SDK writes + one. + """ + if not attributes: + return None + rebuilt: dict[str, Any] | None = None + for key in _STRUCTURED_CONTENT_KEYS: + value = attributes.get(key) + if not isinstance(value, (Mapping, list, tuple)): + continue + if rebuilt is None: + rebuilt = dict(attributes) + rebuilt[key] = _structured_json_text(value) + return rebuilt + + +def _structured_json_text(value: Mapping[str, Any] | list[Any] | tuple[Any, ...]) -> str: + """``value`` as JSON text, a blob part's bytes as their base64. + + The base64 form is kept only when the whole value encodes: then the text + is JSON and the media rebuild finds the blob part. A value the encoder + refuses (a cycle, a key that is no string or number) is the fallback text + of the value as it came, whose byte objects are markers. The fallback of + the converted value would carry the base64 as a bare string, which + nothing after this pass recognises as media. + """ + try: + text = strict_json_text(_plain_content(value, [])) + except RecursionError: + text = None + return json_text(value) if text is None else text + + +def _plain_content(value: Any, ancestors: list[int]) -> Any: + """``value`` with every mapping a dict and every array a list, for the encoder. + + A blob part's byte content becomes its base64 (see + :func:`structured_content_as_json`). A cycle is left as it is, for the + encoder to refuse. + """ + if not isinstance(value, (Mapping, list, tuple)): + return value + if id(value) in ancestors: + return value + ancestors.append(id(value)) + try: + if isinstance(value, Mapping): + plain = {key: _plain_content(item, ancestors) for key, item in value.items()} + content = plain.get("content") + if plain.get("type") == "blob" and isinstance(content, BYTE_OBJECTS): + encoded = _base64(content) + if encoded is not None: + plain["content"] = encoded + return plain + return [_plain_content(item, ancestors) for item in value] + finally: + ancestors.pop() + + +def _base64(content: bytes | bytearray | memoryview) -> str | None: + """A byte object's base64, or None when its bytes cannot be read (a released memoryview).""" + try: + return base64.b64encode(content).decode("ascii") + except (ValueError, TypeError): + return None + + #: The message keys whose parts a normalizer builds (the contract's #: ``raw_payloads.message_keys`` that hold semconv JSON). The system #: instructions are read and rewritten here, never emitted. @@ -1345,7 +1446,14 @@ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult: return self._inner.export([self._normalized(span) for span in spans]) def _normalized(self, span: ReadableSpan) -> ReadableSpan: - new_attributes = self._table.normalize(span.attributes) + # First, so every pass below reads the content keys as JSON text, + # however the instrumentation set them. + structured = structured_content_as_json(span.attributes) + new_attributes = self._table.normalize( + span.attributes if structured is None else structured + ) + if new_attributes is None: + new_attributes = structured # After the table, which maps the dialects' usage onto the canonical # keys, so a zero it mapped goes with the native ones. On every span, # the SDK's own generations included, not only third-party ones. diff --git a/tests/conformance/_recording.py b/tests/conformance/_recording.py index 15c7248..547bc1c 100644 --- a/tests/conformance/_recording.py +++ b/tests/conformance/_recording.py @@ -1,4 +1,4 @@ -# Vendored from rius-semconv ab957f21453782a0e47350f3b6f964533785cf17 fixtures/_recording.py by +# Vendored from rius-semconv de35796d8a89264c10a6558c15b62a5151c9b8ed fixtures/_recording.py by # scripts/sync-semconv-fixtures.sh. Do not edit: change it in rius-semconv. """Shared helpers for the recorders under fixtures//record.py. diff --git a/tests/conformance/_replay.py b/tests/conformance/_replay.py index 074047d..62ae768 100644 --- a/tests/conformance/_replay.py +++ b/tests/conformance/_replay.py @@ -1,4 +1,4 @@ -# Vendored from rius-semconv ab957f21453782a0e47350f3b6f964533785cf17 fixtures/_replay.py by +# Vendored from rius-semconv de35796d8a89264c10a6558c15b62a5151c9b8ed fixtures/_replay.py by # scripts/sync-semconv-fixtures.sh. Do not edit: change it in rius-semconv. """Turn a stored recording back into OpenTelemetry ReadableSpans (Python). diff --git a/tests/fixtures/semconv/SOURCE b/tests/fixtures/semconv/SOURCE index 63631e0..5253e06 100644 --- a/tests/fixtures/semconv/SOURCE +++ b/tests/fixtures/semconv/SOURCE @@ -1 +1 @@ -rius-semconv ab957f21453782a0e47350f3b6f964533785cf17 +rius-semconv de35796d8a89264c10a6558c15b62a5151c9b8ed diff --git a/tests/fixtures/semconv/sdk_cases/README.md b/tests/fixtures/semconv/sdk_cases/README.md index 05ad26c..b3c04f1 100644 --- a/tests/fixtures/semconv/sdk_cases/README.md +++ b/tests/fixtures/semconv/sdk_cases/README.md @@ -17,6 +17,7 @@ code, so the two SDKs agree with each other by agreeing with these files. | `env.json` | `RIUS_*` variables: booleans (blank or unrecognised keeps the default), blank strings (unset), numbers (as Python's `float()` reads them, clamped to range). | `resolve_config()` / `resolveConfig({}, env)` | | `resource.json` | `OTEL_RESOURCE_ATTRIBUTES` merged under the SDK's own resource keys, and the `unknown_service` placeholder never stamped as an agent name. | `init()` | | `anthropic_error_type.json` | `error.type` on a span the Anthropic SDK made itself: the exception class it raises for the HTTP status, for the statuses every Anthropic client in both languages maps alike (400, 401, 403, 404, 409, 422, 429, and every 5xx but 503, 504 and 529); anything else kept. | the SDK's span normalization | +| `structured_content.json` | `gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions` and `gen_ai.tool.definitions` set by another instrumentation as maps and arrays: each written as its compact JSON and then normalized as that string, so it exports as its JSON string does; a blob part's byte content as its base64, any other byte object the marker. | the SDK's span normalization | Each file holds an `about`, which says what a case's fields mean, and `cases`, each with a unique `name`. A field an SDK spells differently is named @@ -50,8 +51,9 @@ mapping with one tagged key, which each SDK's test decodes: A case belongs here only when both SDKs must give the same result. Where the languages differ by nature it is left out: JavaScript has one number type, so -`1.0` is `"1"` in TypeScript and `"1.0"` in Python; Python writes a boolean a -mask returns for the status description as `True`, TypeScript as `true`. +`1.0` is `"1"` in TypeScript and `"1.0"` in Python, and `1e-7` is `"1e-7"` in +TypeScript and `"1e-07"` in Python, inside JSON text as anywhere else; Python +writes a boolean a mask returns for the status description as `True`, TypeScript as `true`. Behaviour only one SDK has is tested in that SDK alone. ## Changing a case diff --git a/tests/fixtures/semconv/sdk_cases/structured_content.json b/tests/fixtures/semconv/sdk_cases/structured_content.json new file mode 100644 index 0000000..1fa57c4 --- /dev/null +++ b/tests/fixtures/semconv/sdk_cases/structured_content.json @@ -0,0 +1,399 @@ +{ + "about": "How an SDK exports the content keys another instrumentation set as structured values (maps and arrays) rather than JSON strings, as the GenAI conventions now ask: gen_ai.input.messages, gen_ai.output.messages, gen_ai.system_instructions and gen_ai.tool.definitions. Each such value is written as its JSON text in the one encoding (compact, raw UTF-8, no HTML escaping, a non-finite number null) and then normalized exactly as that string would be, so a structured value and its JSON string export the same attributes. A byte object that is a blob part's content is written as its base64, as a blob part's JSON carries it, at any depth, so a part in `parts` is rebuilt with its byte_size and its bytes stripped, and one elsewhere (inside a tool call response, say) has its base64 stripped to the blob's marker; any other byte object is the marker. A data URL in a uri part is rebuilt as a blob part, as in its JSON string. A string, a number or a boolean is not structured and is kept; a lone byte object is the marker. A float's text is the SDK's own (an integral float is `2.0` in Python and `2` in TypeScript), so the cases hold no integral float and no exponent. `attributes` are the span's attributes as it ends, as the third-party instrumentation set them, and `expected` every attribute the span is exported with, after normalization and before masking. Keys are never integer-like, since JavaScript orders those first in an object.", + "cases": [ + { + "name": "input_messages_structured", + "attributes": { + "gen_ai.input.messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "content": "Weather in Zürich? & 天気" + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "tool_call", + "id": "call_1", + "name": "get_weather", + "arguments": { + "city": "Zürich", + "days": 2, + "units": null + } + } + ] + }, + { + "role": "tool", + "parts": [ + { + "type": "tool_call_response", + "id": "call_1", + "response": { + "temperature": 21.5, + "sunny": true + } + } + ] + } + ] + }, + "expected": { + "gen_ai.input.messages": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Weather in Zürich? & 天気\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"tool_call\",\"id\":\"call_1\",\"name\":\"get_weather\",\"arguments\":{\"city\":\"Zürich\",\"days\":2,\"units\":null}}]},{\"role\":\"tool\",\"parts\":[{\"type\":\"tool_call_response\",\"id\":\"call_1\",\"response\":{\"temperature\":21.5,\"sunny\":true}}]}]" + } + }, + { + "name": "input_messages_as_their_json_string", + "attributes": { + "gen_ai.input.messages": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Weather in Zürich? & 天気\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"tool_call\",\"id\":\"call_1\",\"name\":\"get_weather\",\"arguments\":{\"city\":\"Zürich\",\"days\":2,\"units\":null}}]},{\"role\":\"tool\",\"parts\":[{\"type\":\"tool_call_response\",\"id\":\"call_1\",\"response\":{\"temperature\":21.5,\"sunny\":true}}]}]" + }, + "expected": { + "gen_ai.input.messages": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Weather in Zürich? & 天気\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"tool_call\",\"id\":\"call_1\",\"name\":\"get_weather\",\"arguments\":{\"city\":\"Zürich\",\"days\":2,\"units\":null}}]},{\"role\":\"tool\",\"parts\":[{\"type\":\"tool_call_response\",\"id\":\"call_1\",\"response\":{\"temperature\":21.5,\"sunny\":true}}]}]" + } + }, + { + "name": "output_messages_blob_with_byte_content", + "attributes": { + "gen_ai.output.messages": [ + { + "role": "assistant", + "parts": [ + { + "type": "text", + "content": "Here it is" + }, + { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "content": { + "$bytes": 8 + } + } + ] + } + ] + }, + "expected": { + "gen_ai.output.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Here it is\"},{\"type\":\"blob\",\"modality\":\"image\",\"mime_type\":\"image/png\",\"byte_size\":8,\"stripped_reason\":\"not_captured\"}]}]" + } + }, + { + "name": "output_messages_blob_with_base64_content", + "attributes": { + "gen_ai.output.messages": [ + { + "role": "assistant", + "parts": [ + { + "type": "text", + "content": "Here it is" + }, + { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "content": "AAAAAAAAAAA=" + } + ] + } + ] + }, + "expected": { + "gen_ai.output.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Here it is\"},{\"type\":\"blob\",\"modality\":\"image\",\"mime_type\":\"image/png\",\"byte_size\":8,\"stripped_reason\":\"not_captured\"}]}]" + } + }, + { + "name": "system_instructions_structured", + "attributes": { + "gen_ai.system_instructions": [ + { + "type": "text", + "content": "Be brief." + }, + { + "type": "text", + "content": "Answer in French." + } + ] + }, + "expected": { + "gen_ai.system_instructions": "[{\"type\":\"text\",\"content\":\"Be brief.\"},{\"type\":\"text\",\"content\":\"Answer in French.\"}]" + } + }, + { + "name": "system_instructions_array_of_strings", + "attributes": { + "gen_ai.system_instructions": [ + "Be brief.", + "Answer in French." + ] + }, + "expected": { + "gen_ai.system_instructions": "[\"Be brief.\",\"Answer in French.\"]" + } + }, + { + "name": "system_instructions_blob_with_byte_content", + "attributes": { + "gen_ai.system_instructions": [ + { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "content": { + "$bytes": 8 + } + } + ] + }, + "expected": { + "gen_ai.system_instructions": "[{\"type\":\"blob\",\"modality\":\"image\",\"mime_type\":\"image/png\",\"byte_size\":8,\"stripped_reason\":\"not_captured\"}]" + } + }, + { + "name": "tool_definitions_structured_non_finite_number", + "attributes": { + "gen_ai.tool.definitions": [ + { + "type": "function", + "name": "get_weather", + "description": "Weather for a city", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + }, + "days": { + "type": "integer", + "default": { + "$number": "NaN" + } + } + }, + "required": [ + "city" + ] + } + } + ] + }, + "expected": { + "gen_ai.tool.definitions": "[{\"type\":\"function\",\"name\":\"get_weather\",\"description\":\"Weather for a city\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"},\"days\":{\"type\":\"integer\",\"default\":null}},\"required\":[\"city\"]}}]" + } + }, + { + "name": "byte_object_outside_a_blob_part", + "attributes": { + "gen_ai.input.messages": [ + { + "role": "user", + "parts": [ + { + "type": "custom", + "data": { + "$bytes": 4 + } + } + ] + } + ] + }, + "expected": { + "gen_ai.input.messages": "[{\"role\":\"user\",\"parts\":[{\"type\":\"custom\",\"data\":\"[stripped unknown 4 bytes]\"}]}]" + } + }, + { + "name": "every_content_key_at_once", + "attributes": { + "gen_ai.input.messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "content": "Weather in Zürich? & 天気" + } + ] + } + ], + "gen_ai.output.messages": [ + { + "role": "assistant", + "parts": [ + { + "type": "tool_call", + "id": "call_1", + "name": "get_weather", + "arguments": { + "city": "Zürich", + "days": 2, + "units": null + } + } + ] + } + ], + "gen_ai.system_instructions": [ + { + "type": "text", + "content": "Be brief." + } + ], + "gen_ai.tool.definitions": [ + { + "type": "function", + "name": "get_weather", + "description": "Weather for a city", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + }, + "days": { + "type": "integer", + "default": { + "$number": "NaN" + } + } + }, + "required": [ + "city" + ] + } + } + ] + }, + "expected": { + "gen_ai.input.messages": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Weather in Zürich? & 天気\"}]}]", + "gen_ai.output.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"tool_call\",\"id\":\"call_1\",\"name\":\"get_weather\",\"arguments\":{\"city\":\"Zürich\",\"days\":2,\"units\":null}}]}]", + "gen_ai.system_instructions": "[{\"type\":\"text\",\"content\":\"Be brief.\"}]", + "gen_ai.tool.definitions": "[{\"type\":\"function\",\"name\":\"get_weather\",\"description\":\"Weather for a city\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"},\"days\":{\"type\":\"integer\",\"default\":null}},\"required\":[\"city\"]}}]" + } + }, + { + "name": "lone_byte_object", + "attributes": { + "gen_ai.input.messages": { + "$bytes": 4 + } + }, + "expected": { + "gen_ai.input.messages": "[stripped unknown 4 bytes]" + } + }, + { + "name": "tool_definitions_non_integral_floats", + "attributes": { + "gen_ai.tool.definitions": [ + { + "type": "function", + "name": "set_thermostat", + "description": "Set a target temperature", + "parameters": { + "type": "object", + "properties": { + "celsius": { + "type": "number", + "minimum": -12.5, + "maximum": 32.75, + "default": 21.5 + }, + "step": { + "type": "number", + "default": 0.25 + } + }, + "required": [ + "celsius" + ] + } + } + ] + }, + "expected": { + "gen_ai.tool.definitions": "[{\"type\":\"function\",\"name\":\"set_thermostat\",\"description\":\"Set a target temperature\",\"parameters\":{\"type\":\"object\",\"properties\":{\"celsius\":{\"type\":\"number\",\"minimum\":-12.5,\"maximum\":32.75,\"default\":21.5},\"step\":{\"type\":\"number\",\"default\":0.25}},\"required\":[\"celsius\"]}}]" + } + }, + { + "name": "input_messages_uri_part_with_data_url", + "attributes": { + "gen_ai.input.messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "content": "What is in this image?" + }, + { + "type": "uri", + "modality": "image", + "mime_type": "image/png", + "uri": "data:image/png;base64,AAAAAAAAAAA=" + } + ] + } + ] + }, + "expected": { + "gen_ai.input.messages": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"What is in this image?\"},{\"type\":\"blob\",\"modality\":\"image\",\"mime_type\":\"image/png\",\"byte_size\":8,\"stripped_reason\":\"not_captured\"}]}]" + } + }, + { + "name": "blob_nested_outside_parts", + "attributes": { + "gen_ai.input.messages": [ + { + "role": "tool", + "parts": [ + { + "type": "tool_call_response", + "id": "call_1", + "response": { + "screenshot": { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "content": { + "$bytes": 8 + } + } + } + } + ] + } + ] + }, + "expected": { + "gen_ai.input.messages": "[{\"role\":\"tool\",\"parts\":[{\"type\":\"tool_call_response\",\"id\":\"call_1\",\"response\":{\"screenshot\":{\"type\":\"blob\",\"modality\":\"image\",\"mime_type\":\"image/png\",\"content\":\"[stripped image/png 8 bytes]\"}}}]}]" + } + }, + { + "name": "string_value_kept", + "attributes": { + "gen_ai.input.messages": "plain text, not JSON" + }, + "expected": { + "gen_ai.input.messages": "plain text, not JSON" + } + }, + { + "name": "scalar_value_kept", + "attributes": { + "gen_ai.input.messages": 3 + }, + "expected": { + "gen_ai.input.messages": 3 + } + } + ] +} diff --git a/tests/test_normalization_structured_content.py b/tests/test_normalization_structured_content.py new file mode 100644 index 0000000..3fc9982 --- /dev/null +++ b/tests/test_normalization_structured_content.py @@ -0,0 +1,255 @@ +"""Content attributes another instrumentation sets as structured values. + +The GenAI conventions now ask for ``gen_ai.input.messages``, +``gen_ai.output.messages``, ``gen_ai.system_instructions`` and +``gen_ai.tool.definitions`` to be maps and arrays rather than JSON strings, +and OpenTelemetry Python keeps such values on a span from 1.45. The exporter +writes each one as the JSON text this SDK writes for the same content, then +treats it exactly as that string: its media parts are rebuilt and stripped, so +no byte of a blob leaves. A span carrying the string and a span carrying the +structured value export the same attributes. + +The spans are built directly rather than through a tracer: OpenTelemetry +before 1.45 drops a mapping attribute when it is set, and the floor CI job runs +this suite on 1.25. +""" + +from __future__ import annotations + +import base64 +import json +import math +from types import MappingProxyType +from typing import Any + +import pytest +from opentelemetry.sdk.trace import ReadableSpan, TracerProvider +from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter +from opentelemetry.trace import SpanContext + +from rius._serde import MAX_ATTR_CHARS, byte_object_marker +from rius.normalization import NormalizingSpanExporter +from rius.semconv import ( + GEN_AI_INPUT_MESSAGES, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_DEFINITIONS, +) + +PNG = bytes(range(8)) + + +def _export(attributes: dict[str, Any]) -> dict[str, Any]: + context = SpanContext(trace_id=1, span_id=2, is_remote=False) + span = ReadableSpan(name="chat", context=context, attributes=attributes) + sink = InMemorySpanExporter() + NormalizingSpanExporter(sink).export([span]) + [out] = sink.get_finished_spans() + return dict(out.attributes or {}) + + +def _json(value: Any) -> str: + return json.dumps(value, separators=(",", ":"), ensure_ascii=False) + + +_MESSAGES = [ + {"role": "user", "parts": [{"type": "text", "content": "Weather in Paris? & é"}]}, + { + "role": "assistant", + "parts": [ + { + "type": "tool_call", + "id": "call_1", + "name": "get_weather", + "arguments": {"city": "Paris", "days": 2}, + } + ], + }, +] + + +@pytest.mark.parametrize( + "key", [GEN_AI_INPUT_MESSAGES, GEN_AI_OUTPUT_MESSAGES, GEN_AI_SYSTEM_INSTRUCTIONS] +) +def test_a_structured_message_key_is_written_as_its_json(key: str) -> None: + value = _MESSAGES if key != GEN_AI_SYSTEM_INSTRUCTIONS else _MESSAGES[0]["parts"] + exported = _export({key: value}) + assert exported[key] == _json(value) + + +def test_structured_tool_definitions_are_written_as_their_json() -> None: + tools = [ + { + "type": "function", + "name": "get_weather", + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}, + } + ] + assert _export({GEN_AI_TOOL_DEFINITIONS: tools})[GEN_AI_TOOL_DEFINITIONS] == _json(tools) + + +def test_the_value_as_opentelemetry_stores_it_exports_as_the_string_does() -> None: + # OpenTelemetry 1.45 stores a list as a tuple and keeps byte objects, so + # the value a third-party span carries is this shape, not the one it set. + stored = ( + { + "role": "user", + "parts": ( + {"type": "text", "content": "describe"}, + {"type": "blob", "modality": "image", "mime_type": "image/png", "content": PNG}, + ), + }, + ) + as_string = _json( + [ + { + "role": "user", + "parts": [ + {"type": "text", "content": "describe"}, + { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "content": base64.b64encode(PNG).decode(), + }, + ], + } + ] + ) + structured = _export({GEN_AI_INPUT_MESSAGES: stored, "other": "x"}) + assert structured == _export({GEN_AI_INPUT_MESSAGES: as_string, "other": "x"}) + parts = json.loads(structured[GEN_AI_INPUT_MESSAGES])[0]["parts"] + assert parts[1] == { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "byte_size": 8, + "stripped_reason": "not_captured", + } + + +def test_a_blob_in_the_system_instructions_and_tool_definitions_loses_its_bytes() -> None: + blob = {"type": "blob", "mime_type": "image/png", "content": PNG} + exported = _export({GEN_AI_SYSTEM_INSTRUCTIONS: [blob], GEN_AI_TOOL_DEFINITIONS: [blob]}) + encoded = base64.b64encode(PNG).decode() + for key in (GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_DEFINITIONS): + assert encoded not in exported[key] + assert json.loads(exported[key])[0]["type"] == "blob" + + +def test_a_byte_object_anywhere_else_is_the_marker() -> None: + exported = _export( + {GEN_AI_OUTPUT_MESSAGES: [{"role": "assistant", "parts": [{"type": "x", "data": PNG}]}]} + ) + part = json.loads(exported[GEN_AI_OUTPUT_MESSAGES])[0]["parts"][0] + assert part == {"type": "x", "data": byte_object_marker(PNG)} + + +def test_a_memoryview_blob_is_read_as_its_bytes() -> None: + blob = {"type": "blob", "mime_type": "image/png", "content": memoryview(PNG)} + exported = _export({GEN_AI_SYSTEM_INSTRUCTIONS: [blob]}) + assert json.loads(exported[GEN_AI_SYSTEM_INSTRUCTIONS])[0]["byte_size"] == 8 + + +def test_any_mapping_is_an_object() -> None: + value = [MappingProxyType({"type": "text", "content": "hi"})] + assert _export({GEN_AI_SYSTEM_INSTRUCTIONS: value})[GEN_AI_SYSTEM_INSTRUCTIONS] == _json( + [{"type": "text", "content": "hi"}] + ) + + +def test_a_non_finite_number_inside_is_null() -> None: + tools = [{"name": "t", "parameters": {"default": math.nan, "max": math.inf}}] + exported = _export({GEN_AI_TOOL_DEFINITIONS: tools}) + assert ( + exported[GEN_AI_TOOL_DEFINITIONS] + == '[{"name":"t","parameters":{"default":null,"max":null}}]' + ) + + +def test_an_array_of_strings_is_its_json_array() -> None: + exported = _export({GEN_AI_SYSTEM_INSTRUCTIONS: ("be brief", "be kind")}) + assert exported[GEN_AI_SYSTEM_INSTRUCTIONS] == '["be brief","be kind"]' + + +def test_a_large_value_is_not_cut_at_the_attribute_cap() -> None: + # A string under the strip budget keeps its length; so does the same + # content as a structured value. + text = "word " * (MAX_ATTR_CHARS // 2) + value = [{"role": "user", "parts": [{"type": "text", "content": text}]}] + exported = _export({GEN_AI_INPUT_MESSAGES: value}) + assert exported[GEN_AI_INPUT_MESSAGES] == _json(value) + assert exported == _export({GEN_AI_INPUT_MESSAGES: _json(value)}) + + +def test_a_value_that_cannot_be_encoded_never_fails_the_export() -> None: + cycle: list[Any] = [{"type": "text", "content": "hi"}] + cycle.append(cycle) + exported = _export({GEN_AI_INPUT_MESSAGES: cycle, "other": "x"}) + assert isinstance(exported[GEN_AI_INPUT_MESSAGES], str) + assert exported["other"] == "x" + + +def test_a_byte_key_never_fails_the_export_or_leaks_its_bytes() -> None: + exported = _export({GEN_AI_INPUT_MESSAGES: [{b"k": PNG}]}) + assert isinstance(exported[GEN_AI_INPUT_MESSAGES], str) + assert "\\x00\\x01" not in exported[GEN_AI_INPUT_MESSAGES] + + +_IMAGE = bytes(range(256)) * 40 +_IMAGE_BASE64 = base64.b64encode(_IMAGE).decode("ascii") + + +def _cyclic_messages_with_a_blob() -> list[Any]: + blob = {"type": "blob", "mime_type": "image/png", "content": _IMAGE} + messages: list[Any] = [{"role": "user", "parts": [blob]}] + messages[0]["self"] = messages + return messages + + +@pytest.mark.parametrize( + "value", + [ + pytest.param(_cyclic_messages_with_a_blob(), id="blob-in-a-cycle"), + pytest.param( + [{b"k": 1, "type": "blob", "mime_type": "image/png", "content": _IMAGE}], + id="blob-in-a-byte-keyed-map", + ), + pytest.param( + [{("a", 1): 1, "parts": [{"type": "blob", "content": _IMAGE}]}], + id="blob-beside-a-tuple-key", + ), + ], +) +def test_a_blob_in_a_value_that_cannot_be_encoded_never_leaks_its_bytes(value: Any) -> None: + exported = _export({GEN_AI_INPUT_MESSAGES: value}) + text = exported[GEN_AI_INPUT_MESSAGES] + assert isinstance(text, str) + assert _IMAGE_BASE64[:64] not in text + assert "\\x00\\x01" not in text + assert "[stripped" in text + + +@pytest.mark.parametrize("value", ["already text", 3, True, PNG]) +def test_a_value_that_is_not_structured_is_not_reencoded(value: Any) -> None: + exported = _export({GEN_AI_INPUT_MESSAGES: value}) + expected = byte_object_marker(PNG) if value is PNG else value + assert exported[GEN_AI_INPUT_MESSAGES] == expected + + +def test_other_keys_keep_their_structured_values() -> None: + exported = _export({"app.payload": {"a": [1, 2]}}) + assert exported["app.payload"] == {"a": [1, 2]} + + +def test_a_span_from_a_real_tracer_is_converted() -> None: + probe = TracerProvider().get_tracer("probe").start_span("p", attributes={"m": {"a": 1}}) + if "m" not in (probe.attributes or {}): + pytest.skip("this OpenTelemetry SDK drops mapping attributes (before 1.45)") + sink = InMemorySpanExporter() + tracer = TracerProvider().get_tracer("third.party") + span = tracer.start_span("chat", attributes={GEN_AI_INPUT_MESSAGES: _MESSAGES}) + span.end() + NormalizingSpanExporter(sink).export([span]) # type: ignore[list-item] + [out] = sink.get_finished_spans() + assert (out.attributes or {})[GEN_AI_INPUT_MESSAGES] == _json(_MESSAGES) diff --git a/tests/test_sdk_cases.py b/tests/test_sdk_cases.py index 47cc39b..05fe933 100644 --- a/tests/test_sdk_cases.py +++ b/tests/test_sdk_cases.py @@ -5,8 +5,9 @@ both SDKs are held to one expected result for each: how input.value and output.value are written, how set_attribute encodes a value, how messages and rius.context.sizes are recorded, what the masking exporter keeps, how RIUS_* -variables resolve, how the resource takes in OTEL_RESOURCE_ATTRIBUTES and how -error.type is named on the Anthropic SDK's own spans. +variables resolve, how the resource takes in OTEL_RESOURCE_ATTRIBUTES, how +error.type is named on the Anthropic SDK's own spans and how a content key +another instrumentation set as a structured value is exported. Their README describes the format, including the tagged values JSON cannot hold (``{"$bytes": N}``, ``{"$number": "NaN"}``). """ @@ -21,14 +22,15 @@ from typing import Any import pytest -from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace import ReadableSpan, TracerProvider from opentelemetry.sdk.trace.export import SimpleSpanProcessor from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter -from opentelemetry.trace import Status, StatusCode +from opentelemetry.trace import SpanContext, Status, StatusCode import rius from rius.config import resolve_config from rius.masking import MaskingSpanExporter +from rius.normalization import NormalizingSpanExporter CASES = Path(__file__).parent / "fixtures" / "semconv" / "sdk_cases" @@ -123,6 +125,21 @@ def test_anthropic_error_type(case: dict[str, Any], exporter: _Spans) -> None: assert exporter.attributes()["error.type"] == case["expected"] +@pytest.mark.parametrize("case", _cases("structured_content"), ids=_ids("structured_content")) +def test_structured_content(case: dict[str, Any]) -> None: + # Built directly rather than through a tracer: OpenTelemetry before 1.45 + # drops a mapping attribute when it is set, and the floor CI job runs + # this suite on 1.25. + attributes = {key: _value(raw) for key, raw in case["attributes"].items()} + context = SpanContext(trace_id=1, span_id=2, is_remote=False) + sink = InMemorySpanExporter() + NormalizingSpanExporter(sink).export( + [ReadableSpan(name="chat", context=context, attributes=attributes)] + ) + (span,) = sink.get_finished_spans() + assert dict(span.attributes or {}) == case["expected"] + + @pytest.mark.parametrize("case", _cases("attributes"), ids=_ids("attributes")) def test_set_attribute(case: dict[str, Any], exporter: _Spans) -> None: span = rius.start_span("s")