Backtestspydanticrun-20260930-144322#13631

Issue #13631 Merged fix PR #13632 Run 30 Sep 2026 · run-20260930-144322 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 root cause the same way: `bool` discriminator keys become `'true'`/`'false'` before the `str(k)` fallback in `tagged_union_schema`. Both add a test that fails before the change and passes after. The deciding difference is control flow. Patch A uses a separate `if isinstance(k, bool)` after the Enum normalization, so an Enum whose value is a bool is unwrapped to `True`/`False` and then also converted to `'true'`/`'false'`. Patch B uses `elif`, so such an Enum key would still stringify to `'True'`/`'False'`. That is the same bug the issue reports, just reached through an Enum. Patch A is therefore more complete for serialized-payload matching. On tests, Patch B asserts the full schema, which is more thorough but more brittle and unrelated to the fix. It also leaves a placeholder `"""<link>"""` docstring. Patch A's test targets exactly the discriminator mapping the issue is about. Scope and craft are otherwise comparable. Patch A wins on the correctness edge case.

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

56s12 turns

Wall-clock time in the container

Full test suite

No new failures

12,326 passed · 500 skipped · 12,826 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

20vs 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+20 −0
pydantic/json_schema.pyindex f6da6fc3..cd8d3084 100644@@ -1380,6 +1380,9 @@ class GenerateJsonSchema:         for k, v in schema['choices'].items():             if isinstance(k, Enum):                 k = k.value+            if isinstance(k, bool):+                # Use the JSON representation (`true`/`false`) so mapping keys match the serialized payload+                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 077116ff..f225c9c0 100644@@ -4416,6 +4416,23 @@ def test_discriminated_annotated_union_literal_enum():     }  +def test_discriminated_union_literal_bool_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',+    }++ def test_alias_same():     class Cat(BaseModel):         pet_type: Literal['cat'] = Field(alias='typeOfPet') 
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'] 

What the agent reported

I fixed the bug: bool discriminators now produce "true" / "false" as mapping keys instead of "True" / "False". The new regression test failed before the change and passes after it, and the nearby existing tests still pass.

What was wrong: In GenerateJsonSchema.tagged_union_schema (pydantic/json_schema.py), Enum keys were already converted to their .value, but every other key went through str(k). For a bool, that gives Python's "True" / "False", which doesn't match the JSON value true / false that OpenAPI tooling compares against.

What I changed:

  • pydantic/json_schema.py:1383: after the Enum step, a bool key now becomes 'true' or 'false'. Because this runs after the Enum step, an Enum whose value is a bool gets the same treatment.
  • Test: I added test_discriminated_union_literal_bool_mapping_keys to tests/test_json_schema.py. It uses the exact Enabled / Disabled models from the report and checks that the discriminator is {'mapping': {'false': '#/$defs/Disabled', 'true': '#/$defs/Enabled'}, 'propertyName': 'enabled'}.

Test evidence:

  • Before the fix, the new test failed on the mapping assertion.
  • After the fix, ./bt-test tests/test_json_schema.py: 533 passed, 3 skipped, 1 xfailed.
  • The other test files that use discriminators (test_forward_ref, test_validate_call, test_dataclasses, test_edge_cases, test_root_model): 671 passed, 3 skipped, 5 xfailed.

Blast radius: The change only affects discriminator keys that are bool, and it changes their JSON schema output. A search found no existing test or doc expecting 'True' / 'False' mapping keys. Keys that are strings, ints or other Enums are unchanged. Validation itself is untouched, since the change is only in JSON schema generation.

Requirements:

  1. bool discriminator mapping keys should be "true" / "false": done, covered by the new test.
  2. Output should match the report's expected mapping: done; the test asserts that exact dict.
  3. Handle this like the existing Enum normalisation in tagged_union_schema: done, placed right after the Enum step.

The diff was small enough that I reviewed it myself instead of using the reviewer subagent. It contains only the source change and the test, with no scratch files, and nothing is committed.