Backtestspydanticrun-20261005-183002#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 A = our agent, Patch B = the merged fix.
Both patches map plain `bool` discriminator keys to 'true'/'false', which fixes the reported example. The difference is in branch structure. Patch A uses a separate `if isinstance(k, bool)` after the Enum normalization. A bool-valued Enum (e.g. `Flag.on = True`) is first unwrapped to `True` and then converted to 'true'. Patch B uses `elif`, so that bool check never runs for Enum keys. A bool-valued Enum would still produce `str(True)` == 'True', the same OpenAPI mismatch the issue describes. Patch A therefore fixes the root cause (keys should match the JSON-serialized value) more completely, and it adds a test for exactly that Enum case. Patch A also maps `None` to 'null', following the same JSON-representation logic. That is a small, consistent extension backed by a test that checks validation still works, so it adds little risk. On tests, both would fail before and pass after for the basic bool case. Patch B's full-schema assertion is more brittle and covers only that one case. Patch A's tests are targeted and cover the Enum and None edge cases. On scope and craft, both are minimal and readable, but Patch B's `elif` is a real correctness gap rather than a style choice.
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
8m 31s
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
60vs 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..be19c400 100644@@ -1380,6 +1380,11 @@ class GenerateJsonSchema: for k, v in schema['choices'].items(): if isinstance(k, Enum): k = k.value+ if isinstance(k, bool):+ # Use the JSON representation so that keys match the serialized discriminator value+ 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..498a1585 100644@@ -7280,3 +7280,58 @@ def test_nested_model_deduplication() -> None: assert 'Level1' in definitions assert 'Level1-Input' not in definitions assert 'Level1-Output' not in definitions+++def test_discriminated_union_bool_discriminator_mapping_keys() -> None:+ 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()['properties']['setting']['discriminator'] == {+ 'propertyName': 'enabled',+ 'mapping': {'true': '#/$defs/Enabled', 'false': '#/$defs/Disabled'},+ }+++def test_discriminated_union_bool_enum_discriminator_mapping_keys() -> None:+ class Flag(Enum):+ on = True+ off = False++ class On(BaseModel):+ flag: Literal[Flag.on]++ class Off(BaseModel):+ flag: Literal[Flag.off]++ class Model(BaseModel):+ value: On | Off = Field(discriminator='flag')++ assert Model.model_json_schema()['properties']['value']['discriminator'] == {+ 'propertyName': 'flag',+ 'mapping': {'true': '#/$defs/On', 'false': '#/$defs/Off'},+ }+++def test_discriminated_union_none_discriminator_mapping_keys() -> None:+ class Unset(BaseModel):+ kind: Literal[None]++ class Named(BaseModel):+ kind: Literal['named']+ name: str++ class Model(BaseModel):+ value: Unset | Named = Field(discriminator='kind')++ assert Model.model_validate({'value': {'kind': None}}).value == Unset(kind=None)+ assert Model.model_json_schema()['properties']['value']['discriminator'] == {+ 'propertyName': 'kind',+ 'mapping': {'null': '#/$defs/Unset', 'named': '#/$defs/Named'},+ }
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']