Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 41 additions & 5 deletions src/rius/_serde.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,21 +349,57 @@ def serialize(value: Any) -> str:
return f"<unserializable {type(value).__name__}>"


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"<unserializable {type(value).__name__}>"


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
Expand All @@ -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))
110 changes: 109 additions & 1 deletion src/rius/normalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -98,6 +102,7 @@

from __future__ import annotations

import base64
import copy
import json
import logging
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion tests/conformance/_recording.py
Original file line number Diff line number Diff line change
@@ -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/<family>/record.py.

Expand Down
2 changes: 1 addition & 1 deletion tests/conformance/_replay.py
Original file line number Diff line number Diff line change
@@ -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).

Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/semconv/SOURCE
Original file line number Diff line number Diff line change
@@ -1 +1 @@
rius-semconv ab957f21453782a0e47350f3b6f964533785cf17
rius-semconv de35796d8a89264c10a6558c15b62a5151c9b8ed
6 changes: 4 additions & 2 deletions tests/fixtures/semconv/sdk_cases/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading