Backtestspydanticrun-20260929-204949#13631

Issue #13631 Merged fix PR #13632 Run 29 Sep 2026 · run-20260929-204949 pydantic/pydantic

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

Par

Our patch was judged on par with the merged fix.

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

The core fix is essentially identical in both patches: after the Enum-value normalization, both intercept `bool` keys and map them to JSON `'true'`/`'false'` instead of `str(True)`/`str(False)`, resolving the root cause described in the issue. The only code difference is Patch A's standalone `if isinstance(k, bool)` versus Patch B's `elif`; since `bool` and `Enum` are disjoint types (a bool can never also be an Enum), the two are functionally equivalent, and both comments accurately explain the reasoning. Both add a test that fails before and passes after, exercising the exact `Enabled`/`Disabled` scenario from the issue. Patch B's test asserts the entire schema (documenting `const` values etc.) which is more thorough but also more brittle to unrelated schema changes; Patch A's test is narrowly focused on the discriminator mapping, which is less brittle but less comprehensive. These are offsetting minor trade-offs. On correctness, scope, and craft no meaningful difference remains.

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

3m 48s10 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

21vs 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+21 −0
pydantic/json_schema.pyindex f6da6fc3..1e6420a7 100644@@ -1380,6 +1380,10 @@ class GenerateJsonSchema:         for k, v in schema['choices'].items():             if isinstance(k, Enum):                 k = k.value+            if isinstance(k, bool):+                # Booleans serialize to JSON `true`/`false`; match the serialized+                # payload value per the OpenAPI discriminator spec (rather than `str(True)`).+                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..6707a3f2 100644@@ -4416,6 +4416,23 @@ def test_discriminated_annotated_union_literal_enum():     }  +def test_discriminated_union_bool_discriminator_mapping():+    class Enabled(BaseModel):+        enabled: Literal[True]+        config: str++    class Disabled(BaseModel):+        enabled: Literal[False]++    class Model(BaseModel):+        setting: Union[Enabled, Disabled] = Field(discriminator='enabled')++    assert Model.model_json_schema()['properties']['setting']['discriminator'] == {+        'propertyName': 'enabled',+        'mapping': {'true': '#/$defs/Enabled', 'false': '#/$defs/Disabled'},+    }++ 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

The review confirms the fix is complete, correct, and minimal. Everything is done.

Summary

What was wrong

In GenerateJsonSchema.tagged_union_schema (pydantic/json_schema.py), discriminator mapping keys were stringified via str(k). Enum keys were first normalized with k.value, but bool keys (from a Literal[True]/Literal[False] discriminator) fell through to str(k), producing the Python-style keys "True"/"False". The OpenAPI discriminator spec requires mapping keys to match the serialized payload value, which for a boolean is JSON true/false — so tooling (openapi-generator, Redocly) failed to match either variant.

What I changed

Added a bool branch after the Enum reduction in tagged_union_schema, converting bool keys to 'true'/'false':

if isinstance(k, bool):
    # Booleans serialize to JSON `true`/`false`; match the serialized
    # payload value per the OpenAPI discriminator spec (rather than `str(True)`).
    k = 'true' if k else 'false'

isinstance(k, bool) is checked explicitly (not via its int superclass), so integer discriminators are unaffected. Placing it after the Enum reduction also handles an Enum whose .value is a bool.

Added regression test test_discriminated_union_bool_discriminator_mapping in tests/test_json_schema.py, using the exact scenario from the report and asserting the discriminator equals {'propertyName': 'enabled', 'mapping': {'true': '#/$defs/Enabled', 'false': '#/$defs/Disabled'}}.

Test evidence

  • Before the fix: the new test failed, showing actual mapping {'False': ..., 'True': ...}.
  • After the fix: the new test passes.
  • Gate over all discriminator tests in tests/test_json_schema.py and tests/types/unions/test_discriminated_union.py: 88 passed, 4 pre-existing xfailed — no regressions.
  • Reviewer confirmed the diff fully and minimally addresses the report, with no blast radius on int/str/enum discriminators and no stray files.

Requirements disposition

  1. bool discriminator mapping keys must be "true"/"false" instead of "True"/"False" — Implemented, with a regression test that fails before and passes after (evidence above).

No other explicit asks were in the report (the Enum-normalization note was context, and Enum behavior is verified unchanged by the passing test_discriminated_annotated_union_literal_enum). Changes are left uncommitted in the working tree.