Backtestspydanticrun-20260930-144322#13599
PEP 695 type aliases don't work with callable discriminators
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. `_convert_schema` gains a `definitions` mapping, and `apply_discriminator` passes it along. That lets the deferred path used by `Field(discriminator=Discriminator(callable))` resolve `definition-ref` schemas produced by PEP 695 / `TypeAliasType` aliases, both for the top-level union and for individual choices. Without this, tags on those schemas are never found, which is the `Tag not provided` error in the issue. The two resolution helpers behave essentially the same: each tries the handler first, then the definitions dict, and raises `MissingDefinitionForUnionRef` when a top-level ref is missing. B always passes a dict (`definitions or {}`) and uses a single LookupError-raising helper, which keeps the existing try/except structure. A returns None from its helper and rewrites the control flow; this is fine but slightly more churn. A also swallows `LookupError` behind a `pragma: no cover`. The deciding factor is tests. A adds one test that covers the basic union alias case and only checks the happy path. B parametrizes the union alias case and a case where an individual member is an alias-wrapped tagged type. It checks both tags and asserts a `union_tag_invalid` error for a bad tag. It also adds a recursive type alias case, which exercises the ref-resolution path through definitions more thoroughly. Correctness is equivalent, so B's stronger and broader tests make it the better patch.
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
6m 41s24 turns
Wall-clock time in the container
Full test suite
No new failures
12,323 passed · 499 skipped · 12,822 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
81vs 60 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial 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: unknownThe two patches
pydantic/_internal/_discriminated_union.pyindex 94c82026..abc5aa25 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 or {}) return _ApplyInferredDiscriminator(discriminator, definitions or {}).apply(schema) pydantic/types.pyindex f32a2ab8..65c0df21 100644@@ -3112,13 +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':+ # `definitions` is used to resolve refs when called from `apply_discriminator()` (no `handler` available):+ def resolve_ref_schema(schema: core_schema.DefinitionReferenceSchema) -> core_schema.CoreSchema:+ if handler is not None:+ return handler.resolve_ref_schema(schema)+ if definitions is not None and schema['schema_ref'] in definitions:+ return definitions[schema['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)- except LookupError: # pragma: no cover+ def_schema = resolve_ref_schema(original_schema)+ except LookupError: from pydantic._internal._discriminated_union import MissingDefinitionForUnionRef raise MissingDefinitionForUnionRef(original_schema['schema_ref'])@@ -3144,11 +3155,10 @@ 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 (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..19e694d4 100644@@ -2338,6 +2338,61 @@ def test_discriminated_union_type_alias_type_separate_callable_discriminator() - assert m.g == Bar(type='bar') +def _get_type_discriminator_value(data: Any) -> Any:+ if isinstance(data, dict):+ return data.get('type')+ return getattr(data, 'type_', None)+++class _A1(BaseModel):+ type_: Literal['A1'] = Field(alias='type')+++class _A2(BaseModel):+ type_: Literal['A2'] = Field(alias='type')+++_TaggedAnyA = TypeAliasType('_TaggedAnyA', Annotated[_A1, Tag('A1')] | Annotated[_A2, Tag('A2')])+_TaggedA1 = TypeAliasType('_TaggedA1', Annotated[_A1, Tag('A1')])+++@pytest.mark.parametrize(+ 'annotation',+ [+ pytest.param(_TaggedAnyA, id='union_type_alias'),+ pytest.param(_TaggedA1 | Annotated[_A2, Tag('A2')], id='tagged_member_type_alias'),+ ],+)+def test_callable_discriminator_field_type_alias(annotation: Any) -> None:+ """A callable `Discriminator` set through `Field(discriminator=...)` should support+ type aliases the same way as the `Annotated[Alias, Discriminator(...)]` form.+ """++ class Model(BaseModel):+ a: annotation = Field(discriminator=Discriminator(_get_type_discriminator_value))++ assert isinstance(Model.model_validate({'a': {'type': 'A1'}}).a, _A1)+ assert isinstance(Model.model_validate({'a': {'type': 'A2'}}).a, _A2)++ with pytest.raises(ValidationError) as exc_info:+ Model.model_validate({'a': {'type': 'B'}})++ assert exc_info.value.errors(include_url=False)[0]['type'] == 'union_tag_invalid'+++def test_callable_discriminator_field_recursive_type_alias() -> None:+ RecursiveAlias = TypeAliasType(+ 'RecursiveAlias',+ Annotated[int, Tag('int')] | Annotated[list['RecursiveAlias'], Tag('list')],+ )++ class Model(BaseModel):+ a: RecursiveAlias = Field(discriminator=Discriminator(lambda v: 'list' if isinstance(v, list) else 'int'))++ assert Model.model_validate({'a': [1, [2]]}).a == [1, [2]]+ assert Model.model_validate({'a': 1}).a == 1++ @pytest.mark.xfail( reason="Nested references aren't flattened (see comment in `_ApplyInferredDiscriminator._handle_choice()`)", )
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
I fixed it: a PEP 695 type alias now works with Field(discriminator=Discriminator(fn)), and your M3 case validates. The full test suite passes apart from one failure that also happens without my change (explained below). Nothing is committed.
What was wrong
There are two ways to attach a callable Discriminator, and they took different code paths:
Annotated[Alias, Discriminator(fn)]already worked, because the schema handler resolves the alias's reference to its definition (support added in #11941).Field(discriminator=Discriminator(fn))goes throughapply_discriminator(), which calledDiscriminator._convert_schema(schema)without a handler. The alias therefore stayed as an unresolveddefinition-ref, got treated as a one-member union with noTag, and raised`Tag` not provided for choice {'type': 'definition-ref', ...}. The string-discriminator path (M1) worked because it resolves references from thedefinitionsmapping it is given.
What I changed
pydantic/_internal/_discriminated_union.py:apply_discriminatornow passes itsdefinitionsmapping to_convert_schema.pydantic/types.py:_convert_schematakes an optionaldefinitionsargument. A small localresolve_ref_schemauses the handler when there is one and otherwise looks the reference up indefinitions. That covers both the alias itself and alias members inside a union.- When no handler is passed and the alias's definition isn't built yet, it raises
MissingDefinitionForUnionRefso building the schema is postponed, as the string-discriminator path already does. - Behaviour when a handler is passed is unchanged.
Tests
- New tests in
tests/types/unions/test_discriminated_union.py, all right aftertest_discriminated_union_type_alias_type_separate_callable_discriminator: test_callable_discriminator_field_type_alias[union_type_alias]: your M3 scenario, usingTypeAliasType(what atypestatement creates).test_callable_discriminator_field_type_alias[tagged_member_type_alias]: an alias of a single tagged model used as one member of a union.test_callable_discriminator_field_recursive_type_alias: an alias that refers to itself, which exercises the postponed path.
Each checks that the right model or value comes back, and the first two also check that an unknown tag raises union_tag_invalid. All three fail with the reported error without the fix and pass with it.
- Manual check: with real
typestatements on Python 3.13, the Field form and the Annotated form both validate. A self-referencing model with a callable discriminator still works. - Targeted
./bt-teston the union, type-alias, forward-ref, JSON-schema, generics, types, main and edge-case tests: 2402 passed, 0 failed. - Full
./bt-test: 12322 passed, 1 failed. The failure istests/test_validators.py::test_v1_validator_deprecated, which expects a file under/work/while this checkout is at/workspace/. It fails the same way with my change removed, so it comes from the environment, not this fix. - Review: the reviewer found no blocking issues. The one gap it raised (nothing tested the postponed path) is covered by the recursive-alias test.
Requirements
- M3 (PEP 695 alias of tagged union +
Field(discriminator=Discriminator(fn))) raises "Tag not provided": fixed, covered by theunion_type_aliastest. - M1, M2, M4 keep working: they use the string path or no alias, which this change doesn't touch; the whole discriminated-union test file and the full suite pass.
- "Example Code from #12843 also doesn't work": that issue's code isn't in the report and I couldn't look it up offline. I covered the likely variants instead: an alias used as one union member (
tagged_member_type_alias) and a recursive alias. Both failed with the same error before the fix and pass now. It's worth running #12843's actual example to confirm.
One small limitation remains, and it isn't new: if an alias used as one member of a union isn't built yet (for example, an alias that refers to itself and carries its own Tag), you still get the Tag error rather than a postponed build.