From b302c411d4bbe3f2fb54c8424aed920eb04c4661 Mon Sep 17 00:00:00 2001 From: Jim Bennett Date: Wed, 18 Nov 2026 14:01:44 -0800 Subject: [PATCH] Serialize Pydantic models by alias so they round-trip DefaultSerde and PydanticJsonSerde dumped Pydantic models with model_dump_json(), which writes field names, while model_validate_json() reads aliases. An aliased field therefore did not survive a journal round trip. For the OpenAI Agents integration, a Responses API function call was journaled with "async_" instead of "async"; on replay the unknown key was kept as an extra and sent in the next request, which the API rejects with 400 "Unknown parameter: 'input[1].async_'". Dump with by_alias=True in both serdes and in RestateModelResponse.to_input_items(). Fixes #320 Co-Authored-By: Claude Opus 5.5 --- python/restate/ext/openai/models.py | 3 +- python/restate/serde.py | 10 +++++-- tests/serde.py | 46 +++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 4 deletions(-) diff --git a/python/restate/ext/openai/models.py b/python/restate/ext/openai/models.py index 7754b594..09c0d9fc 100644 --- a/python/restate/ext/openai/models.py +++ b/python/restate/ext/openai/models.py @@ -48,7 +48,8 @@ class RestateModelResponse(BaseModel): """ def to_input_items(self) -> list[TResponseInputItem]: - return [it.model_dump(exclude_unset=True) for it in self.output] # type: ignore + # by_alias: the Responses API expects wire names (e.g. `async`, not `async_`). + return [it.model_dump(exclude_unset=True, by_alias=True) for it in self.output] # type: ignore class AgentsTerminalException(AgentsException, TerminalError): diff --git a/python/restate/serde.py b/python/restate/serde.py index f5fb7cde..2d2fe03f 100644 --- a/python/restate/serde.py +++ b/python/restate/serde.py @@ -229,7 +229,8 @@ class DefaultSerde(Serde[I]): Behavior: - Serialization: - If the object is an instance of Pydantic's `BaseModel`, - it uses `model_dump_json()` for serialization. + it uses `model_dump_json(by_alias=True)` for serialization, so the JSON + uses the same field names `model_validate_json()` reads back. - Otherwise, it falls back to `json.dumps()`. - Deserialization: - Uses `json.loads()` to convert byte arrays into Python objects. @@ -307,7 +308,9 @@ def serialize(self, obj: typing.Optional[I]) -> bytes: if Msgspec.is_struct(hint): return Msgspec.encode(obj) if is_pydantic(hint): - return obj.model_dump_json().encode("utf-8") # type: ignore[attr-defined] + # by_alias: model_validate_json() reads aliases, so dumping field names + # would break the round trip for aliased fields. + return obj.model_dump_json(by_alias=True).encode("utf-8") # type: ignore[attr-defined] if is_dataclass(obj): data = DaciteToDict(obj) # type: ignore return json.dumps(data).encode("utf-8") @@ -351,7 +354,8 @@ def serialize(self, obj: typing.Optional[I]) -> bytes: """ if obj is None: return bytes() - json_str = obj.model_dump_json() # type: ignore[attr-defined] + # by_alias: see DefaultSerde.serialize. + json_str = obj.model_dump_json(by_alias=True) # type: ignore[attr-defined] return json_str.encode("utf-8") diff --git a/tests/serde.py b/tests/serde.py index d15c5f25..e0e6f258 100644 --- a/tests/serde.py +++ b/tests/serde.py @@ -31,3 +31,49 @@ def extract_core_type_optional(): kind, tpe = extract_core_type(t) assert kind == "simple" assert tpe is t + + +def test_pydantic_serdes_round_trip_aliased_fields(): + """Aliased fields survive a round trip: dump and validate use the same names.""" + from pydantic import BaseModel, ConfigDict, Field + + from restate.serde import DefaultSerde, PydanticJsonSerde, Serde + + class Call(BaseModel): + model_config = ConfigDict(extra="allow") + name: str + async_: bool = Field(alias="async") + + call = Call.model_validate({"name": "get_weather", "async": True}) + serdes: list[Serde[Call]] = [DefaultSerde(Call), PydanticJsonSerde(Call)] + for serde in serdes: + buf = serde.serialize(call) + assert b'"async":true' in buf + restored = serde.deserialize(buf) + assert restored == call + assert restored is not None and restored.model_extra == {} + + +def test_openai_model_response_replay_keeps_wire_names(): + """A journaled Responses API function call replays with `async`, not `async_`.""" + import pytest + + pytest.importorskip("agents") + from agents.usage import Usage + from openai.types.responses import ResponseFunctionToolCall + + from restate.ext.openai.models import RestateModelResponse + from restate.serde import DefaultSerde + + call = ResponseFunctionToolCall.model_validate( + {"type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": "{}", "async": False} + ) + resp = RestateModelResponse(output=[call], usage=Usage(), response_id="resp_1") + + serde = DefaultSerde(RestateModelResponse) + replayed = serde.deserialize(serde.serialize(resp)) + assert replayed is not None + (raw_item,) = replayed.to_input_items() + item: dict = dict(raw_item) + assert "async_" not in item + assert item["async"] is False