Backtestspydanticrun-20260923-170312#13631
JSON schema discriminator mapping uses Python-style True/False keys for bool discriminators
The merged fix was judged better than our patch.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches make the identical root-cause fix — normalizing bool discriminator keys to JSON 'true'/'false' before str(k) — and both add a test that fails before and passes after, so correctness on the reported scenario (plain Literal[True]/[False]) is equal. The differences are marginal. Patch B uses a separate `if` (rather than A's `elif`), which additionally normalizes a bool that came out of an Enum's `.value`; that is a genuine but degenerate, untested edge (a bool-valued Enum used as a Literal discriminator) that lies outside the reported issue and slightly alters prior behavior. Patch A uses a clean if/elif chain and, more importantly, adds an explanatory comment stating *why* the JSON representation is used — matching the repo's existing convention of commenting the adjacent str(k) choice — which aids maintainability. Patch A's test also asserts the entire generated schema (including that the boolean fields render as {'const': True/False, 'type': 'boolean'}), giving broader regression coverage than Patch B's discriminator-only assertion. Since correctness on the actual issue is a wash, Patch A edges ahead on test thoroughness and craft (documenting intent). It is a narrow win, not a tie: B's extra edge-handling is speculative and unverified, while A's advantages are concrete.
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 20s7 turns
Wall-clock time in the container
Full test suite
No new failures
6,547 passed · 367 skipped · 6,914 total
Contamination audit
Unknown
See the audit notes for this run
Patch size
21vs 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..fcdd63f3 100644@@ -1380,6 +1380,8 @@ class GenerateJsonSchema: for k, v in schema['choices'].items(): if isinstance(k, Enum): k = k.value+ if isinstance(k, bool):+ 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..d6a8ba04 100644@@ -3917,6 +3917,25 @@ def test_discriminated_union(): } +def test_discriminated_union_bool_discriminator():+ class Enabled(BaseModel):+ enabled: Literal[True]+ config: str++ class Disabled(BaseModel):+ enabled: Literal[False]++ class Model(BaseModel):+ setting: Enabled | Disabled = Field(discriminator='enabled')++ # Per the OpenAPI discriminator spec, boolean values serialize to JSON `true`/`false`,+ # so the mapping keys must be `'true'`/`'false'`, not Python reprs `'True'`/`'False'`.+ assert Model.model_json_schema()['properties']['setting']['discriminator'] == {+ 'propertyName': 'enabled',+ 'mapping': {'true': '#/$defs/Enabled', 'false': '#/$defs/Disabled'},+ }++ def test_discriminated_annotated_union(): class Cat(BaseModel): pet_type: Literal['cat']
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 fix is complete and verified. Here is my final report.
What was wrong
In GenerateJsonSchema.tagged_union_schema (pydantic/json_schema.py), discriminator mapping keys are stringified via str(k). Enum keys were normalized to k.value first, but bool keys fell straight through to str(k), producing the Python reprs "True"/"False". Per the OpenAPI discriminator spec, mapping keys must match the serialized JSON payload value, and a JSON boolean serializes to true/false — so tooling (openapi-generator, Redocly, etc.) could not resolve the mapping.
What I changed
pydantic/json_schema.py — added a bool-normalization branch after the existing Enum branch:
if isinstance(k, Enum):
k = k.value
if isinstance(k, bool):
k = 'true' if k else 'false'
Placed as a separate if after the Enum branch so an Enum whose .value is a bool is also normalized. isinstance(k, bool) does not catch plain ints (Literal[1] still renders '1'), so only booleans are affected.
tests/test_json_schema.py — added test_discriminated_union_bool_discriminator, asserting:
Model.model_json_schema()['properties']['setting']['discriminator'] == {
'propertyName': 'enabled',
'mapping': {'true': '#/$defs/Enabled', 'false': '#/$defs/Disabled'},
}
Test evidence
- The test-writer confirmed the new test fails before the fix (producing
'True'/'False'keys, exactly as reported) and passes after. - Gate run:
./bt-test tests/test_json_schema.py -k discriminat→ 7 passed (6 existing discriminator tests still pass + the new regression test). No regressions. - Final diff touches only the two expected files (2 + 19 insertions); no scratch/temp files, no existing tests weakened.
- Reviewer verdict: PASS.
Requirements checklist
- Bool discriminator mapping keys must be
"true"/"false"instead of"True"/"False"— ✅ Implemented (json_schema.py) with a passing regression test asserting the exact expected mapping from the report. - Enum keys already normalized via
k.valuemust remain correct — ✅ Preserved; bool branch placed after the Enum branch so a bool-valued Enum is also handled, and existing Enum discriminator tests still pass.
All changes are left uncommitted in the working tree.