Backtestspydanticrun-20261002-175417#13802
Three error-reference examples no longer raise the error they document, and the docs test suite cannot detect it
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches make the same three doc fixes. Each replaces `False` with `'not a complex number'` for `complex_type`. Each deletes the stale `string_sub_type` section. Each swaps `ImportString` for a `Callable`, which has no JSON schema, so the `invalid-for-json-schema` example raises again. Bare `Callable` versus `Callable[..., object]` makes no practical difference. The patches differ in what else they do. Patch B addresses the root cause the issue highlights: the docs suite cannot detect an example whose `except` branch never runs. B adds `test_error_examples_enter_except`. This test uses an AST transformer to record a sentinel at the start of every `except` block in the error-docs examples, then fails if any block is never entered. It honours skip, xfail and `requires` settings. It would have failed on all three broken examples before the fix and passes after, so it is a real regression test for the blind spot. B also keeps `test_validation_error_codes` consistent by excluding `string_sub_type` with a clear comment, rather than changing pydantic-core. Patch A adds no test for the blind spot, so a future change like the complex-validation one could again silently make a docs section untrue. A also removes the `StringSubType` variant from the Rust error enum, the public `ErrorType` literal and the core error tests. The issue explicitly called this a maintainer decision, and the change is breaking for anyone constructing or matching that error type. A also makes an unrelated edit to `docs/concepts/experimental.md`, changing the partial-JSON example input from a truncated string `"12` to a closed `"12"`. This alters what that example demonstrates and its expected output, which is risky churn outside the issue's scope. On correctness, both fix the three examples. On tests, B adds a meaningful detector and A adds nothing. On scope, A adds breaking-API and unrelated-docs risk. B is the better 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
8m 53s
Wall-clock time in the container
Full test suite
No new failures
12,878 passed · 546 skipped · 13,424 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
89vs 39 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
Three examples on the error-reference pages no longer raise the error they document, and the documentation test suite cannot detect it.
Every example on those pages has the same shape: do something that should fail, catch it, then print or assert the error code. The only assertion lives inside the except branch. When the operation stops failing, that branch never runs, so nothing is printed and no assert is evaluated. run_print_check compares printed output against the #> comments, and an example whose print never ran produces no output to disagree with, so the example exits 0 and CI stays green while the page documents behaviour that no longer exists.
I checked this exhaustively rather than by sampling. I injected a sentinel as the first statement of every except block on both error pages and ran each example. Of the 152 examples containing a try/except at v2.13.5, all 152 run, and exactly 3 never enter their except branch. On main the count is 3 of 157. None of the three is marked test="skip", so all three are executed by CI today.
1. complex_type, docs/errors/validation_errors.md
Model(num=False) now validates successfully to 0j, so the #> 'complex_type' line never prints. This changed in 2.13.0b1 with #12498, which made complex validation call the complex() constructor unconditionally in Python mode, and complex(False) is 0j.
2. string_sub_type, docs/errors/validation_errors.md
The section says a strict str field rejects an instance of a str subclass. It does not: the example returns a plain str with the value 'foo', and #> 'string_sub_type' never prints. pydantic_core 2.49.0 still declares the error ("Input should be a string, not an instance of a subclass of str"), but I could not find any str schema that raises it. Building core_schema.str_schema() directly with strict=True, without strict, and with strict=True plus a pattern all accept a str subclass and return a plain str.
This looks intentional rather than accidental. #6261 reported exactly this behaviour as a bug in June 2023, was labelled bug V2, and was closed with the conversation moved to pydantic-core#786. So the check appears to have been removed on purpose and this documentation section was left behind describing it.
3. invalid-for-json-schema, docs/errors/usage_errors.md
ImportString has had a JSON schema since 2.8.0 via #9344, so Model.model_json_schema() succeeds and returns a plain string schema. The assert exc_info.code == 'invalid-for-json-schema' inside the except block has not executed since that release.
Output of the example code below
Identical on 2.13.5 and on main at 2.14.0b2:
1. no exception; num = 0j
2. no exception; accepted 'foo'
3. no exception; {'properties': {'a': {'title': 'A', 'type': 'string'}}, 'required': ['a'], 'title': 'ImportStringModel', 'type': 'object'}
Suggested fixes
complex_typeis a one-word fix.Model(num='not a complex number')still raisescomplex_type, and so do[],{}and a bareobject(). ReplacingFalsewith any of those restores the example.string_sub_typeneeds a decision rather than a fix, which is the main reason I am opening an issue instead of sending a patch. Given the trail through #6261, the section probably wants deleting rather than repairing, and possibly the error variant too, but that is your call.invalid-for-json-schemaneeds a type that genuinely has no JSON schema, in place ofImportString.
Separately, the blind spot itself is fixable. If an example on these pages had to demonstrate that the error occurred, for instance by printing inside the except and also failing loudly when nothing was raised, then a future change like #12498 would turn the docs red instead of silently making a section untrue. I am happy to send a PR for any or all of this, including that check as a test, if you tell me which direction you prefer.
I used AI assistance to run this audit, in line with your AI policy. I have reproduced and understood each of the three cases myself and can explain any of them.
Example Code
from enum import Enum
from pydantic import (
BaseModel,
Field,
ImportString,
PydanticUserError,
ValidationError,
)
# 1. validation_errors.md, `complex_type`: documented to print 'complex_type'
class ComplexModel(BaseModel):
num: complex
try:
ComplexModel(num=False)
print('1. no exception; num =', ComplexModel(num=False).num)
except ValidationError as exc:
print('1.', repr(exc.errors()[0]['type']))
# 2. validation_errors.md, `string_sub_type`: documented to print 'string_sub_type'
class MyEnum(str, Enum):
foo = 'foo'
class StrictStrModel(BaseModel):
x: str = Field(strict=True)
try:
print('2. no exception; accepted', repr(StrictStrModel(x=MyEnum.foo).x))
except ValidationError as exc:
print('2.', repr(exc.errors()[0]['type']))
# 3. usage_errors.md, `invalid-for-json-schema`: the assert is never reached
class ImportStringModel(BaseModel):
a: ImportString
try:
print('3. no exception;', ImportStringModel.model_json_schema())
except PydanticUserError as exc:
print('3.', exc.code)
Python, Pydantic & OS Version
pydantic version: 2.13.5
pydantic-core version: 2.46.5
python version: 3.12.10 (CPython)
platform: Windows 11
also reproduced against main at pydantic 2.14.0b2 / pydantic-core 2.49.0The two patches
docs/errors/usage_errors.mdindex 7e28e9f8..48403726 100644@@ -620,11 +620,13 @@ type C = B This error is raised when Pydantic fails to generate a JSON schema for some `CoreSchema`. ```python-from pydantic import BaseModel, ImportString, PydanticUserError+from collections.abc import Callable++from pydantic import BaseModel, PydanticUserError class Model(BaseModel):- a: ImportString+ a: Callable try:docs/errors/validation_errors.mdindex 71d3a929..95e240e7 100644@@ -233,7 +233,7 @@ class Model(BaseModel): try:- Model(num=False)+ Model(num='not a complex number') except ValidationError as exc: print(repr(exc.errors()[0]['type'])) #> 'complex_type'@@ -1845,31 +1845,6 @@ except ValidationError as exc: #> 'string_pattern_mismatch' ``` -## `string_sub_type`--This error is raised when the value is an instance of a strict subtype of `str` when the field is strict:--```python-from enum import Enum--from pydantic import BaseModel, Field, ValidationError---class MyEnum(str, Enum):- foo = 'foo'---class Model(BaseModel):- x: str = Field(strict=True)---try:- Model(x=MyEnum.foo)-except ValidationError as exc:- print(repr(exc.errors()[0]['type']))- #> 'string_sub_type'-```- ## `string_too_long` This error is raised when the input value is a string whose length is greater than the field's `max_length` constraint:tests/test_docs.pyindex 7c185657..e2a5029c 100644@@ -1,5 +1,7 @@ from __future__ import annotations as _annotations +import ast+import dataclasses import os import platform import re@@ -249,6 +251,59 @@ def test_docs_devtools_example(example: CodeExample, eval_example: EvalExample, assert output_html == output_file.read_text() +class _RecordExceptHandlers(ast.NodeTransformer):+ """Insert a call recording the line number at the start of every `except` block."""++ def __init__(self) -> None:+ self.handler_lines: set[int] = set()++ def visit_ExceptHandler(self, node: ast.ExceptHandler) -> ast.ExceptHandler:+ self.generic_visit(node)+ self.handler_lines.add(node.lineno)+ record = ast.parse(f'__docs_except_hit__({node.lineno})').body[0]+ node.body.insert(0, ast.copy_location(record, node))+ return node+++@pytest.mark.thread_unsafe+@pytest.mark.skipif(bool(skip_reason), reason=skip_reason or 'not skipping')+@pytest.mark.parametrize(+ 'example', list(find_examples(str(DOCS_ROOT / 'errors'), skip=sys.platform == 'win32')), ids=str+)+def test_error_examples_enter_except(example: CodeExample, eval_example: EvalExample, mocker):+ """Every `except` block in the error docs examples must run, i.e. the documented error must actually be raised.++ The assertions in those examples live inside the `except` block, so if the error stops being raised,+ `test_docs_examples` still passes as nothing gets printed or asserted.+ """+ prefix_settings = example.prefix_settings()+ if prefix_settings.get('test', '').startswith(('skip', 'xfail')):+ pytest.skip('running code skipped')+ requires_settings = prefix_settings.get('requires')+ if requires_settings:+ major, minor = map(int, requires_settings.split('.'))+ if sys.version_info < (major, minor):+ pytest.skip(f'requires python {requires_settings}')++ transformer = _RecordExceptHandlers()+ tree = ast.fix_missing_locations(transformer.visit(ast.parse(example.source)))+ if not transformer.handler_lines:+ pytest.skip('no except block')++ mocker.patch('random.randint', return_value=3)+ entered: set[int] = set()+ instrumented = dataclasses.replace(example, source=ast.unparse(tree))+ with time_machine.travel(datetime(2032, 1, 2, 3, 4, 5, 6).astimezone(), tick=False):+ eval_example.run(+ instrumented,+ module_globals={'__docs_except_hit__': entered.add},+ rewrite_assertions=prefix_settings.get('rewrite_assert', 'true') == 'true',+ )++ not_entered = sorted(example.start_line + line for line in transformer.handler_lines - entered)+ assert not not_entered, f'`except` block(s) never entered at {example.path.name} line(s) {not_entered}'++ def test_error_codes(): error_text = (DOCS_ROOT / 'errors/usage_errors.md').read_text() @@ -265,6 +320,7 @@ def test_validation_error_codes(): expected_validation_error_codes = set(core_schema.ErrorType.__args__) # Remove codes that are not currently accessible from pydantic: expected_validation_error_codes.remove('timezone_offset') # not currently exposed for configuration in pydantic+ expected_validation_error_codes.remove('string_sub_type') # no longer raised by any validator in pydantic-core test_failures = []
docs/concepts/experimental.mdindex cc349f3a0..ab1665260 100644@@ -342,7 +342,7 @@ class MyModel(BaseModel): ta = TypeAdapter(MyModel) try: v = ta.validate_json(- '{"a": 1, "b": ["12345", "12', experimental_allow_partial=True+ '{"a": 1, "b": ["12345", "12"', experimental_allow_partial=True ) except ValidationError as e: print(e)docs/errors/usage_errors.mdindex 7e28e9f82..3e6a67412 100644@@ -620,11 +620,13 @@ type C = B This error is raised when Pydantic fails to generate a JSON schema for some `CoreSchema`. ```python-from pydantic import BaseModel, ImportString, PydanticUserError+from collections.abc import Callable++from pydantic import BaseModel, PydanticUserError class Model(BaseModel):- a: ImportString+ a: Callable[..., object] try:docs/errors/validation_errors.mdindex 71d3a9292..95e240e70 100644@@ -233,7 +233,7 @@ class Model(BaseModel): try:- Model(num=False)+ Model(num='not a complex number') except ValidationError as exc: print(repr(exc.errors()[0]['type'])) #> 'complex_type'@@ -1845,31 +1845,6 @@ except ValidationError as exc: #> 'string_pattern_mismatch' ``` -## `string_sub_type`--This error is raised when the value is an instance of a strict subtype of `str` when the field is strict:--```python-from enum import Enum--from pydantic import BaseModel, Field, ValidationError---class MyEnum(str, Enum):- foo = 'foo'---class Model(BaseModel):- x: str = Field(strict=True)---try:- Model(x=MyEnum.foo)-except ValidationError as exc:- print(repr(exc.errors()[0]['type']))- #> 'string_sub_type'-```- ## `string_too_long` This error is raised when the input value is a string whose length is greater than the field's `max_length` constraint:pydantic-core/python/pydantic_core/core_schema.pyindex b6fce060b..fda0e35ee 100644@@ -4776,7 +4776,6 @@ ErrorType: TypeAlias = Literal[ 'iterable_type', 'iteration_error', 'string_type',- 'string_sub_type', 'string_unicode', 'string_too_short', 'string_too_long',pydantic-core/src/errors/types.rsindex 4bdb92135..f49f48509 100644@@ -247,7 +247,6 @@ error_types! { // --------------------- // string errors StringType {},- StringSubType {}, StringUnicode {}, StringTooShort { min_length: {ctx_type: usize, ctx_fn: field_from_context},@@ -533,7 +532,6 @@ impl ErrorType { Self::IterableType { .. } => "Input should be iterable", Self::IterationError { .. } => "Error iterating over object, error: {error}", Self::StringType { .. } => "Input should be a valid string",- Self::StringSubType { .. } => "Input should be a string, not an instance of a subclass of str", Self::StringUnicode { .. } => { "Input should be a valid string, unable to parse raw data as a unicode string" }pydantic-core/tests/test_errors.pyindex 66f15d81a..b024e618b 100644@@ -303,7 +303,6 @@ all_errors = [ {'field_type': 'Foobar', 'max_length': 42, 'actual_length': 50}, ), ('string_type', 'Input should be a valid string', None),- ('string_sub_type', 'Input should be a string, not an instance of a subclass of str', None), ('string_unicode', 'Input should be a valid string, unable to parse raw data as a unicode string', None), ('string_pattern_mismatch', "String should match pattern 'foo'", {'pattern': 'foo'}), ('string_not_ascii', 'String should contain only ASCII characters', None),