Backtestspydanticrun-20260923-170312#13780

Issue #13780 Merged fix PR # Run 23 Sep 2026 · run-20260923-170312 pydantic/pydantic

Concurrent TypeAdapter construction raises RuntimeError on free-threaded Python

Worse

The merged fix was judged better than our patch.

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

Both patches fix the exact site named in the issue (`_decorator_infos_for_class` iterating `vars(typ).items()`), and both do so with a snapshot. On correctness B's `vars(typ).copy()` is the stronger primitive: `dict.copy()` runs as a single locked C operation that is atomic against concurrent mutation, whereas Patch A's `list(vars(typ).items())` iterates the items view through the generic iterator protocol, which still carries the `ma_used` size-change check and is not clearly atomic under free-threading — so A's fix may not fully close the very window the issue describes. B also fixes the same class of race at the other iteration sites it can occur (`LazyLocalNamespace.data`), which is the same root cause (reading annotations lazily materializing `__annotations_cache__`/`__annotate_func__`). On tests, B adds a dedicated `test_freethreaded.py` that reproduces the issue's exact scenario (concurrent `TypeAdapter(TypedDict)` under a barrier) plus targeted concurrent tests for each site it touches, properly skip-guarded via a `is_free_threaded` conftest helper — these genuinely fail-before/pass-after on a free-threaded build. Patch A's regression test is single-threaded and simulates mutation via a MutatingDescriptor's `__get__`; it is doubtful the collect loop actually invokes that `__get__` during the `vars` iteration (the loop reads `.decorator_info`/`.wrapped` attributes on the proxy, not the wrapped descriptor), so the test may pass regardless of the fix — a weaker, possibly tautological test. Patch A wins on scope: it is minimal and surgical, while B's `main.py` change (replacing `delattr` with `set_model_mocks` in `model_rebuild`) is a behavioral change beyond the reported reproducer, adding risk. But that change is reasoned and covered by its own test, and scope is the third priority. Since B is stronger on the two higher-priority criteria (correctness completeness and effective, on-point regression tests), it is the better fix despite the broader footprint.

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

34m 13s16 turns

Wall-clock time in the container

Full test suite

No new failures

6,781 passed · 373 skipped · 7,154 total

Contamination audit

Unknown

See the audit notes for this run

Patch size

48vs 198 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Constructing separate TypeAdapter instances concurrently for the same new TypedDict can raise RuntimeError: dictionary changed size during iteration on free-threaded Python.

A full run produced 91 failures in 800 attempts with the GIL disabled and none with PYTHON_GIL=1. It also reproduces on Pydantic main at 1c8a330acc3077e77da64e3672c7c875fb4c6eaa.

Lazy annotation evaluation adds __annotations_cache__ while another thread iterates vars(typ).items() in _decorator_infos_for_class.

Example Code

from __future__ import annotations

import threading
from concurrent.futures import ThreadPoolExecutor

from pydantic import TypeAdapter
from typing_extensions import TypedDict


def run_round() -> None:
    class Record(TypedDict):
        value: int

    for index in range(1000):
        setattr(Record, f'metadata_{index}', index)

    barrier = threading.Barrier(8)

    def build(_: int) -> None:
        barrier.wait()
        TypeAdapter(Record).validate_python({'value': '42'})

    with ThreadPoolExecutor(max_workers=8) as executor:
        list(executor.map(build, range(8)))


for _ in range(100):
    run_round()

The synthetic attributes only widen the iteration window. They are not modified after the threads start.

Python, Pydantic & OS Version

pydantic version: 2.13.5
pydantic-core version: 2.46.5
python version: 3.14.3 free-threading build
platform: macOS-26.6.2-arm64
related packages: typing_extensions-4.15.0

The two patches

Our patch+47 −1
pydantic/_internal/_decorators.pyindex 160a18c0..d54ee92b 100644@@ -535,7 +535,10 @@ def _decorator_infos_for_class(     res = DecoratorInfos()     to_replace: list[tuple[str, Any]] = [] -    for var_name, var_value in vars(typ).items():+    # Take a snapshot of the class namespace: on the free-threaded build another thread may+    # mutate `typ.__dict__` (e.g. adding `__annotations_cache__` via lazy annotation evaluation)+    # while we iterate, which would raise "dictionary changed size during iteration" (see #13780).+    for var_name, var_value in list(vars(typ).items()):         if isinstance(var_value, PydanticDescriptorProxy):             info = var_value.decorator_info             if isinstance(info, ValidatorDecoratorInfo):tests/test_decorators.pyindex 667ff813..f822cc64 100644@@ -138,3 +138,46 @@ def test_decorator_info_not_mutated() -> None:      assert A.__pydantic_decorators__.computed_fields['func'].info.title is None     assert B.__pydantic_decorators__.computed_fields['func'].info.title == 'test'+++def test_decorator_infos_for_class_dict_not_mutated_during_iteration():+    """Regression test for #13780.++    On the free-threaded build, one thread adding an attribute to the class+    (e.g. ``__annotations_cache__`` from lazy annotation evaluation) while another+    iterates ``vars(typ).items()`` in ``_decorator_infos_for_class`` raised+    ``RuntimeError: dictionary changed size during iteration``. Reproduce that+    deterministically by widening the class ``__dict__`` from inside the loop body.+    """+    from pydantic._internal._decorators import (+        DecoratorInfos,+        FieldValidatorDecoratorInfo,+        PydanticDescriptorProxy,+    )++    class MutatingDescriptor:+        """A descriptor whose ``__get__`` grows the owning class' ``__dict__``,+        simulating a concurrent thread adding attributes mid-iteration."""++        def __get__(self, obj, objtype=None):+            for index in range(50):+                setattr(objtype, f'_widen_{index}', index)++            def func(cls, value):+                return value++            return func++    class Model:+        pass++    Model.my_validator = PydanticDescriptorProxy(+        wrapped=MutatingDescriptor(),+        decorator_info=FieldValidatorDecoratorInfo(+            fields=('x',), mode='after', check_fields=None, json_schema_input_type=None+        ),+    )++    decorators = DecoratorInfos.build(Model)++    assert 'my_validator' in decorators.field_validators 
Merged fix · PR #+186 −12
pydantic/_internal/_decorators.pyindex 160a18c00..72b668c53 100644@@ -535,7 +535,12 @@ def _decorator_infos_for_class(     res = DecoratorInfos()     to_replace: list[tuple[str, Any]] = [] -    for var_name, var_value in vars(typ).items():+    # Iterate on the vars with a copy to avoid changes in dictionary size during iteration.+    # This can happen if a concurrent thread has Pydantic processing the same `typ` (e.g. two+    # concurrent threads doing `TypeAdapter(SomeClassType)`), and such thread reads annotations+    # for the first time during the iteration here in the other thread (since 3.14, reading annotations+    # can set attributes such as `__annotations_cache__` or `__annotate_func__` to the type).+    for var_name, var_value in vars(typ).copy().items():         if isinstance(var_value, PydanticDescriptorProxy):             info = var_value.decorator_info             if isinstance(info, ValidatorDecoratorInfo):pydantic/_internal/_namespace_utils.pyindex d308f7e4c..495f17da6 100644@@ -4,6 +4,7 @@ import sys from collections.abc import Callable, Generator, Iterator, Mapping from contextlib import contextmanager from functools import cached_property+from types import MappingProxyType from typing import Any, NamedTuple, TypeAlias, TypeVar  from typing_extensions import ParamSpec, TypeAliasType, TypeVarTuple@@ -88,7 +89,12 @@ class LazyLocalNamespace(Mapping[str, Any]):      @cached_property     def data(self) -> dict[str, Any]:-        return {k: v for ns in self._namespaces for k, v in ns.items()}+        # In rare scenarios, a race condition can happen when iterating over class namespaces (i.e. created with `var(SomeClass)`),+        # if another thread accesses the type annotations for the first time (since 3.14, reading annotations can set attributes+        # such as `__annotations_cache__` or `__annotate_func__` to the type).+        return {+            k: v for ns in self._namespaces for k, v in (ns.copy() if isinstance(ns, MappingProxyType) else ns).items()+        }      def __len__(self) -> int:         return len(self.data)pydantic/main.pyindex 1c0258c69..395c3c85f 100644@@ -711,16 +711,12 @@ class BaseModel(metaclass=_model_construction.ModelMetaclass):              cls.__pydantic_complete__ = False -            for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):-                if attr in cls.__dict__ and not isinstance(-                    getattr(cls, attr), (_mock_val_ser.MockCoreSchema, _mock_val_ser.MockValSer)-                ):-                    # Deleting the validator/serializer is necessary as otherwise they can get reused in-                    # pydantic-core. Same applies for the core schema that can be reused in schema generation.-                    # We do so only if they aren't mock instances, otherwise concurrent reads of these attributes-                    # — performed without holding the rebuild lock (e.g. when instantiating the model) — can-                    # resolve them from the parent class.-                    delattr(cls, attr)+            if already_complete:+                # The existing validator/serializer must not be reused in pydantic-core, and the core schema+                # must not be reused in schema generation. If the model is already complete (i.e. `force=True`),+                # we set back mocks for the model (we could also delete the complete core schema/validator/serializer,+                # but this isn't thread-safe).+                _mock_val_ser.set_model_mocks(cls)              if _types_namespace is not None:                 rebuild_ns = _types_namespacetests/conftest.pyindex b066a013a..694c5855b 100644@@ -23,6 +23,11 @@ from pydantic import BaseModel from pydantic._internal._generate_schema import GenerateSchema from pydantic.json_schema import GenerateJsonSchema +try:+    is_free_threaded = not sys._is_gil_enabled()+except AttributeError:+    is_free_threaded = False+  def pytest_addoption(parser: pytest.Parser):     parser.addoption('--test-mypy', action='store_true', help='run mypy tests')tests/test_freethreaded.pynew file mode 100644index 000000000..af4ef4929@@ -0,0 +1,162 @@+import sys+import threading+from collections.abc import Callable+from concurrent.futures import ThreadPoolExecutor+from typing import Any++import pytest+from typing_extensions import TypedDict++import pydantic.dataclasses+from pydantic import BaseModel, TypeAdapter, field_validator++from .conftest import is_free_threaded++pytestmark = [+    pytest.mark.skipif(sys.platform == 'emscripten', reason='no threading on emscripten'),+    pytest.mark.skipif(not is_free_threaded, reason='only relevant on free-threaded builds'),+]+++def run_concurrently(+    setup: Callable[[], Any], target: Callable[[Any, int], Any], *, rounds: int = 100, threads: int = 8+):+    """Run `target` in `threads` threads at once, `rounds` times, with a fresh `setup()` result each round."""+    for _ in range(rounds):+        ctx = setup()+        barrier = threading.Barrier(threads)++        def work(index: int) -> None:+            barrier.wait()+            target(ctx, index)++        with ThreadPoolExecutor(max_workers=threads) as executor:+            for future in [executor.submit(work, i) for i in range(threads)]:+                future.result()+++def test_typed_dict_concurrent_type_adapter() -> None:+    def setup():+        class Record(TypedDict):+            value: int++        return Record++    def target(Record, _):+        assert TypeAdapter(Record).validate_python({'value': '42'}) == {'value': 42}++    run_concurrently(setup, target)+++def test_base_model_concurrent_creation_with_shared_base() -> None:+    def setup():+        class Mixin:+            a: int = 1++            @field_validator('a')+            @classmethod+            def val_a_1(cls, v: int) -> int:+                return v++            @field_validator('a')+            @classmethod+            def val_a_2(cls, v: int) -> int:+                return v++            @field_validator('a')+            @classmethod+            def val_a_3(cls, v: int) -> int:+                return v++        return Mixin++    def target(Mixin, _):+        class Model(BaseModel, Mixin):+            b: int++        assert Model(b='1').b == 1++    run_concurrently(setup, target)+++def test_dataclass_concurrent_creation_with_shared_base() -> None:+    def setup():+        class Base:+            a: int = 1++            @field_validator('a')+            @classmethod+            def val_a_1(cls, v: int) -> int:+                return v++            @field_validator('a')+            @classmethod+            def val_a_2(cls, v: int) -> int:+                return v++            @field_validator('a')+            @classmethod+            def val_a_3(cls, v: int) -> int:+                return v++        return Base++    def target(Base, _):+        @pydantic.dataclasses.dataclass+        class Sub(Base):+            b: int++        assert Sub(b='1').b == 1++    run_concurrently(setup, target)+++def test_model_rebuild_concurrent_subclass_creation(monkeypatch: pytest.MonkeyPatch) -> None:+    """Test targeted at our `LazyLocalNamespace.data` property implementation."""++    def setup():+        monkeypatch.delitem(globals(), 'Later', raising=False)++        class Model(BaseModel):+            # `Later` isn't defined yet, so the field is deferred and no annotations cache is set on the class:+            x: Later  # noqa: F821  # pyright: ignore[reportUndefinedVariable]++        # Widen the class dict so that iterating over it takes long enough for the race to happen:+        for i in range(3000):+            setattr(Model, f'attr_{i}', i)++        # Dynamically set the item in globals instead of a simple assignment to force `ForwardRef.evaluate()` into looking at the+        # provided namespace during evaluation (otherwise it doesn't look at globals/locals and uses `ForwardRef.__cell__` directly)+        monkeypatch.setitem(globals(), 'Later', int)+        return Model++    def target(Model, index: int):+        if index == 0:+            # Collecting the fields of the subclass reads the annotations of `Model` for the first time:+            class Sub(Model):+                pass++            assert Sub(x='1').x == 1+        else:+            Model.model_rebuild(force=True)++    run_concurrently(setup, target)+++def test_model_force_rebuild_concurrent_instantiation() -> None:+    """Test targeted at our logic in `model_rebuild()`, when we set back mocks on already complete models."""++    def setup():+        class Model(BaseModel):+            x: int++        assert Model(x=1).x == 1  # `Model` is complete, with a real validator set on the class+        return Model++    def target(Model, index):+        if index == 0:+            Model.model_rebuild(force=True)+        else:+            assert Model(x='1').x == 1++    run_concurrently(setup, target) 

What the agent reported

The review confirms the fix is correct, minimal, and complete. Here's my final report.

Summary

What was wrong: In pydantic/_internal/_decorators.py, _decorator_infos_for_class iterated the class namespace directly with for var_name, var_value in vars(typ).items():. On free-threaded Python, when separate TypeAdapter instances are built concurrently for the same new TypedDict, one thread's lazy annotation evaluation adds __annotations_cache__ to the class dict while another thread is mid-iteration over it, raising RuntimeError: dictionary changed size during iteration (GitHub #13780).

What I changed:

  • pydantic/_internal/_decorators.py (line 538): snapshot the namespace before iterating — for var_name, var_value in list(vars(typ).items()): — with an explanatory comment referencing #13780. This is the minimal fix; the loop body is untouched. The function is the single collection path for both typ and its bases, so both are covered.
  • tests/test_decorators.py: added test_decorator_infos_for_class_dict_not_mutated_during_iteration, a deterministic regression test. It places a PydanticDescriptorProxy wrapping a descriptor whose __get__ widens the class __dict__; DecoratorInfos.build reaches it mid-loop, mutating the dict exactly as the free-threaded race does. This reproduces the identical RuntimeError on a normal GIL build (the reporter's threaded snippet only fails on free-threaded builds, so it could not serve as a gate).

Test evidence:

  • Before the fix: the new test failed with RuntimeError: dictionary changed size during iteration at _decorators.py:538 — the exact reported error.
  • After the fix: ./bt-test tests/test_decorators.py → 32 passed (including the new test); ./bt-test tests/test_validators.py (heavy consumer of this path) → 179 passed, 2 pre-existing xfailed. No regressions.
  • Reviewer confirmed the diff is correct, minimal, touches only the two files, and adds no scratch files or weakened tests.

Requirements list:

  1. Fix concurrent TypeAdapter construction raising RuntimeError on free-threaded Python (the sole ask / "Initial Checks") — implemented (snapshot fix) with test evidence (fail-before/pass-after above).
  2. Example reproduction scenario (concurrent TypeAdapter(Record) over a mutated TypedDict) — covered by a deterministic regression test exercising the same _decorator_infos_for_class iteration and asserting the build succeeds; verified failing before and passing after.

All changes are left uncommitted in the working tree.