Backtestspydanticrun-20261009-110034#13713

Issue #13713 Merged fix PR #13714 Run 9 Oct 2026 · run-20261009-110034 pydantic/pydantic

str_min_length and str_max_length are enforced by the validator but absent from the JSON schema

Better

Our patch was judged better than the merged fix.

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

Both patches add a config fallback in `str_schema`, so both fix the basic config-only rows in the issue's precedence table.

Patch A puts the fallback on every call to `str_schema`. Several callers produce strings that pydantic-core never checks against `str_min_length`/`str_max_length`:
- `decimal_schema` builds its string branch through `str_schema`.
- Format and to-string serializer output goes through it.
- `PlainSerializer(return_type=str)` output goes through it.

Under Patch A, a model with `str_max_length=3` and a `Decimal` field would emit `maxLength: 3` on the decimal's string form. That makes JSON Schema reject inputs pydantic accepts, which is the issue's defect class in reverse. Patch A also leaves config scoping alone. Plain dataclasses and TypedDicts without their own config push an empty config, and core-schema definitions (reused or recursive types) are generated outside the model's config. So in those cases the schema still omits constraints the validator enforces.

Patch B handles these cases explicitly:
- It suppresses the config lengths for decimals and serializer output.
- It keeps the parent config in effect for config-less dataclasses and TypedDicts, matching how validation behaves.
- It applies the root schema's config while generating definitions.

Patch B's tests are much stronger. The parametrized test covers every row of the issue's precedence table and cross-checks the schema against actual validation for lengths 0–12. Further tests cover TypeAdapter, list, dict keys and values, Optional, nested models with their own config, plain dataclasses and TypedDicts, definitions and recursive aliases, and the unvalidated-string cases. Patch A's single test covers only the config-only case and the field-override case.

Patch B is larger, and its config-stack changes carry some risk. However, that work is needed to make the schema faithful rather than adding new mismatches, and it is well commented. Patch B is the more correct and better-tested fix.

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

12m 46s

Wall-clock time in the container

Full test suite

No new failures

1,260 passed · 15 skipped · 1,275 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

232vs 29 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

str_min_length and str_max_length are enforced by the validator but do not appear in the JSON schema, so a JSON Schema validator silently accepts input the model rejects.

class Model(BaseModel):
    model_config = ConfigDict(str_min_length=3)
    s: str

Model.model_json_schema()['properties']['s']
#> {'title': 'S', 'type': 'string'}       <-- no minLength

Model(s='ab')                             #> ValidationError
jsonschema.validate({'s': 'ab'}, Model.model_json_schema())   #> accepted

The same holds for str_max_length. This is the same class of defect as #13704 — a constraint pydantic applies that a consumer of the schema cannot see — but it comes from a different place, so that fix will not cover it.

Why it happens

A field-level constraint lands on the core schema, where GenerateJsonSchema.str_schema finds it:

'schema': {'type': 'str', 'min_length': 3}

A config-level one does not. It stays in the model's config block and is applied by pydantic-core at validation time, leaving the string node bare:

{'type': 'model',
 'schema': {'type': 'model-fields',
            'fields': {'s': {'type': 'model-field', 'schema': {'type': 'str'}}}},   # <-- nothing here
 'config': {'str_min_length': 3, 'title': 'Model'}}

str_schema only reads the core schema node, so the constraint is invisible to it.

Precedence

Worth stating because it decides what the schema should say when both are present: a field-level length replaces the config one rather than narrowing it. Measured on main (952c239):

configfieldrejected lengthsschema today
str_max_length=5—8, 12{} — nothing emitted
—max_length=1012maxLength: 10 ✅
str_max_length=5max_length=1012maxLength: 10 ✅
str_max_length=10max_length=58, 12maxLength: 5 ✅
str_min_length=3—1{} — nothing emitted
str_min_length=3min_length=1noneminLength: 1 ✅

So only the config-only rows are wrong, and the fix is to fall back to the config value when the field left the key unset — the rows that already work keep working untouched.

str_strip_whitespace, str_to_lower and str_to_upper are not affected: they transform rather than constrain, and the result is still a string, so the schema stays accurate.

Example Code

import jsonschema
from pydantic import BaseModel, ConfigDict, ValidationError


class Model(BaseModel):
    model_config = ConfigDict(str_min_length=3, str_max_length=5)

    s: str


schema = Model.model_json_schema()
print(schema['properties']['s'])
#> {'title': 'S', 'type': 'string'}

for value in ('ab', 'abcdef'):
    try:
        Model(s=value)
    except ValidationError:
        print(f'pydantic rejects {value!r}')
    jsonschema.validate({'s': value}, schema)
    print(f'jsonschema accepts {value!r} -- constraint lost')

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: 952c239

I have a fix and a regression test ready and will open a PR without a closing reference, so it does not trip enforce-issue-assignment. Happy to have this assigned to me and the PR linked properly, or to leave it if you would rather take it in-house.

The two patches

Our patch+216 −16
pydantic/json_schema.pyindex 6fc639f1..80f3c33b 100644@@ -20,6 +20,7 @@ import re import warnings from collections import Counter, defaultdict from collections.abc import Callable, Hashable, Iterable, Sequence+from contextlib import AbstractContextManager from copy import deepcopy from enum import Enum from re import Pattern@@ -765,7 +766,9 @@ class GenerateJsonSchema:              return pattern -        json_schema = self.str_schema(core_schema.str_schema(pattern=get_decimal_pattern(schema)))+        # The `str_min_length`/`str_max_length` config values don't apply to decimals:+        with self._without_str_length_config():+            json_schema = self.str_schema(core_schema.str_schema(pattern=get_decimal_pattern(schema)))         if self.mode == 'validation':             multiple_of = schema.get('multiple_of')             le = schema.get('le')@@ -800,11 +803,24 @@ class GenerateJsonSchema:         """         json_schema = {'type': 'string'}         self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)+        # pydantic-core falls back to the `str_min_length`/`str_max_length` config values when the+        # schema doesn't set `min_length`/`max_length`, so the JSON Schema should reflect them as well:+        config = self._config.config_dict+        if 'min_length' not in schema and config.get('str_min_length'):+            json_schema['minLength'] = config['str_min_length']+        if 'max_length' not in schema and config.get('str_max_length') is not None:+            json_schema['maxLength'] = config['str_max_length']         if isinstance(json_schema.get('pattern'), Pattern):             # TODO: should we add regex flags to the pattern?             json_schema['pattern'] = json_schema.get('pattern').pattern  # type: ignore         return json_schema +    def _without_str_length_config(self) -> AbstractContextManager[None]:+        """Disable the `str_min_length`/`str_max_length` config values, for strings pydantic-core doesn't validate."""+        return self._config_wrapper_stack.push(+            {**self._config.config_dict, 'str_min_length': 0, 'str_max_length': None}+        )+     def bytes_schema(self, schema: core_schema.BytesSchema) -> JsonSchemaValue:         """Generates a JSON schema that matches a bytes value. @@ -1532,8 +1548,10 @@ 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)-        with self._config_wrapper_stack.push(config):+        cls_config = _get_typed_dict_config(cls)+        config = cls_config if cls_config is not None else {}+        # TypedDicts without config use the parent's config for validation, so keep it in effect:+        with self._config_wrapper_stack.push(cls_config):             json_schema = self._named_required_fields_schema(named_required_fields)          # There's some duplication between `extra_behavior` and@@ -1886,9 +1904,11 @@ class GenerateJsonSchema:         """          cls = schema['cls']-        config = cast('ConfigDict', getattr(cls, '__pydantic_config__', {}))+        cls_config = cast('ConfigDict | None', getattr(cls, '__pydantic_config__', None))+        config = cls_config if cls_config is not None else {} -        with self._config_wrapper_stack.push(config):+        # Plain dataclasses (without config) use the parent's config for validation, so keep it in effect:+        with self._config_wrapper_stack.push(cls_config):             json_schema = self.generate_inner(schema['schema']).copy()          self._update_class_schema(json_schema, cls, config)@@ -2204,13 +2224,16 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """-        for definition in schema['definitions']:-            try:-                self.generate_inner(definition)-            except PydanticInvalidForJsonSchema as e:  # noqa: PERF203-                core_ref: CoreRef = CoreRef(definition['ref'])  # type: ignore-                self._core_defs_invalid_for_json_schema[self.get_defs_ref((core_ref, self.mode))] = e-                continue+        # pydantic-core validates the definitions with the config of the schema they're attached to+        # (e.g. the model's config), so it should be in effect when generating them:+        with self._config_wrapper_stack.push(_get_root_config(schema['schema'])):+            for definition in schema['definitions']:+                try:+                    self.generate_inner(definition)+                except PydanticInvalidForJsonSchema as e:  # noqa: PERF203+                    core_ref: CoreRef = CoreRef(definition['ref'])  # type: ignore+                    self._core_defs_invalid_for_json_schema[self.get_defs_ref((core_ref, self.mode))] = e+                    continue         return self.generate_inner(schema['schema'])      def definition_ref_schema(self, schema: core_schema.DefinitionReferenceSchema) -> JsonSchemaValue:@@ -2242,10 +2265,13 @@ class GenerateJsonSchema:                 # PlainSerializerFunctionSerSchema or WrapSerializerFunctionSerSchema                 return_schema = schema.get('return_schema')                 if return_schema is not None:-                    return self.generate_inner(return_schema)+                    # Serializer output isn't validated, so the string length config values don't apply:+                    with self._without_str_length_config():+                        return self.generate_inner(return_schema)             case {'type': 'format' | 'to-string'}:                 # FormatSerSchema or ToStringSerSchema-                return self.str_schema(core_schema.str_schema())+                with self._without_str_length_config():+                    return self.str_schema(core_schema.str_schema())             case {'type': 'model'}:                 # ModelSerSchema                 return self.generate_inner(schema['schema'])@@ -2997,13 +3023,26 @@ else:             return hash(type(self))  -def _get_typed_dict_config(cls: type[Any] | None) -> ConfigDict:+def _get_typed_dict_config(cls: type[Any] | None) -> ConfigDict | None:     if cls is not None:         try:             return _decorators.get_attribute_from_bases(cls, '__pydantic_config__')         except AttributeError:             pass-    return {}+    return None+++def _get_root_config(schema: CoreSchema) -> ConfigDict | None:+    while schema['type'] in {'function-before', 'function-after', 'function-wrap'}:+        schema = schema['schema']  # type: ignore[typeddict-item]+    match schema:+        case {'type': 'model', 'cls': cls}:+            return cls.model_config+        case {'type': 'dataclass', 'cls': cls}:+            return getattr(cls, '__pydantic_config__', None)+        case {'type': 'typed-dict'}:+            return _get_typed_dict_config(schema.get('cls'))+    return None   def _get_ser_schema_for_default_value(schema: CoreSchema) -> core_schema.PlainSerializerFunctionSerSchema | None:tests/test_json_schema.pyindex 4c439df2..fea13c65 100644@@ -857,6 +857,167 @@ def test_date_types_ser_json_temporal(field_type, iso8601_format, ser_json_tempo     assert Model.model_json_schema(mode='validation')['properties']['a']['type'] == 'string'  +@pytest.mark.parametrize(+    'config,field,expected',+    [+        ({'str_max_length': 5}, {}, {'maxLength': 5}),+        ({'str_min_length': 3}, {}, {'minLength': 3}),+        ({'str_min_length': 3, 'str_max_length': 5}, {}, {'minLength': 3, 'maxLength': 5}),+        ({}, {'max_length': 10}, {'maxLength': 10}),+        ({'str_max_length': 5}, {'max_length': 10}, {'maxLength': 10}),+        ({'str_max_length': 10}, {'max_length': 5}, {'maxLength': 5}),+        ({'str_min_length': 3}, {'min_length': 1}, {'minLength': 1}),+        ({'str_min_length': 3}, {'max_length': 10}, {'minLength': 3, 'maxLength': 10}),+        ({'str_min_length': 0, 'str_max_length': None}, {}, {}),+    ],+)+def test_str_length_config_json_schema(config, field, expected):+    class Model(BaseModel):+        model_config = ConfigDict(**config)++        s: str = Field(**field)++    assert Model.model_json_schema()['properties']['s'] == {'title': 'S', 'type': 'string', **expected}+    # The JSON Schema should match what the validator actually enforces:+    for length in range(13):+        value = 'a' * length+        try:+            Model(s=value)+        except ValidationError:+            valid = False+        else:+            valid = True+        assert valid == (expected.get('minLength', 0) <= length <= expected.get('maxLength', math.inf))+++def test_str_length_config_json_schema_other_entrypoints():+    config = ConfigDict(str_min_length=3, str_max_length=5)+    constraints = {'minLength': 3, 'maxLength': 5}++    assert TypeAdapter(str, config=config).json_schema() == {'type': 'string', **constraints}+    assert TypeAdapter(list[str], config=config).json_schema() == {+        'type': 'array',+        'items': {'type': 'string', **constraints},+    }++    @pydantic.dataclasses.dataclass(config=config)+    class DC:+        s: str++    assert TypeAdapter(DC).json_schema()['properties']['s'] == {'title': 'S', 'type': 'string', **constraints}++    class TD(TypedDict):+        __pydantic_config__ = config  # type: ignore+        s: str++    assert TypeAdapter(TD).json_schema()['properties']['s'] == {'title': 'S', 'type': 'string', **constraints}++    class Model(BaseModel):+        model_config = config++        d: dict[str, str]+        o: str | None = None++    props = Model.model_json_schema()['properties']+    assert props['d']['additionalProperties'] == {'type': 'string', **constraints}+    assert props['d']['propertyNames'] == constraints+    assert props['o']['anyOf'][0] == {'type': 'string', **constraints}+    with pytest.raises(ValidationError):+        Model(d={'ab': 'abc'})+    with pytest.raises(ValidationError):+        Model(d={'abc': 'abcdef'})+++def test_str_length_config_json_schema_nested_config():+    """Nested models use their own config, plain dataclasses and TypedDicts the parent's one, as in validation."""++    class Inner(BaseModel):+        model_config = ConfigDict(str_max_length=10)++        s: str++    @dataclasses.dataclass+    class PlainDC:+        s: str++    class PlainTD(TypedDict):+        s: str++    class Outer(BaseModel):+        model_config = ConfigDict(str_max_length=3)++        inner: Inner+        dc: PlainDC+        td: PlainTD++    defs = Outer.model_json_schema()['$defs']+    assert defs['Inner']['properties']['s'] == {'title': 'S', 'type': 'string', 'maxLength': 10}+    assert defs['PlainDC']['properties']['s'] == {'title': 'S', 'type': 'string', 'maxLength': 3}+    assert defs['PlainTD']['properties']['s'] == {'title': 'S', 'type': 'string', 'maxLength': 3}++    Outer(inner={'s': 'a' * 10}, dc={'s': 'abc'}, td={'s': 'abc'})+    for bad in (+        {'inner': {'s': 'a' * 11}, 'dc': {'s': 'abc'}, 'td': {'s': 'abc'}},+        {'inner': {'s': 'a'}, 'dc': {'s': 'abcd'}, 'td': {'s': 'abc'}},+        {'inner': {'s': 'a'}, 'dc': {'s': 'abc'}, 'td': {'s': 'abcd'}},+    ):+        with pytest.raises(ValidationError):+            Outer(**bad)+++def test_str_length_config_json_schema_definitions():+    """Reused and recursive types end up in core schema definitions, which are validated with the model's config."""++    @dataclasses.dataclass+    class PlainDC:+        s: str++    class PlainTD(TypedDict):+        s: str++    Rec = TypeAliasType('Rec', 'list[Rec] | str')++    class Model(BaseModel):+        model_config = ConfigDict(str_max_length=3)++        dc1: PlainDC+        dc2: PlainDC+        td1: PlainTD+        td2: PlainTD+        rec: Rec++    defs = Model.model_json_schema()['$defs']+    assert defs['PlainDC']['properties']['s'] == {'title': 'S', 'type': 'string', 'maxLength': 3}+    assert defs['PlainTD']['properties']['s'] == {'title': 'S', 'type': 'string', 'maxLength': 3}+    assert defs['Rec']['anyOf'][1] == {'type': 'string', 'maxLength': 3}++    ok = {'dc1': {'s': 'abc'}, 'dc2': {'s': 'abc'}, 'td1': {'s': 'abc'}, 'td2': {'s': 'abc'}, 'rec': ['abc']}+    Model(**ok)+    for key, value in (('dc2', {'s': 'abcd'}), ('td2', {'s': 'abcd'}), ('rec', ['abcd']), ('rec', 'abcd')):+        with pytest.raises(ValidationError):+            Model(**{**ok, key: value})+++def test_str_length_config_json_schema_unvalidated_strings():+    """The config string lengths aren't applied to decimals and serializer output, so they aren't emitted."""++    class Model(BaseModel):+        model_config = ConfigDict(str_max_length=3)++        d: Decimal+        ser: Annotated[int, PlainSerializer(str, return_type=str)]++    m = Model(d='123456.789', ser=123456)+    assert m.model_dump(mode='json') == {'d': '123456.789', 'ser': '123456'}++    validation_props = Model.model_json_schema()['properties']+    assert 'maxLength' not in validation_props['d']['anyOf'][1]++    serialization_props = Model.model_json_schema(mode='serialization')['properties']+    assert 'maxLength' not in serialization_props['d']+    assert serialization_props['ser'] == {'title': 'Ser', 'type': 'string'}++ @pytest.mark.parametrize('ser_json_temporal', ['iso8601', 'seconds', 'milliseconds']) def test_date_types_ser_json_temporal_matches_serialized_output(ser_json_temporal):     class Model(BaseModel): 
Merged fix · PR #13714+28 −1
pydantic/json_schema.pyindex 6fc639f1e..7578fc1e5 100644@@ -798,8 +798,12 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """-        json_schema = {'type': 'string'}+        json_schema: JsonSchemaValue = {'type': 'string'}         self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)+        if 'minLength' not in json_schema and self._config.str_min_length:+            json_schema['minLength'] = self._config.str_min_length+        if 'maxLength' not in json_schema and self._config.str_max_length is not None:+            json_schema['maxLength'] = self._config.str_max_length         if isinstance(json_schema.get('pattern'), Pattern):             # TODO: should we add regex flags to the pattern?             json_schema['pattern'] = json_schema.get('pattern').pattern  # type: ignoretests/test_json_schema.pyindex 4c439df2f..e718d3389 100644@@ -2048,6 +2048,29 @@ def test_typeddict_default_bytes(ser_json_bytes: Literal['base64', 'utf8'], prop     }  +def test_str_length_config() -> None:+    class Model(BaseModel):+        model_config = ConfigDict(str_min_length=3, str_max_length=5)++        from_config: str+        from_field: Annotated[str, Field(min_length=1, max_length=10)]++    properties = Model.model_json_schema()['properties']+    assert properties['from_config'] == {+        'title': 'From Config',+        'type': 'string',+        'minLength': 3,+        'maxLength': 5,+    }+    # A field-level length replaces the config one rather than narrowing it:+    assert properties['from_field'] == {+        'title': 'From Field',+        'type': 'string',+        'minLength': 1,+        'maxLength': 10,+    }++ def test_model_subclass_metadata():     class A(BaseModel):         """A Model docstring"""