Backtestspydanticrun-20261027-165153#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 change `GenerateJsonSchema.tagged_union_schema` to emit `true`/`false` keys for bool discriminators, and both pass the core scenarios from the issue (plain Literal[True]/Literal[False], TypeAdapter annotated union, mixed bool/string literals). The difference is ordering relative to the existing Enum normalization. Patch A applies the bool check after `k = k.value`, so an Enum whose member values are True/False also yields `true`/`false`. Patch B uses `elif isinstance(k, bool)`, so once a key is an Enum it is unwrapped to a raw bool and then falls through to `str(k)`, producing `True`/`False` again. The issue explicitly points at the Enum-to-value normalization as the path bool keys sit next to, and an Enum with bool values serializes to JSON `true`/`false` just like a bare bool, so B leaves a directly adjacent instance of the same bug in place. The independent test for that case confirms it: A passes, B fails with the old `'False'`/`'True'` keys. On tests, A adds two targeted tests (plain bool and bool-valued Enum) that would fail before and pass after; B adds one full-schema assertion that covers the plain case well but not the Enum case. Scope and craft are comparable: both are small, localized edits with reasonable comments, and A's inline conditional is slightly denser but clear. A is the more complete root-cause 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
5m 12s
Wall-clock time in the container
Full test suite
No new failures
1,218 passed · 15 skipped · 1,233 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
50vs 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..ae08488a 100644@@ -1381,9 +1381,12 @@ class GenerateJsonSchema: if isinstance(k, Enum): k = k.value 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 JSON- generated[str(k)] = self.generate_inner(v).copy()+ # Keys must be strings for json. Bools are rendered as their JSON serialization+ # (`true`/`false`), so that OpenAPI discriminator mapping keys match the payload value.+ # Otherwise use str(k); while not technically correct, it's the closest that can be represented+ # in valid JSON+ key = ('true' if k else 'false') if isinstance(k, bool) else str(k)+ generated[key] = self.generate_inner(v).copy() except PydanticOmit: continue except PydanticInvalidForJsonSchema as exc:tests/test_json_schema.pyindex 077116ff..04d8098f 100644@@ -7280,3 +7280,44 @@ 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():+ 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': {+ 'mapping': {'false': '#/$defs/Disabled', 'true': '#/$defs/Enabled'},+ 'propertyName': 'enabled',+ },+ 'oneOf': [{'$ref': '#/$defs/Enabled'}, {'$ref': '#/$defs/Disabled'}],+ 'title': 'Setting',+ }+++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: On | Off = Field(discriminator='flag')++ assert Model.model_json_schema()['properties']['setting']['discriminator'] == {+ 'mapping': {'false': '#/$defs/Off', 'true': '#/$defs/On'},+ 'propertyName': 'flag',+ }
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']