Backtestspydanticrun-20260929-204949#13599

Issue #13599 Merged fix PR #13604 Run 29 Sep 2026 · run-20260929-204949 pydantic/pydantic

PEP 695 type aliases don't work with callable discriminators

Worse

The merged fix was judged better than our patch.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches share the identical root-cause fix: passing `definitions` through `apply_discriminator` into `Discriminator._convert_schema` and teaching that method to resolve `definition-ref` schemas from the definitions dict when no `handler` is present (the deferred/callable discriminator path). Correctness is essentially equivalent; both resolve M3 by resolving the type-alias-produced definition-refs both at the root and per-choice. Patch A consolidates the resolution logic into a single `_resolve_ref` helper used in both places, which is cleaner and removes the duplicated try/except pattern; it does broaden the root guard from `handler is not None` to always checking `definition-ref` (raising MissingDefinitionForUnionRef when unresolved), a minor defensive change that in practice never fires without handler-or-definitions and matches `_apply_to_root`'s intent. Patch B is more conservative, keeping `(handler is not None or definitions is not None)` guards, but at the cost of duplicated resolve logic and a manual `raise LookupError`. The decisive difference is tests: Patch A adds a concise, idiomatic test using `TypeAliasType` placed directly beside the existing analogous test, matching surrounding conventions. Patch B's test relies on `exec` of a source string with a version-gated skip and mutable globals — more faithful to the raw issue text but noticeably uglier and harder to maintain, with no added coverage value over A's equivalent runtime type-alias construction. A wins on craft and test quality with no correctness regression.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

8m16 turns

Wall-clock time in the container

Full test suite

No new failures

12,321 passed · 499 skipped · 12,820 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

74vs 60 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

New type aliases prefixed with the type keyword are not supported as the type annotation for a callable discriminator.

M1, M2, M4 ok
M3

pydantic.errors.PydanticUserError: `Tag` not provided for choice {'type': 'definition-ref', 'schema_ref': '__main__.TaggedAnyA:2210408548368'} used with `Discriminator`

Example Code from #12843 also doesn’t work.

Example Code

import traceback
from sys import stderr

from pydantic import BaseModel, Discriminator, Field, Tag
from typing_extensions import Annotated, Any, Literal, TypeAlias


class A(BaseModel):
    type_: str

class A1(A):
    type_: Literal['A1'] = Field(alias='type')

class A2(A):
    type_: Literal['A2'] = Field(alias='type')

def _discriminator(data: Any) -> str:
    if isinstance(data, dict):
        return data['type']
    return data.type_

discriminator = Discriminator(_discriminator)

type AnyA = A1 | A2
AnyA_old: TypeAlias = A1 | A2

type TaggedAnyA = Annotated[A1, Tag('A1')] | Annotated[A2, Tag('A2')]
TaggedAnyA_old: TypeAlias = Annotated[A1, Tag('A1')] | Annotated[A2, Tag('A2')]


_data = {"a" : {'type': 'A1'}}
try:
    class M1(BaseModel):
        a: AnyA = Field(discriminator='type_')

    M1.model_validate(_data)
except Exception as e:
    traceback.print_exc()
else:
    print("OK", file=stderr)

try:
    class M2(BaseModel):
        a: AnyA_old = Field(discriminator='type_')

    M2.model_validate(_data)
except Exception as e:
    traceback.print_exc()
else:
    print("OK", file=stderr)

try:
    class M3(BaseModel):
        a: TaggedAnyA = Field(discriminator=discriminator)

    M3.model_validate(_data)
except Exception as e:
    traceback.print_exc()
else:
    print("OK", file=stderr)

try:
    class M4(BaseModel):
        a: TaggedAnyA_old = Field(discriminator=discriminator)

    M4.model_validate(_data)
except Exception as e:
    traceback.print_exc()
else:
    print("OK", file=stderr)

Python, Pydantic & OS Version

pydantic version: 2.13.4
        pydantic-core version: 2.46.4
          pydantic-core build: profile=release pgo=false
               python version: 3.14.7 (tags/v3.14.7:823f032, Aug  5 2026, 10:51:32) [MSC v.1944 64 bit (AMD64)]
                     platform: Windows-11-10.0.26200-SP0
             related packages: mypy-2.3.0 typing_extensions-4.16.0
                       commit: unknown

The two patches

Our patch+68 −6
pydantic/_internal/_discriminated_union.pyindex 94c82026..64f23145 100644@@ -65,7 +65,7 @@ def apply_discriminator(         if isinstance(discriminator.discriminator, str):             discriminator = discriminator.discriminator         else:-            return discriminator._convert_schema(schema)+            return discriminator._convert_schema(schema, definitions=definitions)      return _ApplyInferredDiscriminator(discriminator, definitions or {}).apply(schema) pydantic/types.pyindex f32a2ab8..dfd29187 100644@@ -3112,12 +3112,24 @@ class Discriminator:             return self._convert_schema(original_schema, handler)      def _convert_schema(-        self, original_schema: core_schema.CoreSchema, handler: GetCoreSchemaHandler | None = None+        self,+        original_schema: core_schema.CoreSchema,+        handler: GetCoreSchemaHandler | None = None,+        definitions: dict[str, core_schema.CoreSchema] | None = None,     ) -> core_schema.TaggedUnionSchema:-        if handler is not None and original_schema['type'] == 'definition-ref':+        def resolve_ref_schema(schema: core_schema.CoreSchema) -> core_schema.CoreSchema:+            if handler is not None:+                return handler.resolve_ref_schema(schema)+            if definitions is not None:+                schema_ref = schema['schema_ref']+                if schema_ref in definitions:+                    return definitions[schema_ref]+            raise LookupError(schema['schema_ref'])++        if (handler is not None or definitions is not None) and original_schema['type'] == 'definition-ref':             # Same logic as `_ApplyInferredDiscriminator._apply_to_root()`             try:-                def_schema = handler.resolve_ref_schema(original_schema)+                def_schema = resolve_ref_schema(original_schema)             except LookupError:  # pragma: no cover                 from pydantic._internal._discriminated_union import MissingDefinitionForUnionRef @@ -3145,10 +3157,10 @@ class Discriminator:                 tag = metadata.get('pydantic_internal_union_tag_key') or tag             if tag is None:                 # `handler` is None when this method is called from `apply_discriminator()` (deferred discriminators)-                if handler is not None and choice['type'] == 'definition-ref':+                if (handler is not None or definitions is not None) and choice['type'] == 'definition-ref':                     # If choice was built from a PEP 695 type alias, try to resolve the def:                     try:-                        choice = handler.resolve_ref_schema(choice)+                        choice = resolve_ref_schema(choice)                     except LookupError:                         pass                     else:tests/types/unions/test_discriminated_union.pyindex fccb82fb..40fad357 100644@@ -2583,3 +2583,53 @@ def test_union_tags_in_errors():             'type': 'dict_type',         },     ]+++@pytest.mark.skipif(sys.version_info < (3, 12), reason='Requires PEP 695 syntax')+def test_callable_discriminator_pep695_type_alias():+    """Regression test for PEP 695 `type X = ...` aliases used as the annotation for a+    field with a callable `Discriminator` when union members carry `Tag(...)`.++    https://github.com/pydantic/pydantic/issues/13598+    """+    globs = {}+    exec(+        """+from typing_extensions import Annotated, Literal++from pydantic import BaseModel, Discriminator, Field, Tag+++class A(BaseModel):+    type_: str+++class A1(A):+    type_: Literal['A1'] = Field(alias='type')+++class A2(A):+    type_: Literal['A2'] = Field(alias='type')+++def _discriminator(data):+    if isinstance(data, dict):+        return data['type']+    return data.type_+++type TaggedAnyA = Annotated[A1, Tag('A1')] | Annotated[A2, Tag('A2')]+++class M(BaseModel):+    a: TaggedAnyA = Field(discriminator=Discriminator(_discriminator))+""",+        globs,+    )++    M = globs['M']+    A1 = globs['A1']+    A2 = globs['A2']++    assert isinstance(M.model_validate({'a': {'type': 'A1'}}).a, A1)+    assert isinstance(M.model_validate({'a': {'type': 'A2'}}).a, A2) 
Merged fix · PR #13604+47 −13
pydantic/_internal/_discriminated_union.pyindex 94c82026c..64f231459 100644@@ -65,7 +65,7 @@ def apply_discriminator(         if isinstance(discriminator.discriminator, str):             discriminator = discriminator.discriminator         else:-            return discriminator._convert_schema(schema)+            return discriminator._convert_schema(schema, definitions=definitions)      return _ApplyInferredDiscriminator(discriminator, definitions or {}).apply(schema) pydantic/types.pyindex f32a2ab80..50f94cf43 100644@@ -3112,13 +3112,29 @@ class Discriminator:             return self._convert_schema(original_schema, handler)      def _convert_schema(-        self, original_schema: core_schema.CoreSchema, handler: GetCoreSchemaHandler | None = None+        self,+        original_schema: core_schema.CoreSchema,+        handler: GetCoreSchemaHandler | None = None,+        definitions: dict[str, core_schema.CoreSchema] | None = None,     ) -> core_schema.TaggedUnionSchema:-        if handler is not None and original_schema['type'] == 'definition-ref':+        def _resolve_ref(schema: core_schema.CoreSchema) -> core_schema.CoreSchema | None:+            # `handler` is set when this method is called while generating the schema for the field+            # (e.g. via `Annotated[<type>, Discriminator(...)]`). `definitions` is set instead when+            # this method is called from `apply_discriminator()` (deferred/callable discriminators).+            if handler is not None:+                try:+                    return handler.resolve_ref_schema(schema)+                except LookupError:  # pragma: no cover+                    return None+            elif definitions is not None:+                schema_ref = cast(core_schema.DefinitionReferenceSchema, schema)['schema_ref']+                return definitions.get(schema_ref)+            return None++        if original_schema['type'] == 'definition-ref':             # Same logic as `_ApplyInferredDiscriminator._apply_to_root()`-            try:-                def_schema = handler.resolve_ref_schema(original_schema)-            except LookupError:  # pragma: no cover+            def_schema = _resolve_ref(original_schema)+            if def_schema is None:                 from pydantic._internal._discriminated_union import MissingDefinitionForUnionRef                  raise MissingDefinitionForUnionRef(original_schema['schema_ref'])@@ -3144,14 +3160,11 @@ class Discriminator:             if metadata is not None:                 tag = metadata.get('pydantic_internal_union_tag_key') or tag             if tag is None:-                # `handler` is None when this method is called from `apply_discriminator()` (deferred discriminators)-                if handler is not None and choice['type'] == 'definition-ref':+                if choice['type'] == 'definition-ref':                     # If choice was built from a PEP 695 type alias, try to resolve the def:-                    try:-                        choice = handler.resolve_ref_schema(choice)-                    except LookupError:-                        pass-                    else:+                    resolved_choice = _resolve_ref(choice)+                    if resolved_choice is not None:+                        choice = resolved_choice                         metadata = cast('CoreMetadata | None', choice.get('metadata'))                         if metadata is not None:                             tag = metadata.get('pydantic_internal_union_tag_key')tests/types/unions/test_discriminated_union.pyindex fccb82fbb..637679102 100644@@ -2338,6 +2338,27 @@ def test_discriminated_union_type_alias_type_separate_callable_discriminator() -     assert m.g == Bar(type='bar')  +def test_discriminated_union_type_alias_type_separate_callable_discriminator_field() -> None:+    """https://github.com/pydantic/pydantic/issues/13599"""++    class Foo(BaseModel):+        type: Literal['foo']++    class Bar(BaseModel):+        type: Literal['bar']++    FooBar = TypeAliasType('FooBar', Annotated[Foo, Tag('foo')] | Annotated[Bar, Tag('bar')])++    discriminator = Discriminator(lambda v: v['type'])++    class Main(BaseModel):+        f: FooBar = Field(discriminator=discriminator)++    m = Main(f={'type': 'foo'})++    assert m.f == Foo(type='foo')++ @pytest.mark.xfail(     reason="Nested references aren't flattened (see comment in `_ApplyInferredDiscriminator._handle_choice()`)", ) 

What the agent reported

Summary

What was wrong: PEP 695 type X = ... statement aliases failed as the annotation for a field with a callable Discriminator when union members carried Tag(...), raising PydanticUserError:Tagnot provided for choice {'type': 'definition-ref', ...} used withDiscriminator``.

The root cause: a PEP 695 type statement wraps its union in a definition-ref (unlike the old-style TypeAlias, which produces an inline union). The callable-discriminator path in apply_discriminator (_discriminated_union.py:68) called Discriminator._convert_schema(schema) without forwarding the definitions dict, and _convert_schema only dereferenced definition-ref schemas when a handler was present. With no handler and no definitions, it couldn't resolve the ref to reach the tagged union, so it errored.

What I changed (minimal, 2 files):

  • pydantic/_internal/_discriminated_union.py:68 — forward the definitions dict: discriminator._convert_schema(schema, definitions=definitions).
  • pydantic/types.py — Discriminator._convert_schema gained a definitions parameter and a local resolve_ref_schema helper that resolves a definition-ref via the handler when present, else via the definitions dict, else raises LookupError. Both the top-level and per-choice definition-ref guards were broadened from handler is not None to (handler is not None or definitions is not None). Existing MissingDefinitionForUnionRef, except LookupError, and pydantic_internal_union_tag_key behavior preserved.

Test evidence:

  • Added test_callable_discriminator_pep695_type_alias in tests/types/unions/test_discriminated_union.py — gated with skipif(sys.version_info < (3, 12)), uses exec() to keep PEP 695 syntax out of module top-level, and asserts the discriminator routes {'type': 'A1'}→A1 and {'type': 'A2'}→A2. Confirmed failing before the fix (callable-discriminator-no-tag) and passing after.
  • Gate: ./bt-test tests/types/unions/test_discriminated_union.py tests/test_type_alias_type.py → 98 passed, 4 xfailed (the 4 xfails are pre-existing).
  • The report's full reproduction now prints M1 OK / M2 OK / M3 OK / M4 OK.
  • Reviewer confirmed the change mirrors existing handler-based resolution, preserves negative-path behavior, and introduces no unrelated changes.

Requirements list:

  1. M3 — PEP 695 type alias + callable Discriminator + Tag must work → Implemented, with regression test (fails before, passes after).
  2. "Example Code from #12843 also doesn't work" → The #12843 scenario is the TypeAliasType(...) constructor form, already covered by the passing test_discriminated_union_type_alias_type_separate_callable_discriminator; the PEP 695 type-statement variant of that same shape is now fixed by this change and exercised by the new test. Addressed.
  3. M1, M2, M4 must remain working → Verified still pass (repro prints OK for all; gate green).