Backtestspydanticrun-20260929-204949#13780

Issue #13780 Merged fix PR #13785 Run 29 Sep 2026 · run-20260929-204949 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 correctly fix the reported root cause identically — snapshotting the class dict before iterating in `_decorator_infos_for_class` (A uses `list(...)`, B uses `.copy()`), which resolves the `RuntimeError: dictionary changed size during iteration`. The deciding factor is that B recognizes the same annotation-cache race occurs elsewhere: `LazyLocalNamespace.data` also iterates over class namespaces (via `vars()`), and B guards it (only copying MappingProxyType namespaces, which is precise). This is the same root cause, not a separate feature, so its tests (`test_model_rebuild_concurrent_subclass_creation`) faithfully reproduce the exact mechanism described in the issue (reading annotations sets `__annotations_cache__`/`__annotate_func__`). B's tests are also more true-to-issue, using barriers to maximize concurrency like the reproducer. Patch A's single test is portable (runs under GIL too) but more contrived, relying on a dedicated mutator thread rather than the actual annotation-cache mechanism. The one mark against B is the `main.py` `model_rebuild` change (mocks instead of delattr), which is a broader behavior change carrying some risk beyond the reported TypedDict issue — but it is accompanied by a dedicated test justifying it and addresses genuine free-threaded safety. On correctness breadth and test fidelity to the described mechanism, B edges out A; the additional scope is tested and low enough risk not to outweigh that.

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

9m 26s22 turns

Wall-clock time in the container

Full test suite

No new failures

12,712 passed · 509 skipped · 13,221 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

59vs 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+58 −1
pydantic/_internal/_decorators.pyindex 160a18c0..1a07df03 100644@@ -535,7 +535,7 @@ def _decorator_infos_for_class(     res = DecoratorInfos()     to_replace: list[tuple[str, Any]] = [] -    for var_name, var_value in vars(typ).items():+    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_type_adapter.pyindex 1038a829..cb24e3b8 100644@@ -1,4 +1,7 @@ import json+import sys+import threading+import time from dataclasses import dataclass from datetime import date, datetime from typing import Annotated, Any, ForwardRef, Generic, NamedTuple, TypeAlias, TypeVar, Union@@ -763,3 +766,57 @@ def test_validate_json_invalid_json():             'ctx': {'error': 'trailing comma at line 3 column 3'},         }     ]+++@pytest.mark.skipif(sys.platform == 'emscripten', reason='no threading on emscripten')+def test_concurrent_type_adapter_construction_typeddict():+    """Guard against `RuntimeError: dictionary changed size during iteration`.++    Building `TypeAdapter` instances for a `TypedDict` collects decorator info by iterating+    the class `__dict__`. If another thread mutates that dict concurrently, the iteration can+    raise `RuntimeError: dictionary changed size during iteration`. This test builds adapters+    from several threads while a mutator thread continuously mutates the class dict, and asserts+    no such `RuntimeError` is raised.+    """++    class Record(TypedDict):+        value: int++    # Widen the iteration window so the race is reliably hit on unfixed code.+    for i in range(500):+        setattr(Record, f'metadata_{i}', i)++    stop = threading.Event()+    errors: list[BaseException] = []++    def mutate() -> None:+        i = 0+        while not stop.is_set():+            setattr(Record, f'x_{i}', i)+            delattr(Record, f'x_{i}')+            i += 1++    def build() -> None:+        try:+            while not stop.is_set():+                assert TypeAdapter(Record).validate_python({'value': '42'}) == {'value': 42}+        except RuntimeError as exc:  # pragma: no cover - only on the bug+            errors.append(exc)+            stop.set()++    deadline = time.monotonic() + 2.0+    mutator = threading.Thread(target=mutate, daemon=True)+    builders = [threading.Thread(target=build, daemon=True) for _ in range(6)]+    try:+        mutator.start()+        for t in builders:+            t.start()+        while time.monotonic() < deadline and not stop.is_set():+            time.sleep(0.01)+    finally:+        stop.set()+        mutator.join(timeout=10)+        for t in builders:+            t.join(timeout=10)++    assert errors == [] 
Merged fix · PR #13785+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 fix is complete and verified. Here is my final report.

What was wrong

_decorator_infos_for_class in pydantic/_internal/_decorators.py:538 iterated over vars(typ).items() — a live mappingproxy view of the class's __dict__. When two threads build TypeAdapter instances for the same TypedDict concurrently, one thread's lazy annotation evaluation inserts __annotations_cache__ into the class dict (on free-threaded Python 3.14) while another thread is mid-iteration, raising RuntimeError: dictionary changed size during iteration. There is no per-TypedDict caching/lock around this collection, so every concurrent build races. I confirmed the same race fires even on this GIL build (the GIL is released at bytecode boundaries) by hammering the function with a concurrent mutator thread.

What I changed

  • pydantic/_internal/_decorators.py:538 (one line): vars(typ).items() → list(vars(typ).items()), snapshotting the class dict atomically before iterating. Loop body and semantics are otherwise untouched.
  • tests/test_type_adapter.py: added test_concurrent_type_adapter_construction_typeddict, which builds TypeAdapter(Record) from 6 threads while a mutator thread continuously mutates the class dict (window widened with 500 synthetic attributes), and asserts no RuntimeError is raised. Guarded for emscripten; threads joined in finally.

Test evidence

  • Regression test fails reliably on unfixed code (5/5 runs, RuntimeError: dictionary changed size during iteration) and passes after the fix (verified by implementer and in the gate run).
  • Gate via ./bt-test on test_decorators.py test_type_adapter.py test_types_typeddict.py test_validators.py test_computed_fields.py test_serialize.py: 635 passed, 3 skipped, 5 xfailed, plus the new test passing. The single failure, test_v1_validator_deprecated, is a pre-existing harness path artifact (/work/ vs /workspace/ filename prefix) — I confirmed it fails identically on a clean stashed tree with zero changes, so it is unrelated to this fix.
  • Reviewer confirmed the fix is minimal and correct, no analogous unguarded iteration missed in the same function, no scratch files/mocks/weakened tests.

Requirements disposition

  1. Fix the RuntimeError: dictionary changed size during iteration from concurrent TypeAdapter/TypedDict construction — ✅ Implemented (snapshot at _decorators.py:538) with test evidence (reliable fail→pass).
  2. Reproduces on main / lazy-annotation __annotations_cache__ cause — ✅ Root cause addressed exactly at the reported line; race reproduced and resolved empirically.
  3. Regression coverage for the reported scenario — ✅ Added test_concurrent_type_adapter_construction_typeddict exercising concurrent TypeAdapter(TypedDict) construction under concurrent class-dict mutation, asserting no RuntimeError.

All changes are left uncommitted in the working tree.