Backtestspydanticrun-20260930-183947#13631

Issue #13631 Merged fix PR #13632 Run 30 Sep 2026 · run-20260930-183947 pydantic/pydantic

JSON schema discriminator mapping uses Python-style True/False keys for bool discriminators

Better

Our patch was judged better than the merged fix.

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

Both patches fix the literal case from the issue: `Literal[True]`/`Literal[False]` discriminator keys become `"true"`/`"false"`. The difference is where the bool check runs relative to Enum normalization. Patch A checks `isinstance(k, bool)` after `k = k.value`, so an Enum member whose value is a bool is also written with its JSON form. Patch B uses `elif isinstance(k, bool)`, which runs only when `k` is not an Enum. A bool-valued Enum member is unwrapped to `True`/`False` and then passes through `str(k)`, so it still produces `"True"`/`"False"`. That leaves the same spec mismatch the issue describes, since such a payload also serializes as JSON `true`/`false`. The issue itself points out that Enum keys are normalized to `k.value` before stringification, so handling bools after that step is the more complete fix. On tests: both add a test that fails before the change and passes after it for the issue's example. Patch B asserts the whole schema; Patch A asserts only the relevant property. Patch A also adds a bool-valued Enum test covering the case Patch B misses. Both changes are small and in scope. Patch A's inline key expression is slightly less tidy than Patch B's separate branch, but Patch A is more correct and 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

6m

Wall-clock time in the container

Full test suite

No new failures

12,327 passed · 500 skipped · 12,827 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

47vs 51 merged

Changed lines, ours vs merged

Initial 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.0

The two patches

Our patch+45 −2
pydantic/json_schema.pyindex f6da6fc3..cf6f77de 100644@@ -1382,8 +1382,10 @@ class GenerateJsonSchema:                 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()+                # it's the closest that can be represented in valid JSON.+                # Booleans use their JSON representation, so that keys match the serialized discriminator value:+                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..f74632e2 100644@@ -4523,6 +4523,47 @@ 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: 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 Toggle(Enum):+        on = True+        off = False++    class On(BaseModel):+        state: Literal[Toggle.on]++    class Off(BaseModel):+        state: Literal[Toggle.off]++    class Model(BaseModel):+        setting: On | Off = Field(discriminator='state')++    assert Model.model_json_schema()['properties']['setting']['discriminator'] == {+        'mapping': {'false': '#/$defs/Off', 'true': '#/$defs/On'},+        'propertyName': 'state',+    }++ def test_discriminated_union_in_list():     class BlackCat(BaseModel):         pet_type: Literal['cat'] 
Merged fix · PR #13632+51 −0
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']