Skip to content

Commit 988195e

Browse files
niklassemmlerclaudecursoragenthassiebp
authored
feat(tracing)!: JSON-encode observation and trace metadata values (#1958)
* fix(tracing): JSON-encode metadata attribute values Per-key `langfuse.observation.metadata.<key>` attributes now carry `json.dumps(value, cls=EventSerializer)` for every value, strings included. Previously str and int were passed raw/natively, so ints beyond int64 made the OTLP encoder drop the key, ints beyond 2^53 lost precision on the server, and a server that JSON-decodes values could not tell the string "123" from the number 123. None values are still skipped so updates keep earlier keys. The bare non-dict metadata attribute is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(tracing)!: JSON-encode non-dict metadata too The bare `langfuse.observation.metadata` attribute (non-dict metadata) is now sent as `json.dumps(metadata, cls=EventSerializer)`, strings included, matching the per-key values and langfuse-js #1005. Previously strings were passed through raw, so `metadata="foo"` sent `foo` in Python but `"foo"` in JS. None is still not written. Input/output and other `_serialize` callers are unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test(e2e): match metadata expectations to server decoding The server JSON-decodes per-key metadata values only for Python SDK major >= 5 (langfuse/langfuse#18436). On 4.x the experiment items API returns the raw JSON string, so compare against the encoded value until the version bump. test_concurrency now writes an int so it round-trips the same way with and without server-side decoding. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(tracing): write metadata JSON with compact separators and raw non-ASCII Encode observation and trace metadata values with separators=(",", ":") and ensure_ascii=False so the output is byte-identical to JS JSON.stringify, matching propagated metadata (#1932). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(tracing): debug-log metadata keys skipped because their value is None Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(tracing)!: JSON-encode propagated trace metadata like observation metadata propagate_attributes(metadata=...) now uses the same encoder as observation metadata, so a string such as "123" stays a string once the server decodes langfuse.trace.metadata.<key>. Ints outside the JS-safe range and NaN/Infinity become JSON strings instead of exact digits or being dropped. The 200 character limit applies to the encoded value. Plain str values skip EventSerializer and go straight to json.dumps; the output is byte-identical and pinned against EventSerializer and JSON.stringify. Co-authored-by: Hassieb Pakzad <hassiebp@users.noreply.github.com> * fix(media): extract top-level data URIs from JSON-encoded metadata values Metadata values are JSON-encoded, so a top-level data URI arrives quoted and the exporter no longer recognized it, shipping the base64 inline. Decode the JSON string for Langfuse metadata attributes, process the media, and re-encode the reference string. Co-authored-by: Hassieb Pakzad <hassiebp@users.noreply.github.com> * style(tests): format span attribute limit test Co-authored-by: Hassieb Pakzad <hassiebp@users.noreply.github.com> * fix(tracing): drop None propagated metadata values with a warning Co-authored-by: Hassieb Pakzad <hassiebp@users.noreply.github.com> * perf(media): extract JSON-encoded metadata data URIs without json.loads Strip the quotes of a JSON-encoded top-level data URI in place instead of decoding and re-encoding it. Values with backslashes, inner quotes, or no ;base64 header in the first 256 characters are left unchanged. Co-authored-by: Hassieb Pakzad <hassiebp@users.noreply.github.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Hassieb Pakzad <hassiebp@users.noreply.github.com>
1 parent edf44eb commit 988195e

12 files changed

Lines changed: 639 additions & 175 deletions

‎langfuse/_client/attributes.py‎

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
)
2121
from langfuse._utils.serializer import EventSerializer
2222
from langfuse.api import MapValue
23+
from langfuse.logger import langfuse_logger
2324
from langfuse.model import PromptClient
2425
from langfuse.types import SpanLevel
2526

@@ -160,6 +161,26 @@ def _serialize(obj: Any) -> Optional[str]:
160161
return json.dumps(obj, cls=EventSerializer)
161162

162163

164+
def _serialize_metadata_value(value: Any) -> str:
165+
"""JSON-encode one metadata value, strings included.
166+
167+
The server decodes metadata values from v5 SDKs, so encoding every value
168+
keeps "123" and 123 distinct. EventSerializer turns ints outside the
169+
JS-safe range and NaN/Infinity into JSON strings and never raises, so one
170+
bad value cannot drop the other keys. Compact separators and raw non-ASCII
171+
match JS JSON.stringify.
172+
"""
173+
# Plain strings skip EventSerializer, which returns them unchanged and then
174+
# uses the same string encoder, so the output is identical but cheaper.
175+
# str subclasses (e.g. str enums) still go through EventSerializer.
176+
if type(value) is str:
177+
return json.dumps(value, ensure_ascii=False)
178+
179+
return json.dumps(
180+
value, cls=EventSerializer, separators=(",", ":"), ensure_ascii=False
181+
)
182+
183+
163184
def _flatten_and_serialize_metadata(
164185
metadata: Any, type: Literal["observation", "trace"]
165186
) -> dict:
@@ -169,16 +190,24 @@ def _flatten_and_serialize_metadata(
169190
else LangfuseOtelSpanAttributes.TRACE_METADATA
170191
)
171192

172-
metadata_attributes: Dict[str, Union[str, int, None]] = {}
193+
metadata_attributes: Dict[str, Optional[str]] = {}
173194

174195
if not isinstance(metadata, dict):
175-
metadata_attributes[prefix] = _serialize(metadata)
196+
# JSON-encode non-dict metadata too, strings included, matching the
197+
# per-key values below. None stays None so it is not written.
198+
metadata_attributes[prefix] = (
199+
None if metadata is None else _serialize_metadata_value(metadata)
200+
)
176201
else:
177202
for key, value in metadata.items():
178-
metadata_attributes[f"{prefix}.{key}"] = (
179-
value
180-
if isinstance(value, str) or isinstance(value, int)
181-
else _serialize(value)
182-
)
203+
# Skip None so an update does not overwrite an earlier value.
204+
if value is None:
205+
langfuse_logger.debug(
206+
'Observation metadata key "%s" was not written because its value is None',
207+
key,
208+
)
209+
continue
210+
211+
metadata_attributes[f"{prefix}.{key}"] = _serialize_metadata_value(value)
183212

184213
return metadata_attributes

‎langfuse/_client/propagation.py‎

Lines changed: 17 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
propagate to all child spans within the context.
66
"""
77

8-
import math
98
import re
109
from typing import (
1110
Any,
@@ -39,10 +38,12 @@
3938
_agnosticcontextmanager,
4039
)
4140

42-
from langfuse._client.attributes import LangfuseOtelSpanAttributes
41+
from langfuse._client.attributes import (
42+
LangfuseOtelSpanAttributes,
43+
_serialize_metadata_value,
44+
)
4345
from langfuse._client.constants import LANGFUSE_SDK_EXPERIMENT_ENVIRONMENT
4446
from langfuse._client.span import _set_span_attributes_within_limit
45-
from langfuse._utils.serializer import EventSerializer
4647
from langfuse.logger import langfuse_logger
4748
from langfuse.model import PromptClient
4849

@@ -156,8 +157,8 @@ def propagate_attributes(
156157
within a user session (e.g., a conversation thread, multi-turn interaction).
157158
metadata: Additional key-value metadata to propagate to all spans.
158159
- Keys must be US-ASCII strings
159-
- Values are coerced to strings
160-
- Coerced values must be ≤200 characters
160+
- Values are JSON-encoded, strings included
161+
- Encoded values must be ≤200 characters
161162
- Use for dimensions like internal correlating identifiers
162163
- AVOID: large payloads or sensitive data
163164
version: Version identfier for parts of your application that are independently versioned, e.g. agents
@@ -284,11 +285,13 @@ def propagate_attributes(
284285
- **Validation**: Attribute values (user_id, session_id, version, tags,
285286
trace_name) must be strings ≤200 characters. Environment must also match
286287
Langfuse's environment format: lowercase alphanumeric with optional
287-
hyphens or underscores, must be ≤40 characters, and it must not start with "langfuse". Non-string
288-
metadata values are serialized like JavaScript's `JSON.stringify`
289-
(compact separators, non-ASCII kept as is, None becomes "null",
290-
integers keep their exact digits) before the 200 character limit is
291-
applied. Values containing NaN or Infinity are dropped.
288+
hyphens or underscores, must be ≤40 characters, and it must not start with "langfuse". Metadata
289+
values, strings included, are JSON-encoded the same way as
290+
observation metadata (compact separators, non-ASCII kept as is,
291+
integers outside the JavaScript safe range and NaN/Infinity become
292+
JSON strings) before the 200 character limit is applied, so `"123"`
293+
stays a string on the server. None values are dropped with a warning,
294+
like observation metadata skips them.
292295
Invalid values will be dropped with a warning logged.
293296
- **OpenTelemetry**: This uses OpenTelemetry context propagation under the hood,
294297
making it compatible with other OTel-instrumented libraries.
@@ -388,17 +391,16 @@ def _propagate_attributes(
388391
validated_metadata: Dict[str, str] = {}
389392

390393
for key, value in metadata_value.items():
391-
serialized_value = _serialize_propagated_metadata_value(value)
392-
393-
if serialized_value is None:
394+
if value is None:
394395
langfuse_logger.warning(
395-
"Propagated attribute '%s.%s' contains NaN or Infinity, which "
396-
"is not valid JSON. Dropping value.",
396+
"Propagated attribute '%s.%s' is None. Dropping value.",
397397
metadata_key,
398398
key,
399399
)
400400
continue
401401

402+
serialized_value = _serialize_metadata_value(value)
403+
402404
if _validate_string_value(
403405
value=serialized_value, key=f"{metadata_key}.{key}"
404406
):
@@ -659,41 +661,6 @@ def _validate_propagated_value(
659661
return value
660662

661663

662-
class _PropagatedMetadataSerializer(EventSerializer):
663-
"""EventSerializer variant that matches the JS SDK for propagated metadata.
664-
665-
Integers keep their exact digits as JSON numbers at any depth, and values
666-
containing NaN or Infinity are flagged so the caller can drop them.
667-
"""
668-
669-
def __init__(self, *args: Any, **kwargs: Any) -> None:
670-
super().__init__(*args, **kwargs)
671-
self.found_non_finite_number = False
672-
673-
def default(self, obj: Any) -> Any:
674-
if isinstance(obj, int) and not isinstance(obj, bool):
675-
return obj
676-
677-
if isinstance(obj, float) and not math.isfinite(obj):
678-
self.found_non_finite_number = True
679-
return None
680-
681-
return super().default(obj)
682-
683-
684-
def _serialize_propagated_metadata_value(value: Any) -> Optional[str]:
685-
"""Serialize like JSON.stringify in the JS SDK; None means drop the value."""
686-
if isinstance(value, str):
687-
return value
688-
689-
serializer = _PropagatedMetadataSerializer(
690-
separators=(",", ":"), ensure_ascii=False
691-
)
692-
serialized = serializer.encode(value)
693-
694-
return None if serializer.found_non_finite_number else serialized
695-
696-
697664
def _validate_string_value(*, value: str, key: str) -> bool:
698665
if not isinstance(value, str):
699666
langfuse_logger.warning( # type: ignore

‎langfuse/_client/span_exporter.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,9 @@
8888
"llm.output_messages",
8989
)
9090

91+
# Includes the leading quote of a JSON-encoded data URI.
92+
_MAX_DATA_URI_HEADER_LENGTH = 256
93+
9194

9295
class LangfuseTransformingSpanExporter(SpanExporter):
9396
"""Apply Langfuse export-stage transformations before delegating export."""
@@ -211,6 +214,13 @@ def _process_media_string(
211214
attribute_key: str,
212215
value: str,
213216
) -> str:
217+
if value.startswith('"data:') and _is_langfuse_metadata_attribute(
218+
attribute_key
219+
):
220+
return self._process_json_encoded_media_string(
221+
span=span, attribute_key=attribute_key, value=value
222+
)
223+
214224
media_manager = cast(MediaManager, self._media_manager)
215225
field = _media_field_for_attribute(attribute_key)
216226

@@ -260,6 +270,40 @@ def _process_media_string(
260270

261271
return _serialize_media_value(processed_json_value, fallback=value)
262272

273+
def _process_json_encoded_media_string(
274+
self,
275+
*,
276+
span: ReadableSpan,
277+
attribute_key: str,
278+
value: str,
279+
) -> str:
280+
# Langfuse metadata values are JSON-encoded, so a top-level data URI
281+
# arrives quoted. A JSON string without backslashes holds its characters
282+
# literally, so stripping the outer quotes yields the data URI without
283+
# json.loads. The media reference is built from that backslash- and
284+
# quote-free data URI, so quoting it again is valid JSON. Escaped or
285+
# malformed values are left unchanged.
286+
header_end = value.find(",", 0, _MAX_DATA_URI_HEADER_LENGTH)
287+
288+
if (
289+
header_end == -1
290+
or not value.endswith('"')
291+
or not value[:header_end].endswith(";base64")
292+
or "\\" in value
293+
or value.find('"', 1, -1) != -1
294+
):
295+
return value
296+
297+
data_uri = value[1:-1]
298+
processed_value = self._process_media_string(
299+
span=span, attribute_key=attribute_key, value=data_uri
300+
)
301+
302+
if processed_value == data_uri:
303+
return value
304+
305+
return f'"{processed_value}"'
306+
263307
def _apply_mask_otel_spans(
264308
self,
265309
*,
@@ -556,6 +600,16 @@ def _is_attribute_sequence(value: AttributeValue) -> bool:
556600
return isinstance(value, SequenceCollection) and not isinstance(value, (str, bytes))
557601

558602

603+
def _is_langfuse_metadata_attribute(attribute_key: str) -> bool:
604+
return any(
605+
attribute_key == prefix or attribute_key.startswith(f"{prefix}.")
606+
for prefix in (
607+
LangfuseOtelSpanAttributes.OBSERVATION_METADATA,
608+
LangfuseOtelSpanAttributes.TRACE_METADATA,
609+
)
610+
)
611+
612+
559613
def _is_base64_data_uri(value: str) -> bool:
560614
if not value.startswith("data:") or "," not in value:
561615
return False

‎tests/e2e/test_core_sdk.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ async def update_generation(i, langfuse: Langfuse):
3737
)
3838

3939
# Update generation with metadata
40-
generation.update(metadata={"count": str(i)})
40+
generation.update(metadata={"count": i})
4141

4242
# End the generation
4343
generation.end()

‎tests/e2e/test_experiments.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
ExperimentItem,
1919
ExperimentItemResult,
2020
)
21+
from tests.support.utils import raw_metadata_value
2122

2223
T = TypeVar("T")
2324

@@ -216,7 +217,7 @@ def test_run_experiment_on_local_dataset(sample_dataset):
216217
assert item.output == expected_output
217218
assert item.expected_output == expected_answer
218219
assert item.metadata is not None
219-
assert item.metadata["experiment_name"] == "Euro capitals"
220+
assert item.metadata["experiment_name"] == raw_metadata_value("Euro capitals")
220221

221222
# Run-level evaluations are persisted for local data, too
222223
experiment = get_experiment(
@@ -362,9 +363,11 @@ def test_run_experiment_on_langfuse_dataset():
362363
assert item.expected_output == dataset_item.expected_output
363364

364365
assert item.metadata is not None
365-
assert item.metadata["experiment_name"] == experiment_name
366-
assert item.metadata["dataset_id"] == dataset.id
367-
assert item.metadata["dataset_item_id"] == item.experiment_item_id
366+
assert item.metadata["experiment_name"] == raw_metadata_value(experiment_name)
367+
assert item.metadata["dataset_id"] == raw_metadata_value(dataset.id)
368+
assert item.metadata["dataset_item_id"] == raw_metadata_value(
369+
item.experiment_item_id
370+
)
368371

369372
assert [s.name for s in item.scores or []] == ["factuality"]
370373

‎tests/support/utils.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from typing import Any, Callable, Sequence, TypeVar
66
from uuid import uuid4
77

8+
from langfuse._version import __version__ as langfuse_version
89
from langfuse.api import LangfuseAPI, ObservationV2, ScoreV3
910
from tests.support.retry import (
1011
DEFAULT_RETRY_INTERVAL_SECONDS,
@@ -37,6 +38,19 @@
3738
)
3839
_SDK_METADATA_KEY_PREFIXES = ("scope.", "resourceAttributes.")
3940

41+
# The server JSON-decodes per-key observation metadata values only for Python
42+
# SDK major >= 5 (langfuse/langfuse#18436). Older SDK versions read back the raw
43+
# JSON string on endpoints that do not parse metadata values on read.
44+
_SERVER_DECODES_METADATA_VALUES = int(langfuse_version.split(".")[0]) >= 5
45+
46+
47+
def raw_metadata_value(value: Any) -> Any:
48+
"""Per-key metadata value as stored by the server for this SDK version."""
49+
if _SERVER_DECODES_METADATA_VALUES:
50+
return value
51+
52+
return json.dumps(value, separators=(",", ":"), ensure_ascii=False)
53+
4054

4155
def _has_filters(kwargs: dict[str, Any]) -> bool:
4256
return any(

‎tests/unit/test_langchain.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -845,7 +845,7 @@ def test_tool_when_structured_inputs_only_store_in_inputs_attribute_not_metadata
845845

846846
metadata_prefix = LangfuseOtelSpanAttributes.OBSERVATION_METADATA
847847

848-
assert span.attributes[f"{metadata_prefix}.custom_key"] == "custom_value"
848+
assert span.attributes[f"{metadata_prefix}.custom_key"] == '"custom_value"'
849849
assert f"{metadata_prefix}.inputs" not in span.attributes
850850

851851

0 commit comments

Comments
 (0)