Backtestspydanticrun-20261027-165153#13716

Issue #13716 Merged fix PR #13717 Run 27 Oct 2026 · run-20261027-165153 pydantic/pydantic

validate_by_alias=False still produces a validation JSON schema keyed by the alias

Better

Our patch was judged better than the merged fix.

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

Both patches make the same core change in `_get_alias_name`: when `validate_by_alias` is False in the current config, the validation schema uses the field name. That fixes the model, pydantic dataclass, and configured TypedDict cases, and both patches add regression tests covering the main scenario, serialization being untouched, and scoping between nested models. The independent tests confirm both pass those.

Patch A goes further where the same defect still exists after Patch B's one-liner. Config-less TypedDicts and stdlib dataclasses nested in a `validate_by_alias=False` model inherit the parent's core config, so validation of them really uses the field name, yet with Patch B their schema still names the alias (the independent test `test_validate_by_alias_false_nested_configless_types_follow_model` fails on B, passes on A). Patch A handles this by reading `validate_by_alias` from the core schema's `config` when pushing the config wrapper for typed-dict and dataclass schemas. It also covers named-tuple field titles, arguments schemas (`validate_call`/`TypeAdapter` of a function), and threads `validate_by_alias` into the generated arguments core schemas so the JSON schema can read it per schema rather than from an ambient config. These are not unrelated churn; they are the same 'schema names a key the validator rejects' bug in other containers the generator handles, and each path has a dedicated test.

Risk assessment: Patch A's added surface (a context manager for arguments schemas, a helper to merge core-config `validate_by_alias`) is small, clearly named, and consistent with the existing config-wrapper-stack pattern. The `_generate_schema.py` change only passes a setting that core already reads from config, so validation behavior should be unchanged. Patch B is minimal and correct for the headline case but leaves a real, reachable instance of the issue unfixed. Patch A wins on correctness and test coverage without meaningful added risk.

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

13m 54s

Wall-clock time in the container

Full test suite

No new failures

1,598 passed · 41 skipped · 1,639 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

195vs 35 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

With validate_by_alias=False, the validation JSON schema still names the alias — which is the one key the model refuses.

class Model(BaseModel):
    model_config = ConfigDict(validate_by_alias=False, validate_by_name=True)
    my_field: str = Field(alias='myAlias')

Model.model_json_schema()
#> {'properties': {'myAlias': ...}, 'required': ['myAlias'], ...}

Model(my_field='x')                          # accepted
Model.model_validate({'myAlias': 'x'})       # ValidationError

So the schema describes the opposite of the model: it requires the rejected key and omits the accepted one. model_json_schema(by_alias=False) produces the right document, but a caller has to know the model's config to know to ask for it.

Why this looks like an oversight rather than a decision

_get_alias_name already picks the alias per mode, and it already returns the field name when no alias applies in that mode:

elif self.mode == 'validation':
    alias = field.get('validation_alias', name)
else:
    alias = field.get('serialization_alias', name)

Which is visible in behaviour today:

fieldvalidation schemaserialization schema
Field(serialization_alias='sAlias')my_field ✅sAlias ✅
Field(validation_alias='vAlias')vAlias ✅my_field ✅
Field(alias='myAlias') + validate_by_alias=FalsemyAlias ❌myAlias

The principle "use the alias only in the mode where it applies" is already implemented. validate_by_alias=False turns the validation alias off, and the generator simply does not consult it.

I have a fix and regression tests ready, and will open a PR without a closing reference so it does not trip enforce-issue-assignment.

A related asymmetry I did not touch, because it is your call

serialize_by_alias defaults to False, so with nothing but a plain Field(alias=...) the serialization schema already disagrees with the default dump:

class Model(BaseModel):
    my_field: str = Field(alias='myAlias')

Model(myAlias='x').model_dump_json()
#> {"my_field":"x"}

Model.model_json_schema(mode='serialization')['properties']
#> {'myAlias': ...}

By the argument above that is the same defect. But unlike validate_by_alias=False, which is an explicit opt-out affecting only the people who set it, serialize_by_alias=False is the default, so honouring it would change the serialization schema of every aliased model. That is a breaking change and a product decision, not a drive-by fix, so I have deliberately left it alone and am raising it here instead. Happy to follow up either way you decide.

Example Code

from pydantic import BaseModel, ConfigDict, Field, ValidationError


class Model(BaseModel):
    model_config = ConfigDict(validate_by_alias=False, validate_by_name=True)

    my_field: str = Field(alias='myAlias')


print(list(Model.model_json_schema()['properties']))
#> ['myAlias']

print(Model(my_field='x'))
#> my_field='x'

try:
    Model.model_validate({'myAlias': 'x'})
except ValidationError as exc:
    print(exc.errors()[0]['type'])
    #> missing

Python, Pydantic & OS Version

             pydantic version: 2.14.0b1
        pydantic-core version: 2.48.0
          pydantic-core build: profile=release pgo=false
               python version: 3.13.15 [MSC v.1944 64 bit (AMD64)]
                     platform: Windows-11-10.0.26200-SP0
             related packages: typing_extensions-4.16.0
                       commit: d4e72fa

The two patches

Our patch+189 −6
pydantic/_internal/_generate_schema.pyindex 3766cfee..6b94a8fc 100644@@ -2080,6 +2080,7 @@ class GenerateSchema:             var_args_schema=var_args_schema,             var_kwargs_mode=var_kwargs_mode,             var_kwargs_schema=var_kwargs_schema,+            validate_by_alias=core_config.get('validate_by_alias'),             validate_by_name=core_config.get('validate_by_name'),         ) @@ -2149,6 +2150,7 @@ class GenerateSchema:          return core_schema.arguments_v3_schema(             parameters_list,+            validate_by_alias=core_config.get('validate_by_alias'),             validate_by_name=core_config.get('validate_by_name'),         ) pydantic/json_schema.pyindex 7578fc1e..0289961f 100644@@ -19,7 +19,8 @@ import os import re import warnings from collections import Counter, defaultdict-from collections.abc import Callable, Hashable, Iterable, Sequence+from collections.abc import Callable, Hashable, Iterable, Iterator, Sequence+from contextlib import contextmanager from copy import deepcopy from enum import Enum from re import Pattern@@ -288,6 +289,9 @@ class GenerateJsonSchema:          self._mode: JsonSchemaMode = 'validation' +        # The `validate_by_alias` setting of the arguments schema currently being generated, if any+        self._arguments_validate_by_alias: bool | None = None+         # The following includes a mapping of a fully-unique defs ref choice to a list of preferred         # alternatives, which are generally simpler, such as only including the class name.         # At the end of schema generation, we use these to produce a JSON schema with more human-readable@@ -1536,7 +1540,7 @@ class GenerateJsonSchema:         if self.mode == 'serialization':             named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))         cls = schema.get('cls')-        config = _get_typed_dict_config(cls)+        config = _with_core_validate_by_alias(_get_typed_dict_config(cls), schema)         with self._config_wrapper_stack.push(config):             json_schema = self._named_required_fields_schema(named_required_fields) @@ -1606,7 +1610,7 @@ class GenerateJsonSchema:         if field['type'] == 'computed-field':             alias: Any = field.get('alias', name)         elif self.mode == 'validation':-            alias = field.get('validation_alias', name)+            alias = field.get('validation_alias', name) if self._config.validate_by_alias else name         else:             alias = field.get('serialization_alias', name)         if isinstance(alias, str):@@ -1892,7 +1896,7 @@ class GenerateJsonSchema:         cls = schema['cls']         config = cast('ConfigDict', getattr(cls, '__pydantic_config__', {})) -        with self._config_wrapper_stack.push(config):+        with self._config_wrapper_stack.push(_with_core_validate_by_alias(config, schema)):             json_schema = self.generate_inner(schema['schema']).copy()          self._update_class_schema(json_schema, cls, config)@@ -1924,7 +1928,7 @@ class GenerateJsonSchema:          for field in schema['fields']:             name = field['name']-            if self.by_alias:+            if self.by_alias and self._config.validate_by_alias:                 alias = field.get('validation_alias')                 if isinstance(alias, str):                     name = alias@@ -1957,6 +1961,10 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """+        with self._arguments_validate_by_alias_context(schema):+            return self._arguments_schema(schema)++    def _arguments_schema(self, schema: core_schema.ArgumentsSchema) -> JsonSchemaValue:         prefer_positional = schema.get('metadata', {}).get('pydantic_js_prefer_positional_arguments')          arguments = schema['arguments_schema']@@ -2075,7 +2083,10 @@ class GenerateJsonSchema:             The name of the argument.         """         name = argument['name']-        if self.by_alias:+        validate_by_alias = self._arguments_validate_by_alias+        if validate_by_alias is None:+            validate_by_alias = self._config.validate_by_alias+        if self.by_alias and validate_by_alias:             alias = argument.get('alias')             if isinstance(alias, str):                 name = alias@@ -2092,6 +2103,10 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """+        with self._arguments_validate_by_alias_context(schema):+            return self._arguments_v3_schema(schema)++    def _arguments_v3_schema(self, schema: core_schema.ArgumentsV3Schema) -> JsonSchemaValue:         arguments = schema['arguments_schema']         properties: dict[str, JsonSchemaValue] = {}         required: list[str] = []@@ -2122,6 +2137,18 @@ class GenerateJsonSchema:             json_schema['required'] = required         return json_schema +    @contextmanager+    def _arguments_validate_by_alias_context(+        self, schema: core_schema.ArgumentsSchema | core_schema.ArgumentsV3Schema+    ) -> Iterator[None]:+        """Record the `validate_by_alias` setting of an arguments schema while its JSON schema is generated."""+        previous = self._arguments_validate_by_alias+        self._arguments_validate_by_alias = schema.get('validate_by_alias')+        try:+            yield+        finally:+            self._arguments_validate_by_alias = previous+     def call_schema(self, schema: core_schema.CallSchema) -> JsonSchemaValue:         """Generates a JSON schema that matches a schema that defines a function call. @@ -3010,6 +3037,16 @@ def _get_typed_dict_config(cls: type[Any] | None) -> ConfigDict:     return {}  +def _with_core_validate_by_alias(+    config: ConfigDict, schema: core_schema.TypedDictSchema | core_schema.DataclassSchema+) -> ConfigDict:+    """Apply the `validate_by_alias` setting the core schema was built with, which may be inherited from a parent."""+    validate_by_alias = schema.get('config', {}).get('validate_by_alias')+    if validate_by_alias is None:+        return config+    return {**config, 'validate_by_alias': validate_by_alias}++ def _get_ser_schema_for_default_value(schema: CoreSchema) -> core_schema.PlainSerializerFunctionSerSchema | None:     """Get a `'function-plain'` serialization schema that can be used to serialize a default value. tests/test_json_schema.pyindex e718d338..c052aea4 100644@@ -140,6 +140,150 @@ def test_by_alias():     assert list(ApplePie.model_json_schema(by_alias=False)['properties'].keys()) == ['a', 'b']  +def test_validate_by_alias_false_uses_field_names_in_validation_schema() -> None:+    class Model(BaseModel):+        model_config = ConfigDict(validate_by_alias=False, validate_by_name=True)++        my_field: str = Field(alias='myAlias')+        other: int = Field(1, validation_alias='otherAlias')++    assert Model.model_json_schema() == {+        'type': 'object',+        'title': 'Model',+        'properties': {+            'my_field': {'type': 'string', 'title': 'My Field'},+            'other': {'type': 'integer', 'title': 'Other', 'default': 1},+        },+        'required': ['my_field'],+    }+    # The schema describes the keys the model actually accepts:+    assert Model.model_validate({'my_field': 'x', 'other': 2}).other == 2+    with pytest.raises(ValidationError):+        Model.model_validate({'myAlias': 'x'})++    # `validate_by_alias` has no effect on serialization, so the serialization alias is still used:+    assert list(Model.model_json_schema(mode='serialization')['properties']) == ['myAlias', 'other']+++def test_validate_by_alias_false_is_scoped_to_its_model() -> None:+    class Inner(BaseModel):+        inner_field: int = Field(alias='innerAlias')++    class Outer(BaseModel):+        model_config = ConfigDict(validate_by_alias=False)++        outer_field: Inner = Field(alias='outerAlias')++    schema = Outer.model_json_schema()+    assert list(schema['properties']) == ['outer_field']+    assert schema['required'] == ['outer_field']+    assert list(schema['$defs']['Inner']['properties']) == ['innerAlias']+    assert Outer.model_validate({'outer_field': {'innerAlias': 1}}).outer_field.inner_field == 1+++def test_validate_by_alias_false_typed_dict() -> None:+    @pydantic.with_config(ConfigDict(validate_by_alias=False))+    class TD(TypedDict):+        my_field: Annotated[int, Field(alias='myAlias')]++    ta = TypeAdapter(TD)+    assert ta.json_schema() == {+        'type': 'object',+        'title': 'TD',+        'properties': {'my_field': {'type': 'integer', 'title': 'My Field'}},+        'required': ['my_field'],+    }+    assert ta.validate_python({'my_field': 1}) == {'my_field': 1}+++def test_validate_by_alias_false_dataclass() -> None:+    @dataclass(config=ConfigDict(validate_by_alias=False))+    class DC:+        my_field: int = Field(alias='myAlias')++    ta = TypeAdapter(DC)+    assert ta.json_schema() == {+        'type': 'object',+        'title': 'DC',+        'properties': {'my_field': {'type': 'integer', 'title': 'My Field'}},+        'required': ['my_field'],+    }+    assert ta.validate_python({'my_field': 1}).my_field == 1+++def test_validate_by_alias_false_inherited_by_config_less_typed_dict_and_dataclass() -> None:+    class TD(TypedDict):+        my_field: Annotated[int, Field(alias='myAlias')]++    @dataclasses.dataclass+    class DC:+        my_field: int = Field(alias='myAlias')++    class Model(BaseModel):+        model_config = ConfigDict(validate_by_alias=False)++        td: TD+        dc: DC++    defs = Model.model_json_schema()['$defs']+    assert defs['TD']['properties'] == {'my_field': {'type': 'integer', 'title': 'My Field'}}+    assert defs['TD']['required'] == ['my_field']+    assert defs['DC']['properties'] == {'my_field': {'type': 'integer', 'title': 'My Field'}}+    assert defs['DC']['required'] == ['my_field']+    # The schema describes the keys the nested types actually accept:+    m = Model.model_validate({'td': {'my_field': 1}, 'dc': {'my_field': 2}})+    assert m.td == {'my_field': 1}+    assert m.dc.my_field == 2+++def test_validate_by_alias_false_named_tuple_field_title() -> None:+    class Point(NamedTuple):+        my_field: Annotated[int, Field(validation_alias='myAlias')]++    class Model(BaseModel):+        model_config = ConfigDict(validate_by_alias=False)++        point: Point++    assert Model.model_json_schema()['$defs']['Point']['prefixItems'] == [{'type': 'integer', 'title': 'My Field'}]+++def test_validate_by_alias_false_function_arguments() -> None:+    def func(my_arg: Annotated[int, Field(alias='myAlias')]) -> int:+        return my_arg++    config = ConfigDict(validate_by_alias=False)++    assert TypeAdapter(func, config=config).json_schema() == {+        'type': 'object',+        'properties': {'my_arg': {'type': 'integer', 'title': 'My Arg'}},+        'required': ['my_arg'],+        'additionalProperties': False,+    }++    validated_func = pydantic.validate_call(config=config)(func)+    assert validated_func(my_arg=1) == 1+    with pytest.raises(ValidationError):+        validated_func(myAlias=1)+++@pytest.mark.parametrize('validate_by_alias,expected_name', [(True, 'b'), (False, 'a'), (None, 'b')])+def test_json_schema_arguments_validate_by_alias(validate_by_alias: bool | None, expected_name: str) -> None:+    v1_schema = core_schema.arguments_schema(+        [core_schema.arguments_parameter(name='a', schema=core_schema.int_schema(), alias='b')],+        validate_by_alias=validate_by_alias,+        validate_by_name=True,+    )+    v3_schema = core_schema.arguments_v3_schema(+        [core_schema.arguments_v3_parameter(name='a', schema=core_schema.int_schema(), alias='b')],+        validate_by_alias=validate_by_alias,+        validate_by_name=True,+    )++    for schema in (v1_schema, v3_schema):+        assert list(GenerateJsonSchema().generate(schema)['properties']) == [expected_name]++ def test_ref_template():     class KeyLimePie(BaseModel):         x: str = None 
Merged fix · PR #13717+34 −1
pydantic/json_schema.pyindex 7578fc1e5..9e003e89c 100644@@ -1606,7 +1606,7 @@ class GenerateJsonSchema:         if field['type'] == 'computed-field':             alias: Any = field.get('alias', name)         elif self.mode == 'validation':-            alias = field.get('validation_alias', name)+            alias = name if not self._config.validate_by_alias else field.get('validation_alias', name)         else:             alias = field.get('serialization_alias', name)         if isinstance(alias, str):tests/test_json_schema.pyindex e718d3389..5f3d17166 100644@@ -140,6 +140,39 @@ def test_by_alias():     assert list(ApplePie.model_json_schema(by_alias=False)['properties'].keys()) == ['a', 'b']  +def test_validate_by_alias_false_uses_the_field_name():+    class Model(BaseModel):+        model_config = ConfigDict(validate_by_alias=False, validate_by_name=True)+        my_field: str = Field(alias='myAlias')++    assert list(Model.model_json_schema()['properties']) == ['my_field']+    # Serialization is governed by `serialize_by_alias`, which this leaves alone:+    assert list(Model.model_json_schema(mode='serialization')['properties']) == ['myAlias']++    @pydantic.dataclasses.dataclass(config=ConfigDict(validate_by_alias=False, validate_by_name=True))+    class Dataclass:+        my_field: str = Field(alias='myAlias')++    adapter = TypeAdapter(Dataclass)+    assert list(adapter.json_schema()['properties']) == ['my_field']+++def test_validate_by_alias_false_is_scoped_to_its_own_model():+    class Inner(BaseModel):+        model_config = ConfigDict(validate_by_alias=False, validate_by_name=True)+        inner_field: str = Field(alias='innerAlias')++    class Outer(BaseModel):+        outer_field: str = Field(alias='outerAlias')+        inner: Inner++    json_schema = Outer.model_json_schema()+    assert list(json_schema['properties']) == ['outerAlias', 'inner']+    assert list(json_schema['$defs']['Inner']['properties']) == ['inner_field']++    assert Outer.model_validate({'outerAlias': 'x', 'inner': {'inner_field': 'y'}}).outer_field == 'x'++ def test_ref_template():     class KeyLimePie(BaseModel):         x: str = None