Backtestspydanticrun-20261022-024030#13857
_FieldNameStack/_ModelTypeStack lose their pop() on exception, corrupting later unrelated schema builds
The judges split evenly between our patch and the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
The production fix in `_generate_schema.py` is byte-for-byte identical in both patches: wrapping both `push()` yields in try/finally, which resolves the root cause. The difference is in tests and scope. Patch A adds two behaviour-level regression tests that reproduce the issue through real schema-generation paths: a nested `handler.generate_schema` failure caught in `__get_pydantic_core_schema__`, then asserting `handler.field_name` is None and that a `Self` field resolves to the enclosing model rather than the stale TypedDict. Both fail on base and pass after the fix, and they match exactly the user-visible corruption the independent tests also probed. Patch B's test in test_internal.py is also valid (it drives `GenerateSchema` directly and checks both stacks plus a later unrelated push, mirroring the issue's reproduction), but it asserts on internal attributes rather than observable behaviour. Patch B additionally changes `generic_recursion_self_type` in `_generics.py` and adds a test for it; that is a reasonable adjacent hardening but outside the issue's ask, earning no credit and mildly widening the review surface. With correctness equal, A's tighter scope and tests that verify the issue's consequences through public APIs give it a narrow edge.
Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.
Solve
5m 21s
Wall-clock time in the container
Full test suite
No new failures
848 passed · 38 skipped · 886 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
65vs 62 merged
Changed lines, ours vs merged
The issue
View on GitHubDescription
_FieldNameStack.push() and _ModelTypeStack.push() in pydantic/_internal/_generate_schema.py (around lines 2910/2929) push onto their internal list, yield, then pop:
@contextmanager
def push(self, field_name: str) -> Iterator[None]:
self._stack.append(field_name)
yield
self._stack.pop()
If the code inside the with self.field_name_stack.push(...): block raises (schema generation is deeply recursive and can legitimately raise, e.g. PydanticUserError for a circular reference a few lines above this class in the same file), the yield's continuation - the .pop() - never runs. The stale entry stays on the stack forever, and corrupts every later, otherwise-unrelated push()/get() on that same GenerateSchema instance, not just the one that failed.
Reproduction
Isolated (no pydantic-core needed to demonstrate - this is pure Python control flow, verified against the actual class body copied verbatim):
from contextlib import contextmanager
class _FieldNameStack:
__slots__ = ('_stack',)
def __init__(self):
self._stack = []
@contextmanager
def push(self, field_name):
self._stack.append(field_name)
yield
self._stack.pop()
def get(self):
return self._stack[-1] if self._stack else None
stack = _FieldNameStack()
try:
with stack.push('some_field'):
raise ValueError('boom') # simulates any exception during schema generation
except ValueError:
pass
print(stack.get()) # 'some_field' - already wrong, nothing is being processed
# The real damage: this leaks into a completely unrelated, later, successful push.
with stack.push('other_field'):
pass
print(stack.get()) # 'some_field' again - should be None, 'other_field' was popped
# correctly but the stale entry underneath it was never cleared
Output:
some_field
some_field
Both lines should print None.
Fix
Wrap the yield in try/finally so the pop runs unconditionally, the same guarantee a class-based context manager's __exit__ gets for free:
@contextmanager
def push(self, field_name: str) -> Iterator[None]:
self._stack.append(field_name)
try:
yield
finally:
self._stack.pop()
Same fix applies identically to _ModelTypeStack.push() a few lines below - same shape, same bug.
I have a fix + regression test ready (asserts .get() returns None after a push whose body raised) and I'm happy to open a PR, per the note in the PR template about discussing non-trivial changes here first.
The two patches
pydantic/_internal/_generate_schema.pyindex b458013a..a446559b 100644@@ -2910,8 +2910,10 @@ class _FieldNameStack: @contextmanager def push(self, field_name: str) -> Iterator[None]: self._stack.append(field_name)- yield- self._stack.pop()+ try:+ yield+ finally:+ self._stack.pop() def get(self) -> str | None: if self._stack:@@ -2929,8 +2931,10 @@ class _ModelTypeStack: @contextmanager def push(self, type_obj: type) -> Iterator[None]: self._stack.append(type_obj)- yield- self._stack.pop()+ try:+ yield+ finally:+ self._stack.pop() def get(self) -> type | None: if self._stack:pydantic/_internal/_generics.pyindex 15c4c56d..45f9aeff 100644@@ -432,8 +432,10 @@ def generic_recursion_self_type( yield self_type else: previously_seen_type_refs.add(type_ref)- yield- previously_seen_type_refs.remove(type_ref)+ try:+ yield+ finally:+ previously_seen_type_refs.remove(type_ref) finally: if token: _generic_recursion_cache.reset(token)tests/test_generics.pyindex f8c396cf..e0e6d964 100644@@ -3286,3 +3286,24 @@ def test_generics_parameterization_not_hashable() -> None: Mint = Model[Annotated[int, NoHash()]] assert Mint(f='1').f == 1+++def test_generic_recursion_self_type_cleans_up_when_body_raises() -> None:+ T = TypeVar('T')++ class Inner(BaseModel, Generic[T]):+ pass++ class Outer(BaseModel, Generic[T]):+ pass++ with generic_recursion_self_type(Outer, (int,)):+ with pytest.raises(ValueError, match='boom'):+ with generic_recursion_self_type(Inner, (int,)) as self_type:+ assert self_type is None+ raise ValueError('boom')++ # The failed nested build must not leave a stale entry that would make an+ # unrelated later build of the same type look like a recursive reference:+ with generic_recursion_self_type(Inner, (int,)) as self_type:+ assert self_type is Nonetests/test_internal.pyindex 3bfc123f..73b46190 100644@@ -356,3 +356,29 @@ def _wrap_identity(v: Any, handler: Any) -> Any: ) def test_as_ser_schema(schema: CoreSchema, expected: cs.SerSchema) -> None: assert as_ser_schema(schema) == expected+++def test_generate_schema_stacks_are_popped_when_schema_generation_raises() -> None:+ class BadType:+ @classmethod+ def __get_pydantic_core_schema__(cls, source: Any, handler: Any) -> CoreSchema:+ raise ValueError('boom')++ class Model(BaseModel, defer_build=True):+ x: BadType++ gen_schema = GenerateSchema(ConfigWrapper(None))+ with pytest.raises(ValueError, match='boom'):+ gen_schema.generate_schema(Model)++ assert gen_schema.field_name_stack.get() is None+ assert gen_schema.model_type_stack.get() is None++ # A later, unrelated push must not expose the stale entries once popped:+ with gen_schema.field_name_stack.push('other_field'):+ assert gen_schema.field_name_stack.get() == 'other_field'+ assert gen_schema.field_name_stack.get() is None++ with gen_schema.model_type_stack.push(int):+ assert gen_schema.model_type_stack.get() is int+ assert gen_schema.model_type_stack.get() is None
pydantic/_internal/_generate_schema.pyindex b458013ae..a446559b8 100644@@ -2910,8 +2910,10 @@ class _FieldNameStack: @contextmanager def push(self, field_name: str) -> Iterator[None]: self._stack.append(field_name)- yield- self._stack.pop()+ try:+ yield+ finally:+ self._stack.pop() def get(self) -> str | None: if self._stack:@@ -2929,8 +2931,10 @@ class _ModelTypeStack: @contextmanager def push(self, type_obj: type) -> Iterator[None]: self._stack.append(type_obj)- yield- self._stack.pop()+ try:+ yield+ finally:+ self._stack.pop() def get(self) -> type | None: if self._stack:tests/test_edge_cases.pyindex f5e0de1a1..981d787c0 100644@@ -3218,3 +3218,53 @@ def test_get_pydantic_core_schema_instance() -> None: ta = TypeAdapter(SchemaProvider()) assert ta.validate_python('1') == 1+++def test_model_type_stack_popped_after_schema_generation_error() -> None:+ """https://github.com/pydantic/pydantic/issues/13857"""++ class Unsupported:+ pass++ class Bad(TypedDict):+ x: Unsupported++ class Fallback:+ @classmethod+ def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> CoreSchema:+ try:+ return handler.generate_schema(Bad)+ except PydanticSchemaGenerationError:+ return core_schema.any_schema()++ class Model(BaseModel):+ a: Fallback+ child: Self | None = None++ m = Model.model_validate({'a': 1, 'child': {'a': 2}})+ assert isinstance(m.child, Model)+++def test_field_name_stack_popped_after_schema_generation_error() -> None:+ """https://github.com/pydantic/pydantic/issues/13857"""++ class Unsupported:+ pass++ class Bad(TypedDict):+ x: Unsupported++ field_names: list[str | None] = []++ class Fallback:+ @classmethod+ def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> CoreSchema:+ try:+ handler.generate_schema(Bad)+ except PydanticSchemaGenerationError:+ pass+ field_names.append(handler.field_name)+ return core_schema.any_schema()++ TypeAdapter(Fallback)+ assert field_names == [None]