Backtestspydanticrun-20261003-150343#13599

Issue #13599 Merged fix PR #13604 Run 3 Oct 2026 · run-20261003-150343 pydantic/pydantic

PEP 695 type aliases don't work with callable discriminators

Better

Our patch was judged better than the merged fix.

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

Both patches fix the root cause the same way. They pass `definitions` from `apply_discriminator()` into `Discriminator._convert_schema()`, so definition-refs created by PEP 695 aliases can be resolved when the discriminator is applied through `Field(discriminator=...)`. Both would fix the M3 case in the issue.

The differences show up at the edges:

1. **Recursive or forward-referenced aliases.** Patch B handles an alias choice whose definition isn't available yet by raising `MissingDefinitionForUnionRef`. This lets the discriminator application be deferred, mirroring `_ApplyInferredDiscriminator._handle_choice()`. Patch A falls through to the `Tag not provided` `PydanticUserError` instead, so recursive alias cases are likely to fail with a misleading error rather than being deferred.

2. **Behavior when nothing can resolve the ref.** Patch A drops the `handler is not None` guard on the root definition-ref check. When both `handler` and `definitions` are None, it now raises `MissingDefinitionForUnionRef`, which is a behavior change from before. Patch B keeps that path guarded.

3. **Choice handling.** Patch B leaves the choice as a reference and only reads tag metadata from the resolved definition. Patch A replaces the choice with the inlined definition schema, which is less faithful to reference semantics in the deferred path.

**Tests.** Patch A adds one basic test for the issue scenario. Patch B adds that scenario plus coverage for:
- a generic alias with type params,
- alias-typed union members,
- invalid-tag errors,
- two recursive alias cases that exercise the new deferral path.

These tests would fail before the change and meaningfully cover the edges.

**Craft.** Patch B also simplifies the tag logic and documents the method. Overall, Patch B is more correct at the edges and much better tested.

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

16m 1s

Wall-clock time in the container

Full test suite

No new failures

12,324 passed · 499 skipped · 12,823 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

175vs 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+152 −23
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..5d56f6dc 100644@@ -3112,13 +3112,32 @@ 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':+        """Convert `original_schema` (expected to be a union schema) into a tagged union schema.++        Definition references (e.g. created from PEP 695 type aliases) are resolved either using+        the `handler` (when used as an annotation) or the `definitions` mapping (when the discriminator+        is applied by `apply_discriminator()`, e.g. when using `Field(discriminator=...)`).+        """++        def resolve_ref(schema: core_schema.DefinitionReferenceSchema) -> core_schema.CoreSchema | None:+            if handler is not None:+                try:+                    return handler.resolve_ref_schema(schema)+                except LookupError:+                    return None+            if definitions is not None:+                return definitions.get(schema['schema_ref'])+            return None++        if original_schema['type'] == 'definition-ref' and (handler is not None or definitions is not None):             # 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'])@@ -3143,24 +3162,24 @@ class Discriminator:             metadata = cast('CoreMetadata | None', choice.get('metadata'))             if metadata is not None:                 tag = metadata.get('pydantic_internal_union_tag_key') or tag+            if tag is None and choice['type'] == 'definition-ref':+                # If choice was built from a PEP 695 type alias, try to resolve the def:+                resolved_choice = resolve_ref(choice)+                if resolved_choice is not None:+                    metadata = cast('CoreMetadata | None', resolved_choice.get('metadata'))+                    if metadata is not None:+                        tag = metadata.get('pydantic_internal_union_tag_key')+                elif handler is None and definitions is not None:+                    # The definition isn't available yet (e.g. recursive type alias), defer the discriminator+                    # application (same logic as `_ApplyInferredDiscriminator._handle_choice()`):+                    from pydantic._internal._discriminated_union import MissingDefinitionForUnionRef++                    raise MissingDefinitionForUnionRef(choice['schema_ref'])             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 was built from a PEP 695 type alias, try to resolve the def:-                    try:-                        choice = handler.resolve_ref_schema(choice)-                    except LookupError:-                        pass-                    else:-                        metadata = cast('CoreMetadata | None', choice.get('metadata'))-                        if metadata is not None:-                            tag = metadata.get('pydantic_internal_union_tag_key')--                if tag is None:-                    raise PydanticUserError(-                        f'`Tag` not provided for choice {choice} used with `Discriminator`',-                        code='callable-discriminator-no-tag',-                    )+                raise PydanticUserError(+                    f'`Tag` not provided for choice {choice} used with `Discriminator`',+                    code='callable-discriminator-no-tag',+                )             tagged_union_choices[tag] = choice          # Have to do these verbose checks to ensure falsy values ('' and {}) don't get ignoredtests/types/unions/test_discriminated_union.pyindex fccb82fb..c8857d77 100644@@ -2338,6 +2338,116 @@ 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/13598"""++    class Foo(BaseModel):+        type: Literal['foo']++    class Bar(BaseModel):+        type: Literal['bar']++    FooBar = TypeAliasType('FooBar', Annotated[Foo, Tag('foo')] | Annotated[Bar, Tag('bar')])++    T = TypeVar('T')++    FooBarTV = TypeAliasType('FooBarTV', Annotated[Foo, Tag('foo')] | Annotated[Bar, Tag('bar')], type_params=(T,))++    class Main(BaseModel):+        f: FooBar = Field(discriminator=Discriminator(lambda v: v['type']))+        g: FooBarTV[int] = Field(discriminator=Discriminator(lambda v: v['type']))++    m = Main(f={'type': 'foo'}, g={'type': 'bar'})++    assert m.f == Foo(type='foo')+    assert m.g == Bar(type='bar')++    with pytest.raises(ValidationError) as exc_info:+        Main(f={'type': 'baz'}, g={'type': 'foo'})++    assert exc_info.value.errors(include_url=False)[0]['type'] == 'union_tag_invalid'+++def test_discriminated_union_type_alias_type_choices_callable_discriminator_field() -> None:+    """https://github.com/pydantic/pydantic/issues/13598"""++    class Foo(BaseModel):+        type: Literal['foo']++    class Bar(BaseModel):+        type: Literal['bar']++    TaggedFoo = TypeAliasType('TaggedFoo', Annotated[Foo, Tag('foo')])+    TaggedBar = TypeAliasType('TaggedBar', Annotated[Bar, Tag('bar')])+    FooBar = TypeAliasType('FooBar', Union[TaggedFoo, TaggedBar])++    class Main(BaseModel):+        f: Union[TaggedFoo, TaggedBar] = Field(discriminator=Discriminator(lambda v: v['type']))+        g: FooBar = Field(discriminator=Discriminator(lambda v: v['type']))++    m = Main(f={'type': 'bar'}, g={'type': 'foo'})++    assert m.f == Bar(type='bar')+    assert m.g == Foo(type='foo')+++def test_discriminated_union_recursive_type_alias_type_callable_discriminator_field() -> None:+    """https://github.com/pydantic/pydantic/issues/13598++    The discriminator is deferred, as the type alias definition is not available yet.+    """++    class Leaf(BaseModel):+        type: Literal['leaf'] = 'leaf'++    class Node(BaseModel):+        type: Literal['node'] = 'node'+        child: 'Tree' = Field(discriminator=Discriminator(lambda v: v['type'] if isinstance(v, dict) else v.type))++    Tree = TypeAliasType('Tree', Annotated[Leaf, Tag('leaf')] | Annotated[Node, Tag('node')])+    Node.model_rebuild()++    ta = TypeAdapter(Tree)+    node = ta.validate_python({'type': 'node', 'child': {'type': 'node', 'child': {'type': 'leaf'}}})++    assert node == Node(child=Node(child=Leaf()))++    with pytest.raises(ValidationError) as exc_info:+        Node.model_validate({'child': {'type': 'node', 'child': {'type': 'other'}}})++    errors = exc_info.value.errors(include_url=False)+    assert len(errors) == 1+    assert errors[0]['type'] == 'union_tag_invalid'+    assert errors[0]['loc'] == ('child', 'node', 'child')+++def test_discriminated_union_recursive_type_alias_type_choice_callable_discriminator_field() -> None:+    """https://github.com/pydantic/pydantic/issues/13598++    The discriminator is deferred, as the definition of a type alias choice is not available yet.+    """++    class Leaf(TypedDict):+        kind: Literal['leaf']++    TLeaf = TypeAliasType('TLeaf', Annotated[Leaf, Tag('leaf')])+    TNode = TypeAliasType('TNode', Annotated['Node', Tag('node')])++    class Node(TypedDict):+        kind: Literal['node']+        child: Annotated[Union[TLeaf, TNode], Field(discriminator=Discriminator(lambda v: v['kind']))]++    ta = TypeAdapter(TNode)+    data = {'kind': 'node', 'child': {'kind': 'node', 'child': {'kind': 'leaf'}}}++    assert ta.validate_python(data) == data++    with pytest.raises(ValidationError) as exc_info:+        ta.validate_python({'kind': 'node', 'child': {'kind': 'other'}})++    assert exc_info.value.errors(include_url=False)[0]['type'] == 'union_tag_invalid'++ @pytest.mark.xfail(     reason="Nested references aren't flattened (see comment in `_ApplyInferredDiscriminator._handle_choice()`)", ) 
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()`)", )