Repository navigation
fix(serializer): serialize datetime.time and timedelta values (#20158) - #2131
ShayanMuhammad-CS wants to merge 2 commits into
Conversation
chrikrah
left a comment
There was a problem hiding this comment.
@ShayanMuhammad-CS The time and timedelta branches are correct, and all six new tests fail against base and pass here.
non-blocking: #20158 already offered an ISO 8601 duration as the other option, and pydantic picks that one. The same model reads differently in langfuse and in pydantic's own JSON, and a bare 300.0 loses its unit. It's cheap to pick now, before traces store floats.
$ python -m pytest tests/unit/test_serializer.py -q -p no:cacheprovider # Python 3.12.14, langfuse imported from the export
56 passed # head 8d7553f
6 failed, 50 passed # serializer.py from base 077448c
$ python lf_td.py # pydantic 2.14.3, M(at=time(14, 15), timeout=timedelta(minutes=5))
pydantic model_dump_json: {"at":"14:15:00","timeout":"PT5M"}
EventSerializer: {"at": "14:15:00", "timeout": 300.0}
# not run: e2e tests against a Langfuse server
Is there a consumer that needs seconds, or would PT5M work?
|
Thanks for the thorough review and benchmarking, @chrikrah! Switching
I will update the |
…maintainer feedback (#20158)
|
Hi @chrikrah, Updated in commit
Ready for review and merge! |
Description
Closes langfuse/langfuse#20158
Previously,
EventSerializerinlangfuse._utils.serializerhandleddateanddatetimeobjects, but lacked branches fordatetime.timeanddatetime.timedelta. Because standardtimeandtimedeltainstances lack__slots__and__dict__, they fell through to the unhandled type-name fallback, serializing as"<time>"and"<timedelta>".This also caused Pydantic models containing
timeortimedeltafields to lose their values, asmodel_dump()output recurses throughEventSerializer.default().Fix
timeandtimedeltahandling toEventSerializer._default_inner.datetime.timeviaobj.isoformat().datetime.timedeltavia standard ISO 8601 duration format (e.g."PT5M","PT1M30S","-PT45S"), usingpydantic_core.to_jsonable_pythonwith a zero-dependency fallback_timedelta_to_iso8601, ensuring 100% schema alignment with Pydantic'smodel_dump_json().Testing
Added 6 unit tests to
tests/unit/test_serializer.py:test_time: verifies ISO 8601 formatting ("09:30:00").test_time_with_microseconds_and_timezone: verifies fractional seconds and timezone offset.test_timedelta: verifies ISO 8601 duration formatting ("PT1M30S").test_timedelta_fractional_and_negative: verifies milliseconds ("PT0.25S") and negative intervals ("-PT45S").test_pydantic_model_with_time_and_timedelta: verifies nested Pydantic model serialization ("timeout": "PT5M").test_dict_with_time_and_timedelta: verifies dictionary values ("duration": "PT1H30M").All tests passing: