Backtestspydanticrun-20261009-110034#13857

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

_FieldNameStack/_ModelTypeStack lose their pop() on exception, corrupting later unrelated schema builds

Better

Our patch was judged better than the merged fix.

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

Both patches apply the same root-cause fix: they wrap `yield` in `try`/`finally` in both `_FieldNameStack.push()` and `_ModelTypeStack.push()`. So they are equal on correctness for the reported issue.

Patch A also applies the identical `try`/`finally` hardening to `generic_recursion_self_type` in `_generics.py`. That is the same bug pattern, the change is low-risk, and it has its own targeted test. Per the criteria this is neutral rather than a credit, and it does not obscure the main fix.

On tests, both add regressions that would fail before the change:
- Patch A's `test_internal` test drives a real `GenerateSchema` instance through a failing `TypedDict` schema build. It then directly asserts that `field_name_stack.get()` and `model_type_stack.get()` are `None`, that a later unrelated push does not reveal stale entries (the issue's exact scenario), and that `Self` is still rejected instead of resolving to the stale `TD`. This covers both stacks plus the downstream consequence. Its imports are local and self-contained.
- Patch B's tests are end-to-end through `__get_pydantic_core_schema__` handlers that swallow the error. They show user-visible effects: `Self` resolves correctly for a child model, and `handler.field_name` is `None`. These are realistic and valuable, but more indirect. They also depend on several module-level imports in `test_edge_cases.py` that the diff does not show, and their docstrings are placeholders.

The overall difference is small. Patch A's direct assertions on both stacks, which mirror the issue's reproduction, plus its self-contained test setup give it a slight edge on test quality and craft.

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

7m 13s

Wall-clock time in the container

Full test suite

No new failures

12,849 passed · 526 skipped · 13,375 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

74vs 62 merged

Changed lines, ours vs merged

Description

_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

Our patch+68 −6
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..5326253d 100644@@ -2473,6 +2473,31 @@ def test_generic_recursion_contextvar():     assert not recursively_defined_type_refs()  +def test_generic_recursion_self_type_nested_exception():+    T = TypeVar('T')++    class TestingException(Exception):+        pass++    class Model(BaseModel, Generic[T]):+        pass++    assert not recursively_defined_type_refs()+    with generic_recursion_self_type(Model, (int,)):+        outer_refs = recursively_defined_type_refs()+        try:+            with generic_recursion_self_type(Model, (str,)):+                assert len(recursively_defined_type_refs()) == len(outer_refs) + 1+                raise TestingException+        except TestingException:+            pass++        # The inner type ref must not leak into the still-active outer recursion cache:+        assert recursively_defined_type_refs() == outer_refs+        with generic_recursion_self_type(Model, (str,)) as self_type:+            assert self_type is None++ def test_limited_dict():     d = LimitedDict(10)     d[1] = '1'tests/test_internal.pyindex 3bfc123f..c3713650 100644@@ -356,3 +356,34 @@ 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_schema_generation_stacks_reset_after_exception() -> None:+    """A failure while generating a field/model schema must not leave stale entries on the+    field name and model type stacks of the `GenerateSchema` instance."""+    from typing_extensions import Self, TypedDict++    from pydantic import PydanticSchemaGenerationError, PydanticUserError++    class Unsupported:+        pass++    class TD(TypedDict):+        bad_field: Unsupported++    gen = GenerateSchema(ConfigWrapper(None))+    with pytest.raises(PydanticSchemaGenerationError):+        gen.generate_schema(TD)++    assert gen.field_name_stack.get() is None+    assert gen.model_type_stack.get() is None++    # Later, unrelated pushes must not reveal the stale entries either:+    with gen.field_name_stack.push('other_field'):+        assert gen.field_name_stack.get() == 'other_field'+    assert gen.field_name_stack.get() is None++    # `Self` outside of a model context is still rejected (instead of resolving to `TD`):+    with pytest.raises(PydanticUserError) as exc_info:+        gen.generate_schema(Self)+    assert exc_info.value.code == 'invalid-self-type' 
Merged fix · PR #13859+58 −4
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]