Backtestspydanticrun-20261013-104308#13857
_FieldNameStack/_ModelTypeStack lose their pop() on exception, corrupting later unrelated schema builds
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 identical core change: they wrap the `yield` in `try`/`finally` in both `_FieldNameStack.push()` and `_ModelTypeStack.push()`. That fixes the root cause the issue describes, so correctness on the reported bug is equal. The difference lies in the tests. Patch A's test in `tests/test_internal.py` builds a `GenerateSchema` and checks both stacks directly. It asserts `get()` is None after a push whose body raised. It then does a later unrelated push/pop and checks the stack returns to None. This is the issue's exact scenario, it would clearly fail before the fix (`get()` would return the stale entry), and it doesn't depend on how schema generation routes internally. Patch B's tests are end-to-end: a custom `__get_pydantic_core_schema__` swallows a schema-generation error from a TypedDict, then the test checks `Self` resolution and `handler.field_name`. They are realistic and show real-world impact, and they likely fail before the fix. But they are indirect and fragile: they only exercise the bug if TypedDict schema generation happens to push onto these stacks in that order. A future refactor could make them pass vacuously. Patch A also applies the same `try`/`finally` fix to `generic_recursion_self_type` in `_generics.py`, with a targeted regression test. That is extra hardening, so it is neutral under the scope criterion. It is the same pattern, small and low-risk, so it doesn't count against A. Overall, the fixes are equivalent and A's tests are the more direct and robust regression guard, so A wins narrowly.
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
2m 39s
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
77vs 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..bbd7afd6 100644@@ -2473,6 +2473,37 @@ def test_generic_recursion_contextvar(): assert not recursively_defined_type_refs() +def test_generic_recursion_nested_exception_does_not_leak_type_ref():+ T = TypeVar('T')++ class TestingException(Exception):+ pass++ class Model(BaseModel, Generic[T]):+ pass++ with generic_recursion_self_type(Model, (str,)) as outer_self_type:+ assert outer_self_type is None+ outer_refs = recursively_defined_type_refs()++ try:+ with generic_recursion_self_type(Model, (int,)):+ raise TestingException+ except TestingException:+ pass++ # The ref of the inner (failed) parametrization must have been removed,+ # while the outer one is still being tracked:+ assert recursively_defined_type_refs() == outer_refs++ # A later, unrelated parametrization with the same args must not be+ # wrongly treated as a recursive self-reference:+ with generic_recursion_self_type(Model, (int,)) as maybe_self_type:+ assert maybe_self_type is None++ assert not recursively_defined_type_refs()++ def test_limited_dict(): d = LimitedDict(10) d[1] = '1'tests/test_internal.pyindex 3bfc123f..81bd88d2 100644@@ -356,3 +356,31 @@ 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_on_exception() -> None:+ class TestingException(Exception):+ pass++ class Model(BaseModel):+ pass++ gen = GenerateSchema(ConfigWrapper(None))++ with pytest.raises(TestingException):+ with gen.field_name_stack.push('some_field'):+ raise TestingException+ assert gen.field_name_stack.get() is None++ with gen.field_name_stack.push('other_field'):+ assert gen.field_name_stack.get() == 'other_field'+ assert gen.field_name_stack.get() is None++ with pytest.raises(TestingException):+ with gen.model_type_stack.push(Model):+ raise TestingException+ assert gen.model_type_stack.get() is None++ with gen.model_type_stack.push(int):+ assert gen.model_type_stack.get() is int+ assert gen.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]