Skip to content

Commit f9b875f

Browse files
fix(serializer): handle NaN/Inf floats nested in pydantic models (#1811)
The BaseModel branch in EventSerializer returned obj.model_dump() directly, so non-finite floats nested inside a pydantic model bypassed the NaN/Inf-to-string conversion and were emitted as bare NaN/Infinity tokens (invalid JSON). Recurse the dumped model back through default() so nested non-finite floats are converted to safe strings like every other path.
1 parent 73b5c02 commit f9b875f

2 files changed

Lines changed: 38 additions & 1 deletion

File tree

‎langfuse/_utils/serializer.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,11 @@ def _default_inner(self, obj: Any) -> Any:
136136
if isinstance(raw := getattr(obj, "raw", None), BaseModel):
137137
raw.model_rebuild()
138138

139-
return obj.model_dump()
139+
# Recurse the dumped model back through default() so nested
140+
# non-finite floats (NaN/Inf) are converted to safe strings.
141+
# Returning model_dump() directly lets the json C-encoder emit
142+
# bare NaN/Infinity tokens, which are invalid JSON.
143+
return self.default(obj.model_dump())
140144

141145
# if langchain is not available, the Serializable type is NoneType
142146
if Serializable is not type(None) and isinstance(obj, Serializable): # type: ignore

‎tests/unit/test_serializer.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,39 @@ def test_infinity_floats():
196196
assert serializer.encode(float("-inf")) == '"-Infinity"'
197197

198198

199+
def test_pydantic_model_with_non_finite_floats():
200+
# Non-finite floats nested inside a pydantic model must be converted to
201+
# safe string tokens rather than emitted as bare NaN/Infinity, which are
202+
# invalid JSON and are rejected by the ingestion server's strict parser.
203+
class ModelWithFloats(BaseModel):
204+
nan: float
205+
inf: float
206+
neg_inf: float
207+
finite: float
208+
209+
model = ModelWithFloats(
210+
nan=float("nan"),
211+
inf=float("inf"),
212+
neg_inf=float("-inf"),
213+
finite=1.5,
214+
)
215+
serializer = EventSerializer()
216+
encoded = serializer.encode(model)
217+
218+
# Must be strict JSON: json.loads accepts bare NaN/Infinity by default, so
219+
# use parse_constant to reject them the way the ingestion server does.
220+
def _reject(token):
221+
raise ValueError(f"invalid JSON constant emitted: {token}")
222+
223+
parsed = json.loads(encoded, parse_constant=_reject)
224+
assert parsed == {
225+
"nan": "NaN",
226+
"inf": "Infinity",
227+
"neg_inf": "-Infinity",
228+
"finite": 1.5,
229+
}
230+
231+
199232
def test_slots():
200233
class SlotClass:
201234
__slots__ = ["field"]

0 commit comments

Comments
 (0)