Backtestspydanticrun-20261002-175417#13631

Issue #13631 Merged fix PR #13632 Run 2 Oct 2026 · run-20261002-175417 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 core case: a plain `Literal[True]`/`Literal[False]` discriminator now produces `'true'`/`'false'` mapping keys instead of Python's `str()` output. Both add a test that would fail before the change and pass after it.

The deciding difference is control flow after Enum normalization. Patch B uses `elif isinstance(k, bool)`, so an Enum whose value is a bool (e.g. `Flag.on = True`) is unwrapped by `k = k.value` but then skips the bool branch. It still emits `'True'`/`'False'`, so B leaves an adjacent instance of the same bug the issue describes. The issue points out that Enum keys are normalized to `.value` before stringification, which makes bool-valued enums a natural follow-on case.

Patch A uses a separate `if` after the Enum unwrap, so bool-valued enums are normalized correctly, and it includes a test for exactly that scenario. Patch A also maps `None` to `'null'`. This follows the same JSON-serialization principle, carries low risk, and is tested, so it is at worst neutral.

On tests, B's full-schema assertion is more exhaustive for the one case it covers. A covers more of the relevant edge cases with focused assertions on the discriminator mapping.

Overall, A is more correct at the root cause (map the post-normalization value to its JSON form) 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

8m 57s

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

62vs 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+62 −0
pydantic/json_schema.pyindex f6da6fc3..bbebc8cd 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):+                # Mapping keys must match the JSON-serialized discriminator value (`true`/`false`, not `True`/`False`)+                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..01090cb6 100644@@ -4523,6 +4523,63 @@ 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 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',+    }+++def test_discriminated_union_none_discriminator_mapping_keys():+    class Unset(BaseModel):+        kind: Literal[None]++    class Named(BaseModel):+        kind: Literal['named']++    class Model(BaseModel):+        value: Unset | Named = Field(discriminator='kind')++    assert Model.model_json_schema()['properties']['value']['discriminator'] == {+        'mapping': {'named': '#/$defs/Named', 'null': '#/$defs/Unset'},+        'propertyName': 'kind',+    }++ 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']