Skip to content

[Bug] Pydantic converter with ToJsonOptions drops field aliases and serializes inf/nan as null #2038

Closed

Description

@avanish-garg

What are you really trying to do?

Use PydanticPayloadConverter with ToJsonOptions(exclude_unset=True) (the option the OpenAI Agents, Google ADK and DeepAgents plugins in temporalio/ai-integrations rely on) and still exchange the same JSON with workflows and activities as the default pydantic_data_converter.

Describe the bug

When to_json_options is set, PydanticJSONPlainPayloadConverter.to_payload serializes through SchemaSerializer(any_schema()).to_json(value, exclude_unset=...) instead of pydantic_core.to_json(value). The two calls have different defaults:

  • by_alias: pydantic_core.to_json keeps by_alias=True for backwards compatibility. SchemaSerializer.to_json defaults to by_alias=None, i.e. False, since pydantic 2.11.
  • ser_json_inf_nan: pydantic_core.to_json writes inf/nan as constants (Infinity, NaN). A bare SchemaSerializer writes null.

So setting an option that should only change which fields are emitted (exclude_unset) also changes the wire format of everything else:

  • A model with an aliased field is encoded with the field name instead of the alias ({"order_id":7} instead of {"orderId":7,...}). A receiver whose model accepts only the alias (the pydantic default) silently falls back to the field default. In the reproduction below the workflow was sent orderId=7 and saw order_id = -1.
  • Top-level, list and dict floats inf/-inf/nan are written as null.

Expected: with ToJsonOptions, the JSON must equal what the default converter produces apart from the effect of the options themselves (same converter class, same json/plain encoding).

Note: inf/nan inside a pydantic model field are null on both paths today, because the model's own config governs them. Only values serialized without a model schema (top level, lists, dicts) differ.

Minimal Reproduction

import asyncio, uuid

from pydantic import BaseModel, Field

from temporalio import workflow
from temporalio.contrib.pydantic import (
    PydanticPayloadConverter,
    ToJsonOptions,
    pydantic_data_converter,
)
from temporalio.converter import DataConverter
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker


class Opts(PydanticPayloadConverter):
    def __init__(self) -> None:
        super().__init__(ToJsonOptions(exclude_unset=True))


opts_converter = DataConverter(payload_converter_class=Opts)


class Order(BaseModel):
    order_id: int = Field(default=-1, alias="orderId")
    note: str = ""


@workflow.defn
class Echo:
    @workflow.run
    async def run(self, order: Order) -> int:
        return order.order_id


async def main():
    for name, dc in (
        ("default pydantic_data_converter", pydantic_data_converter),
        ("ToJsonOptions(exclude_unset=True)", opts_converter),
    ):
        pc = dc.payload_converter
        print(
            f"{name}: model -> {pc.to_payloads([Order(orderId=7)])[0].data!r}"
            f"   inf -> {pc.to_payloads([float('inf')])[0].data!r}"
        )

    async with await WorkflowEnvironment.start_local(data_converter=opts_converter) as env:
        async with Worker(
            env.client, task_queue="tq", workflows=[Echo],
            workflow_runner=UnsandboxedWorkflowRunner(),
        ):
            got = await env.client.execute_workflow(
                Echo.run, Order(orderId=7), id=str(uuid.uuid4()), task_queue="tq"
            )
            print("workflow saw order_id =", got)


asyncio.run(main())

Output on main:

default pydantic_data_converter: model -> b'{"orderId":7,"note":""}'   inf -> b'Infinity'
ToJsonOptions(exclude_unset=True): model -> b'{"order_id":7}'   inf -> b'null'
workflow saw order_id = -1

Expected: the second line should be b'{"orderId":7}' and b'Infinity', and the workflow should see 7.

Environment/Versions

  • OS and processor: macOS (Apple Silicon), Python 3.12.14
  • Temporal Version: temporalio main at 2a7d321c (version 1.35.0); local dev server from WorkflowEnvironment.start_local. The native bridge was the 1.34.0 wheel's temporal_sdk_bridge; only pure-Python code from main differs.
  • pydantic 2.14.1 / pydantic-core 2.50.1. On pydantic < 2.11 by_alias already defaulted to True, so only the inf/nan difference applies there (checked on 2.10.6).
  • Docker or Kubernetes or building Temporal from source? No.

Additional context

Cause is temporalio/contrib/pydantic.py (PydanticJSONPlainPayloadConverter.__init__ and to_payload). A fix is small: build the serializer with config={"ser_json_inf_nan": "constants"} and pass by_alias=True. I have one ready with a parity test and will open it once you are happy with the direction. Happy to adjust if you would rather make by_alias configurable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugsdk-python

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions