Backtestspydanticrun-20261003-150343#13631
JSON schema discriminator mapping uses Python-style True/False keys for bool 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 reported case by mapping plain `bool` discriminator keys to `'true'`/`'false'` before stringification in `tagged_union_schema`. Correctness favors B. Patch A adds the bool check as an `elif` after the `Enum` branch. An `Enum` whose values are booleans has its key converted to `True`/`False` via `k.value`, then skips the bool branch and still falls through to `str(k)`. That yields `'True'`/`'False'`, the same bug the issue describes, reached through the Enum normalization path the issue explicitly mentions. Patch B uses a separate `if` after the Enum unwrap, so bool-valued Enums are normalized correctly too. B also maps `None` keys (`Literal[None]` discriminators) to `'null'`. This is the same class of bug (Python repr instead of JSON serialization) and adds little risk. Tests favor B. B tests the plain bool case, the bool-valued Enum case (which would fail under Patch A), and the None case, with focused assertions on the discriminator object. A has one full-schema test for the basic case only. Scope and craft are both fine. B's extra None handling is a small, consistent hardening with a clear explanatory comment. Overall, B is the more complete and correct fix.
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 34s
Wall-clock time in the container
Full test suite
No new failures
12,328 passed · 500 skipped · 12,828 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
58vs 51 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
When a discriminated union uses a bool discriminator (Literal[True] / Literal[False]), the generated JSON schema's discriminator.mapping uses the Python string representations "True" and "False" as keys:
"discriminator": {
"mapping": {"False": "#/$defs/Disabled", "True": "#/$defs/Enabled"},
"propertyName": "enabled"
}
Per the OpenAPI discriminator specification, mapping keys must match the serialized payload value of the discriminator property. For a boolean property, that value serializes to JSON true/false, so the keys should be "true" and "false". Tooling that resolves the mapping against the payload (code generators, validators such as openapi-generator or Redocly) fails to match either variant.
Expected:
"mapping": {"false": "#/$defs/Disabled", "true": "#/$defs/Enabled"}
Note that Enum discriminator keys are already normalized to their value (k.value) before stringification in GenerateJsonSchema.tagged_union_schema; bool keys just fall through to str(k).
Example Code
from typing import Literal
from pydantic import BaseModel, Field
class Enabled(BaseModel):
enabled: Literal[True]
config: str
class Disabled(BaseModel):
enabled: Literal[False]
class Model(BaseModel):
setting: Enabled | Disabled = Field(discriminator='enabled')
print(Model.model_json_schema()['properties']['setting']['discriminator'])
# {'propertyName': 'enabled', 'mapping': {'True': '#/$defs/Enabled', 'False': '#/$defs/Disabled'}}
Python, Pydantic & OS Version
pydantic version: 2.14.0b1
pydantic-core version: 2.48.0
pydantic-core build: profile=debug pgo=false
python version: 3.11.15 (main, Apr 14 2026, 14:28:36) [Clang 22.1.3 ]
platform: Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.41
related packages: typing_extensions-4.15.0The two patches
pydantic/json_schema.pyindex f6da6fc3..be810a42 100644@@ -1380,6 +1380,11 @@ class GenerateJsonSchema: for k, v in schema['choices'].items(): if isinstance(k, Enum): k = k.value+ # Mapping keys must match the JSON-serialized discriminator value (e.g. `true`, not `True`):+ if isinstance(k, bool):+ k = 'true' if k else 'false'+ elif k is None:+ k = 'null' try: # Use str(k) since keys must be strings for json; while not technically correct, # it's the closest that can be represented in valid JSONtests/test_json_schema.pyindex 077116ff..78479b97 100644@@ -4523,6 +4523,59 @@ def test_stdlib_dataclass_custom_docstring_preserved() -> None: assert 'description' not in schema_without_doc +def test_discriminated_union_bool_discriminator_mapping_keys():+ class Enabled(BaseModel):+ enabled: Literal[True]+ config: str++ class Disabled(BaseModel):+ enabled: Literal[False]++ class Model(BaseModel):+ setting: Union[Enabled, Disabled] = Field(discriminator='enabled')++ assert Model.model_json_schema()['properties']['setting']['discriminator'] == {+ 'propertyName': 'enabled',+ 'mapping': {'true': '#/$defs/Enabled', 'false': '#/$defs/Disabled'},+ }+++def test_discriminated_union_bool_enum_discriminator_mapping_keys():+ class Flag(Enum):+ on = True+ off = False++ class On(BaseModel):+ flag: Literal[Flag.on]++ class Off(BaseModel):+ flag: Literal[Flag.off]++ class Model(BaseModel):+ setting: Union[On, Off] = Field(discriminator='flag')++ assert Model.model_json_schema()['properties']['setting']['discriminator'] == {+ 'propertyName': 'flag',+ 'mapping': {'true': '#/$defs/On', 'false': '#/$defs/Off'},+ }+++def test_discriminated_union_none_discriminator_mapping_keys():+ class Missing(BaseModel):+ kind: Literal[None]++ class Named(BaseModel):+ kind: Literal['named']++ class Model(BaseModel):+ value: Union[Missing, Named] = Field(discriminator='kind')++ assert Model.model_json_schema()['properties']['value']['discriminator'] == {+ 'propertyName': 'kind',+ 'mapping': {'null': '#/$defs/Missing', 'named': '#/$defs/Named'},+ }++ def test_discriminated_union_in_list(): class BlackCat(BaseModel): pet_type: Literal['cat']
pydantic/json_schema.pyindex f6da6fc34..c61378a5f 100644@@ -1380,6 +1380,10 @@ class GenerateJsonSchema: for k, v in schema['choices'].items(): if isinstance(k, Enum): k = k.value+ elif isinstance(k, bool):+ # Use the JSON representation so that the discriminator mapping+ # can be matched against the serialized payload value+ k = 'true' if k else 'false' try: # Use str(k) since keys must be strings for json; while not technically correct, # it's the closest that can be represented in valid JSONtests/test_json_schema.pyindex 077116ffa..2d67f01ae 100644@@ -3973,6 +3973,53 @@ def test_discriminated_annotated_union(): } +def test_bool_discriminated_union() -> None:+ """https://github.com/pydantic/pydantic/issues/13631"""++ class Enabled(BaseModel):+ enabled: Literal[True]+ config: str++ class Disabled(BaseModel):+ enabled: Literal[False]++ class Model(BaseModel):+ setting: Enabled | Disabled = Field(discriminator='enabled')++ assert Model.model_json_schema() == {+ '$defs': {+ 'Disabled': {+ 'properties': {'enabled': {'const': False, 'title': 'Enabled', 'type': 'boolean'}},+ 'required': ['enabled'],+ 'title': 'Disabled',+ 'type': 'object',+ },+ 'Enabled': {+ 'properties': {+ 'config': {'title': 'Config', 'type': 'string'},+ 'enabled': {'const': True, 'title': 'Enabled', 'type': 'boolean'},+ },+ 'required': ['enabled', 'config'],+ 'title': 'Enabled',+ 'type': 'object',+ },+ },+ 'properties': {+ 'setting': {+ 'discriminator': {+ 'mapping': {'false': '#/$defs/Disabled', 'true': '#/$defs/Enabled'},+ 'propertyName': 'enabled',+ },+ 'oneOf': [{'$ref': '#/$defs/Enabled'}, {'$ref': '#/$defs/Disabled'}],+ 'title': 'Setting',+ }+ },+ 'required': ['setting'],+ 'title': 'Model',+ 'type': 'object',+ }++ def test_nested_discriminated_union(): class BlackCatWithHeight(BaseModel): color: Literal['black']