|
5 | 5 | propagate to all child spans within the context. |
6 | 6 | """ |
7 | 7 |
|
8 | | -import math |
9 | 8 | import re |
10 | 9 | from typing import ( |
11 | 10 | Any, |
|
39 | 38 | _agnosticcontextmanager, |
40 | 39 | ) |
41 | 40 |
|
42 | | -from langfuse._client.attributes import LangfuseOtelSpanAttributes |
| 41 | +from langfuse._client.attributes import ( |
| 42 | + LangfuseOtelSpanAttributes, |
| 43 | + _serialize_metadata_value, |
| 44 | +) |
43 | 45 | from langfuse._client.constants import LANGFUSE_SDK_EXPERIMENT_ENVIRONMENT |
44 | 46 | from langfuse._client.span import _set_span_attributes_within_limit |
45 | | -from langfuse._utils.serializer import EventSerializer |
46 | 47 | from langfuse.logger import langfuse_logger |
47 | 48 | from langfuse.model import PromptClient |
48 | 49 |
|
@@ -156,8 +157,8 @@ def propagate_attributes( |
156 | 157 | within a user session (e.g., a conversation thread, multi-turn interaction). |
157 | 158 | metadata: Additional key-value metadata to propagate to all spans. |
158 | 159 | - 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 |
161 | 162 | - Use for dimensions like internal correlating identifiers |
162 | 163 | - AVOID: large payloads or sensitive data |
163 | 164 | version: Version identfier for parts of your application that are independently versioned, e.g. agents |
@@ -284,11 +285,13 @@ def propagate_attributes( |
284 | 285 | - **Validation**: Attribute values (user_id, session_id, version, tags, |
285 | 286 | trace_name) must be strings ≤200 characters. Environment must also match |
286 | 287 | 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. |
292 | 295 | Invalid values will be dropped with a warning logged. |
293 | 296 | - **OpenTelemetry**: This uses OpenTelemetry context propagation under the hood, |
294 | 297 | making it compatible with other OTel-instrumented libraries. |
@@ -388,17 +391,16 @@ def _propagate_attributes( |
388 | 391 | validated_metadata: Dict[str, str] = {} |
389 | 392 |
|
390 | 393 | 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: |
394 | 395 | 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.", |
397 | 397 | metadata_key, |
398 | 398 | key, |
399 | 399 | ) |
400 | 400 | continue |
401 | 401 |
|
| 402 | + serialized_value = _serialize_metadata_value(value) |
| 403 | + |
402 | 404 | if _validate_string_value( |
403 | 405 | value=serialized_value, key=f"{metadata_key}.{key}" |
404 | 406 | ): |
@@ -659,41 +661,6 @@ def _validate_propagated_value( |
659 | 661 | return value |
660 | 662 |
|
661 | 663 |
|
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 | | - |
697 | 664 | def _validate_string_value(*, value: str, key: str) -> bool: |
698 | 665 | if not isinstance(value, str): |
699 | 666 | langfuse_logger.warning( # type: ignore |
|
0 commit comments