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
51 changes: 43 additions & 8 deletions src/rius/_media.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,20 +239,45 @@ def replacement(mime: str | None, byte_size: int | None) -> str:
_REPLACEMENT_BETWEEN, _REPLACEMENT_TAIL = _rest.split("<byte_size>")


def is_replacement(value: str) -> bool:
"""Already a complete replacement: never stripped again, never context.
#: 2^53 - 1 has 16 digits, so a run with more significant digits is past it.
_MAX_BYTE_SIZE_DIGITS = 16

The format with a mime that is unknown or token/token and a byte_size of
ASCII digits or unknown; anything that only looks like one is a token.

def parse_replacement(value: str) -> tuple[str | None, int | None] | None:
"""The mime and byte_size a complete replacement names, each None when
unknown; None when ``value`` is no complete replacement (see
``is_replacement``).

The byte_size is the digit run read as a decimal number, leading zeros of
any length allowed. A run with more significant digits than 2^53 - 1 has
is None and is never converted: ``int()`` refuses a string over 4300
digits, and this runs inside the export chain. The caller still bounds a
shorter one to 2^53 - 1, as for a byte_size the part has.
"""
head, between, tail = _REPLACEMENT_HEAD, _REPLACEMENT_BETWEEN, _REPLACEMENT_TAIL
if len(value) < len(head) + len(between) + len(tail):
return False
return None
if not (value.startswith(head) and value.endswith(tail)):
return False
return None
mime, sep, size = value[len(head) : len(value) - len(tail)].rpartition(between)
digits = bool(size) and all("0" <= ch <= "9" for ch in size)
return bool(sep) and (mime == UNKNOWN or is_mime(mime)) and (digits or size == UNKNOWN)
if not (sep and (mime == UNKNOWN or is_mime(mime)) and (digits or size == UNKNOWN)):
return None
byte_size = None
if digits:
significant = size.lstrip("0") or "0"
if len(significant) <= _MAX_BYTE_SIZE_DIGITS:
byte_size = int(significant)
return (None if mime == UNKNOWN else mime), byte_size


def is_replacement(value: str) -> bool:
"""Already a complete replacement: never stripped again, never context.

The format with a mime that is unknown or token/token and a byte_size of
ASCII digits or unknown; anything that only looks like one is a token.
"""
return parse_replacement(value) is not None


# --- the strip ---------------------------------------------------------------
Expand Down Expand Up @@ -1445,7 +1470,9 @@ def native_part(part: Part) -> Part | None:

* A blob carrying content becomes a stripped blob: sized from it,
``not_captured``, its modality from its MIME type first (some producers
label every file an image), else the one it has, else document.
label every file an image), else the one it has, else document. Content
that is a complete replacement gives its size, and its mime when the
part has no valid MIME type.
* Any other part keeps a modality it has, else takes one from its MIME
type, else (a uri) from its filename extension, else document. A blob
without content keeps a valid size and stripped_reason.
Expand All @@ -1457,6 +1484,14 @@ def native_part(part: Part) -> Part | None:
part_type = part.get("type")
mime = part.get("mime_type")
if part_type == "blob" and isinstance(part.get("content"), str):
replaced = parse_replacement(part["content"])
if replaced is not None:
# Bytes a strip already measured (an OTLP bytes value, a byte
# object): the size the base64 of the same bytes would give, and
# the part's own MIME type before the replacement's.
replaced_mime, size = replaced
kept = mime if is_mime(mime) else replaced_mime
return blob_part(own or "document", kept, safe_size(size), NOT_CAPTURED)
return base64_blob(part["content"], own or "document", mime)
if part_type == "uri" and is_data_url(part.get("uri")):
return data_url_blob(part["uri"], own or "document", mime)
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 d826d04f4dbb87171ff763b65515a4b6355d81c5 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 d826d04f4dbb87171ff763b65515a4b6355d81c5 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 d826d04f4dbb87171ff763b65515a4b6355d81c5
54 changes: 53 additions & 1 deletion tests/fixtures/semconv/media_parts.yaml

Large diffs are not rendered by default.

92 changes: 92 additions & 0 deletions tests/test_byte_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,3 +519,95 @@ def test_model_parameters_holding_byte_objects(exported_spans: InMemorySpanExpor
assert written
assert not any(_leaks(str(v)) for v in written.values())
assert all(MARKER in str(v) for v in written.values()), written


def test_a_blob_of_bytes_in_messages_is_stored_as_its_base64_twin() -> None:
# The SDK's serializer writes the bytes as the marker and strips the
# base64 to a replacement, and the exporter rebuilds each blob with the
# size its replacement names: both forms keep byte_size and store alike.
def messages(content: Any) -> str:
blob = {"type": "blob", "modality": "image", "mime_type": "image/png", "content": content}
return serialize([{"role": "user", "parts": [blob]}])

inner = InMemorySpanExporter()
client = init(span_exporter=inner, set_global=False)
for name, content in (("bytes", PNG), ("base64", "iVBORw0KGgo=")):
span = client.get_tracer().start_span(name)
span.set_attribute("gen_ai.input.messages", messages(content))
span.end()
client.flush()
stored = {
s.name: (s.attributes or {})["gen_ai.input.messages"] for s in inner.get_finished_spans()
}
assert stored["bytes"] == stored["base64"]
[part] = json.loads(str(stored["bytes"]))[0]["parts"]
assert part == {
"type": "blob",
"modality": "image",
"mime_type": "image/png",
"byte_size": 8,
"stripped_reason": "not_captured",
}


#: A complete replacement whose size has more digits than Python's int()
#: converts from a string (4300, leading zeros included).
_LONG_REPLACEMENT = "[stripped unknown " + "9" * 4301 + " bytes]"


@pytest.mark.parametrize(
("key", "value", "stored"),
[
pytest.param(
"gen_ai.input.messages",
json.dumps(
[{"role": "user", "parts": [{"type": "blob", "content": _LONG_REPLACEMENT}]}]
),
# Rebuilt with no byte_size: the size is past 2^53 - 1.
'"parts": [{"type":"blob","modality":"document","stripped_reason":"not_captured"}]',
id="blob-content",
),
pytest.param(
"output",
json.dumps({"mime_type": _LONG_REPLACEMENT, "data": "QUJD"}),
_LONG_REPLACEMENT,
id="mime-type",
),
pytest.param(
"output",
json.dumps({"type": "image", "source_type": "base64", "data": _LONG_REPLACEMENT}),
_LONG_REPLACEMENT,
id="data",
),
],
)
def test_a_replacement_with_a_long_digit_run_is_exported(key: str, value: str, stored: str) -> None:
# int() refuses such a run, and the strip asks whether each of these
# strings is a replacement: the export must still deliver the span.
inner = InMemorySpanExporter()
client = init(span_exporter=inner, set_global=False)
span = client.get_tracer().start_span("long")
span.set_attribute(key, value)
span.end()
client.flush()
[exported] = inner.get_finished_spans()
assert stored in str((exported.attributes or {})[key])


def test_a_replacement_with_thousands_of_leading_zeros_names_its_size() -> None:
content = "[stripped unknown " + "0" * 5000 + "8 bytes]"
value = json.dumps([{"role": "user", "parts": [{"type": "blob", "content": content}]}])
inner = InMemorySpanExporter()
client = init(span_exporter=inner, set_global=False)
span = client.get_tracer().start_span("zeros")
span.set_attribute("gen_ai.input.messages", value)
span.end()
client.flush()
[exported] = inner.get_finished_spans()
[part] = json.loads(str((exported.attributes or {})["gen_ai.input.messages"]))[0]["parts"]
assert part == {
"type": "blob",
"modality": "document",
"byte_size": 8,
"stripped_reason": "not_captured",
}
53 changes: 53 additions & 0 deletions tests/test_media_parts.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,59 @@ def test_a_part_with_canonical_values_is_canonical(part: dict[str, Any]) -> None
},
"blob_with_no_content_and_no_stripped_reason": {"type": "blob", "modality": "audio"},
"blob_with_content_that_is_not_a_string": {"type": "blob", "content": 5, "byte_size": 8.0},
"blob_with_content_that_is_the_bytes_marker": {
"type": "blob",
"modality": "image",
"mime_type": "image/png",
"content": "[stripped unknown 16 bytes]",
},
"blob_with_content_that_is_a_replacement_with_a_mime_and_no_hint": {
"type": "blob",
"content": "[stripped image/jpeg 10 bytes]",
},
"blob_with_content_that_is_a_replacement_and_its_own_mime_type": {
"type": "blob",
"mime_type": "application/pdf",
"content": "[stripped image/png 8 bytes]",
},
"blob_with_content_that_is_a_replacement_of_unknown_size": {
"type": "blob",
"modality": "audio",
"content": "[stripped unknown unknown bytes]",
},
"blob_with_content_that_is_a_replacement_too_large_to_keep": {
"type": "blob",
"content": "[stripped unknown 9007199254740992 bytes]",
},
"blob_with_content_that_is_a_replacement_with_leading_zeros": {
"type": "blob",
"content": "[stripped image/png 0008 bytes]",
},
"blob_with_content_that_is_a_replacement_with_thousands_of_leading_zeros": {
"type": "blob",
"content": "[stripped unknown " + "0" * 5000 + "8 bytes]",
},
"blob_with_content_that_is_a_replacement_whose_size_overflows_int64": {
"type": "blob",
"content": "[stripped image/png 99999999999999999999 bytes]",
},
"blob_with_content_that_is_a_replacement_with_thousands_of_digits": {
"type": "blob",
"content": "[stripped unknown " + "9" * 5000 + " bytes]",
},
"blob_with_content_that_only_looks_like_a_replacement": {
"type": "blob",
"mime_type": "image/png",
"content": "[stripped image/png lots bytes]",
},
"blob_with_content_that_is_a_replacement_with_an_invalid_mime": {
"type": "blob",
"content": "[stripped a b 3 bytes]",
},
"blob_with_content_that_holds_a_replacement_in_text": {
"type": "blob",
"content": "see [stripped unknown 16 bytes]",
},
"uri_with_no_mime_type_and_no_modality": {
"type": "uri",
"uri": "https://example.com/download",
Expand Down
Loading