Skip to content

render_type_definitions can emit duplicate TypedDict classes and unresolved type references when type names conflict #8816

Closed

Description

@BlueX888

Initial Checks

Description

FunctionSignature.render_type_definitions resolves type-name conflicts by type name, so its output can be Python that does not behave as intended, with no error raised anywhere in pydantic-ai:

  1. A tool whose parameter and return schemas each define their own User $def renders two class sync_user_User(TypedDict): definitions. Concatenated into one module (as catalogs built from this output do), the second definition silently rebinds the name, so the user parameter ends up with the return type's shape. On top of that, RetWrap.user renders as plain User, which no emitted definition provides.
  2. A non-conflicting type whose fields reference a conflicting type renders the plain name — e.g. Wrapper.user: User — while the only emitted User definitions are the prefixed tool_a_User / tool_b_User, so the reference resolves to nothing.

Example

from pydantic_ai.function_signature import FunctionSignature

# Case 1: one tool whose parameter and return schemas each define their own `User`.
sig = FunctionSignature.from_schema(
    name='sync_user',
    parameters_schema={
        'type': 'object',
        'properties': {'user': {'$ref': '#/$defs/User'}},
        'required': ['user'],
        '$defs': {
            'User': {
                'type': 'object',
                'properties': {'name': {'type': 'string'}},
                'required': ['name'],
            },
        },
    },
    return_schema={
        '$ref': '#/$defs/RetWrap',
        '$defs': {
            'User': {
                'type': 'object',
                'properties': {'id': {'type': 'integer'}, 'email': {'type': 'string'}},
                'required': ['id', 'email'],
            },
            'RetWrap': {
                'type': 'object',
                'properties': {'user': {'$ref': '#/$defs/User'}},
                'required': ['user'],
            },
        },
    },
)

conflicting = FunctionSignature.get_conflicting_type_names([sig])
print('conflicting:', sorted(conflicting))

definitions = FunctionSignature.render_type_definitions([sig], conflicting)
print('--- render_type_definitions ---')
for d in definitions:
    print(d)
print('--- render ---')
print(sig.render('...', name='sync_user', conflicting_type_names=conflicting))

# Case 2: a non-conflicting type whose fields reference a conflicting type.
sig_a = FunctionSignature.from_schema(
    name='tool_a',
    parameters_schema={
        'type': 'object',
        'properties': {'wrap': {'$ref': '#/$defs/Wrapper'}},
        'required': ['wrap'],
        '$defs': {
            'Wrapper': {
                'type': 'object',
                'properties': {'user': {'$ref': '#/$defs/User'}},
                'required': ['user'],
            },
            'User': {
                'type': 'object',
                'properties': {'name': {'type': 'string'}},
                'required': ['name'],
            },
        },
    },
)
sig_b = FunctionSignature.from_schema(
    name='tool_b',
    parameters_schema={
        'type': 'object',
        'properties': {'user': {'$ref': '#/$defs/User'}},
        'required': ['user'],
        '$defs': {
            'User': {
                'type': 'object',
                'properties': {'id': {'type': 'integer'}},
                'required': ['id'],
            },
        },
    },
)

conflicting = FunctionSignature.get_conflicting_type_names([sig_a, sig_b])
print()
print('conflicting:', sorted(conflicting))

definitions = FunctionSignature.render_type_definitions([sig_a, sig_b], conflicting)
print('--- render_type_definitions ---')
for d in definitions:
    print(d)
print('--- render ---')
print(sig_a.render('...', name='tool_a', conflicting_type_names=conflicting))
print(sig_b.render('...', name='tool_b', conflicting_type_names=conflicting))

Actual output on current main (5badf40):

conflicting: ['User']
--- render_type_definitions ---
class sync_user_User(TypedDict):
    name: str
class sync_user_User(TypedDict):
    id: int
    email: str
class RetWrap(TypedDict):
    user: User
--- render ---
def sync_user(*, user: sync_user_User) -> RetWrap:
    ...

conflicting: ['User']
--- render_type_definitions ---
class Wrapper(TypedDict):
    user: User
class tool_a_User(TypedDict):
    name: str
class tool_b_User(TypedDict):
    id: int
--- render ---
def tool_a(*, wrap: Wrapper) -> Any:
    ...
def tool_b(*, user: tool_b_User) -> Any:
    ...

Expected behaviour

  • Every emitted class name is unique. A duplicate class header means the second definition silently shadows the first when the output is assembled into one module.
  • Every annotation resolves to an emitted definition (or a JSON-type builtin the renderer emits). Keeping conflicting names both unique and resolvable is the stated purpose of the tool-name prefix in render_type_definitions ("each definition is rendered with a tool-name prefix (e.g. get_user_Address)").

For case 1 that means two distinct names (e.g. sync_user_User and sync_user_User_2) with RetWrap.user pointing at the name the return-side definition actually renders under; for case 2, Wrapper.user should render as the prefixed name of the User it references (tool_a_User).

Root cause

pydantic_ai_slim/pydantic_ai/function_signature.py:

  • _type_name_overrides (line 31) maps type names to prefixed names (dict[str, str]), and TypeSignature.display_name (line 153) resolves by name — so two same-named $defs owned by one signature both map to the same <tool>_<name>, producing the duplicate class definitions of case 1.
  • render_type_definitions (lines 440–448) renders each definition with overrides installed only for that definition itself; a non-conflicting type is rendered with owner_name=None, so its fields render the unprefixed User of case 2.

Logfire Trace

Not applicable — the rendering path involves no model call.

Python, Pydantic AI & LLM client version

  • Python: 3.12.14
  • Pydantic AI: main @ 5badf40; function_signature.py is identical in v2.51.0 (the latest release), so both are affected
  • LLM provider SDK: N/A

Happy to reopen the PR with this fix once this issue is linked, or to be assigned if you prefer to take it.

Activity

  1. added
    pydanty:is-workingPydanty is mid-flight reviewing/remediating this PR; do not edit until it clears
    on Sep 26, 2026
  2. pydanty commented on Sep 26, 2026

    @pydanty
    Contributor

    pydanty runtime failure

    Run df_run_ec8f8f4984bf4ec9a9e8 started from the GitHub webhook, but the Dogfooding runtime
    failed before pydanty completed the workflow. The pydanty status comment above
    (if any) is from a completed run and still stands.

    Next step: maintainer attention needed; rerun after fixing the runtime failure.

    Failure detail (tail)
    g):
      File "/home/pydanty/dogfooding/.runner.py", line 402, in <module>
        asyncio.run(main())
      File "/home/pydanty/dogfooding/.runner.py", line 362, in main
        result = await result
                 ^^^^^^^^^^^^
      File "/home/pydanty/dogfooding/agents/pydanty/triage_agent.py", line 778, in run
        result = await TriageWorkflowController(
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/pydanty/dogfooding/agents/pydanty/workflow.py", line 888, in run
        execution = await self.executor(phase, inputs)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/pydanty/dogfooding/agents/pydanty/triage_agent.py", line 657, in __call__
        result = await phase_agent.run(
                 ^^^^^^^^^^^^^^^^^^^^^^
      File "/home/pydanty/dogfooding/agents/shared/tool_error_guard.py", line 75, in wrap_tool_execute
        return await handler(args)
               ^^^^^^^^^^^^^^^^^^^
      File "/home/pydanty/dogfooding/agents/shared/tool_loop_guard.py", line 142, in wrap_tool_execute
        return await handler(args)
               ^^^^^^^^^^^^^^^^^^^
      File "/home/pydanty/dogfooding/agents/pydanty/triage_agent.py", line 468, in ask_code_librarian
        result = await code_librarian_agent.run(
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/pydanty/dogfooding/agents/shared/model_retries.py", line 165, in retry_transient_model_request
        return await handler(request_context)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    FallbackExceptionGroup: All models from FallbackModel failed (2 sub-exceptions)
      [1] ModelAPIError: Request timed out.
      [2] ModelHTTPError: status_code: 400, model_name: gpt-5.6-luna, body: {'message': "Invalid 'input[1].id': 'reasoning_content'. Expected an ID that begins with 'rs'.", 'type': 'invalid_request_error', 'param': 'input[1].id', 'code': 'invalid_value'}
    
    
  3. removed
    pydanty:is-workingPydanty is mid-flight reviewing/remediating this PR; do not edit until it clears
    on Sep 26, 2026
  4. self-assigned this
    on Oct 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions