Backtestspydanticrun-20260923-170312#13621

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

Memory leak: transient models using Enum methods or Field(exclude_if=...) survive GC

Better

Our patch was judged better than the merged fix.

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

Both patches make identical root-cause Rust fixes — adding serialization_exclude_if to SerField traversal, class to EnumSerializer traversal, and lookup to every EnumValidator<T> traversal — exactly the missing PyGcTraverse edges the issue identifies. So on correctness they are equivalent; both resolve the leak at its source. The decision turns on tests, scope, and craft. Patch A confines its change to a single new test file (tests/test_gc.py) that faithfully reproduces the issue's own scenario: an Enum with a Python method (the case the issue notes requires BOTH serializer and validator edges), a Field(exclude_if=...) case, and control cases that guard against false passes. These are genuine before/after regression tests with no collateral edits. Patch B's tests are also targeted (isolating serializer vs. validator edges via raw core_schema), which is fine, but B carries significant unrelated scope creep in the same file: it renames __schema__/__validator__ to __pydantic_core_schema__/__pydantic_validator__ in pre-existing tests, rewrites comments into docstrings, and — most concerning — deletes the `@pytest.mark.xfail(is_free_threaded and sys.version_info < (3, 14))` markers from existing tests and rewrites PyPy issue URLs (even changing the issue number 3899→3898). Removing the free-threaded xfail markers is a behavioral change to unrelated tests that could break free-threaded CI and has nothing to do with this fix. B also relocates the EnumSerializer traverse macro purely for placement. On scope (criterion 3) and craft (criterion 4) A is clearly cleaner — minimal, focused, no risky drive-by edits — while matching B on correctness and tests. Hence A is the better fix.

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

31m 38s35 turns

Wall-clock time in the container

Full test suite

No new failures

6,549 passed · 367 skipped · 6,916 total

Contamination audit

Unknown

See the audit notes for this run

Patch size

171vs 139 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Transient BaseModel classes are not collected when either:

  • A model field references an Enum whose class defines a Python method.
  • A model field uses Field(exclude_if=<Python callable>).

After the defining module is removed from sys.modules and every ordinary strong reference is dropped, weak references to the model and enum classes remain alive after repeated full gc.collect() calls. Repeating this construction in disposable module namespaces causes linear memory growth.

Controls using an enum without methods or a field without exclude_if are collected normally.

I encountered this in combination with a Temporal workflow sandbox. With a large interconnected model graph and high volume Temporal workflows this can result in multi-GiB process growth relatively quickly.

The likely cause is missing PyGcTraverse edges for Python objects held by pydantic-core:

Traversing py_schema does not compensate for another unreported direct reference: CPython’s collector accounts for every actual strong edge individually.

I tested a temporary build from Pydantic main at c67a1397327c6abc1a2e2e921af01aebbbeedf1c. Adding only these traversal edges made all objects in the reproduction collectible:

  • Add serialization_exclude_if to SerField traversal.
  • Add class to EnumSerializer traversal.
  • Add lookup to every EnumValidator<T> traversal.

For the enum case, changing only the serializer or only the validator was insufficient; both missing edges were required.

This appears related to earlier missing-traversal fixes such as:

I would be happy to submit a focused patch.

(please note that this analysis was LLM assisted)

Example Code

import gc
import sys
import types
import weakref

def transient_module(name, source, class_names):
    module = types.ModuleType(name)
    sys.modules[name] = module
    exec(compile(source, f"<{name}>", "exec"), module.__dict__)
    refs = tuple(
        weakref.ref(module.__dict__[class_name])
        for class_name in class_names
    )
    del sys.modules[name]
    del module
    return refs

enum_ref, enum_model_ref = transient_module(
    "_pydantic_enum_gc_repro",
    """
from enum import Enum
from pydantic import BaseModel
class Membership(str, Enum):
    FULL = "full"
    def label(self) -> str:
        return self.value
class Model(BaseModel):
    membership: Membership
""",
    ("Membership", "Model"),
)

(exclude_if_model_ref,) = transient_module(
    "_pydantic_exclude_if_gc_repro",
    """
from pydantic import BaseModel, Field
class Model(BaseModel):
    value: int = Field(exclude_if=lambda value: False)
""",
    ("Model",),
)

for _ in range(5):
    gc.collect()

# All three should be False because no intentional strong references remain.
print("enum alive:", enum_ref() is not None)
print("enum model alive:", enum_model_ref() is not None)
print("exclude_if model alive:", exclude_if_model_ref() is not None)

Python, Pydantic & OS Version

pydantic version: 2.12.5
        pydantic-core version: 2.41.5
          pydantic-core build: profile=release pgo=false
               python version: 3.11.15 (main, Aug  5 2026, 03:58:57) [GCC 12.2.0]
                     platform: Linux-6.5.0-1018-oem-x86_64-with-glibc2.36
             related packages: typing_extensions-4.15.0 pydantic-extra-types-2.10.5 mypy-1.16.0
                       commit: unknown

The two patches

Our patch+165 −6
pydantic-core/src/serializers/fields.rsindex ba18ee4f..0d182849 100644@@ -35,7 +35,7 @@ pub(super) struct SerField {     pub serialization_exclude_if: Option<Py<PyAny>>, } -impl_py_gc_traverse!(SerField { serializer });+impl_py_gc_traverse!(SerField { serializer, serialization_exclude_if });  impl SerField {     pub fn new(pydantic-core/src/serializers/type_serializers/enum_.rsindex 0d2819ac..1ad123e9 100644@@ -48,7 +48,7 @@ impl BuildSerializer for EnumSerializer {     } } -impl_py_gc_traverse!(EnumSerializer { serializer });+impl_py_gc_traverse!(EnumSerializer { class, serializer });  impl TypeSerializer for EnumSerializer {     fn to_python<'py>(&self, value: &Bound<'py, PyAny>, state: &mut SerializationState<'py>) -> PyResult<Py<PyAny>> {pydantic-core/src/validators/enum_.rsindex 6ef685da..7717b06a 100644@@ -168,7 +168,7 @@ impl<T: EnumValidateValue> Validator for EnumValidator<T> { #[derive(Debug, Clone)] pub struct PlainEnumValidator; -impl_py_gc_traverse!(EnumValidator<PlainEnumValidator> { class, missing });+impl_py_gc_traverse!(EnumValidator<PlainEnumValidator> { class, missing, lookup });  impl EnumValidateValue for PlainEnumValidator {     fn validate_value<'py, I: Input<'py> + ?Sized>(@@ -200,7 +200,7 @@ impl EnumValidateValue for PlainEnumValidator { #[derive(Debug, Clone)] pub struct IntEnumValidator; -impl_py_gc_traverse!(EnumValidator<IntEnumValidator> { class, missing });+impl_py_gc_traverse!(EnumValidator<IntEnumValidator> { class, missing, lookup });  impl EnumValidateValue for IntEnumValidator {     fn validate_value<'py, I: Input<'py> + ?Sized>(@@ -216,7 +216,7 @@ impl EnumValidateValue for IntEnumValidator { #[derive(Debug, Clone)] pub struct StrEnumValidator; -impl_py_gc_traverse!(EnumValidator<StrEnumValidator> { class, missing });+impl_py_gc_traverse!(EnumValidator<StrEnumValidator> { class, missing, lookup });  impl EnumValidateValue for StrEnumValidator {     fn validate_value<'py, I: Input<'py> + ?Sized>(@@ -232,7 +232,7 @@ impl EnumValidateValue for StrEnumValidator { #[derive(Debug, Clone)] pub struct FloatEnumValidator; -impl_py_gc_traverse!(EnumValidator<FloatEnumValidator> { class, missing });+impl_py_gc_traverse!(EnumValidator<FloatEnumValidator> { class, missing, lookup });  impl EnumValidateValue for FloatEnumValidator {     fn validate_value<'py, I: Input<'py> + ?Sized>(tests/test_gc.pynew file mode 100644index 00000000..ed9054ac@@ -0,0 +1,159 @@+"""Regression tests for garbage collection of transient ``BaseModel`` subclasses.++These tests check that model classes (and any enum classes they reference) are+garbage-collected once all strong references are dropped. Missing GC traversal+edges in ``pydantic-core`` can leak such classes in specific scenarios:++* a field references an :class:`~enum.Enum` whose class defines a Python method;+* a field uses ``Field(exclude_if=<callable>)``.++See https://github.com/pydantic/pydantic/issues/13621.+"""++from __future__ import annotations++import gc+import platform+import sys+import types+import weakref+from collections.abc import Callable+from time import sleep, time++import pytest++try:+    is_free_threaded = not sys._is_gil_enabled()+except AttributeError:+    is_free_threaded = False+++# Mirrors the ``assert_gc`` helper in ``pydantic-core/tests/conftest.py``. On+# free-threaded builds ``gc.collect()`` may return before all cleanup is done,+# so we retry in a loop until the predicate passes or we time out.+def assert_gc(test: Callable[[], bool], timeout: float = 10) -> None:+    """Retry garbage collection until ``test`` passes or ``timeout`` is reached."""+    start = now = time()+    while now - start < timeout:+        if test():+            return+        gc.collect()+        sleep(0.1)+        now = time()+    raise AssertionError('Timeout waiting for GC')+++def transient_module(name: str, source: str, class_names: 'tuple[str, ...]') -> 'tuple[weakref.ref, ...]':+    """Build classes inside a disposable module namespace and return weakrefs to them.++    The module is registered in ``sys.modules`` only for the duration of the+    ``exec`` (so that e.g. ``from __future__`` and forward references resolve as+    they would for a real module), then removed and dropped along with every+    other strong reference. Only the returned weakrefs remain.+    """+    module = types.ModuleType(name)+    sys.modules[name] = module+    exec(compile(source, f'<{name}>', 'exec'), module.__dict__)+    refs = tuple(weakref.ref(module.__dict__[c]) for c in class_names)+    del sys.modules[name]+    del module+    return refs+++ENUM_WITH_METHOD_SOURCE = """+from enum import Enum+from pydantic import BaseModel+++class Membership(str, Enum):+    FULL = 'full'+    TRIAL = 'trial'++    def label(self) -> str:+        return self.value+++class Model(BaseModel):+    membership: Membership+"""++ENUM_WITHOUT_METHOD_SOURCE = """+from enum import Enum+from pydantic import BaseModel+++class Membership(str, Enum):+    FULL = 'full'+    TRIAL = 'trial'+++class Model(BaseModel):+    membership: Membership+"""++EXCLUDE_IF_SOURCE = """+from pydantic import BaseModel, Field+++class Model(BaseModel):+    value: int = Field(exclude_if=lambda value: False)+"""++NO_EXCLUDE_IF_SOURCE = """+from pydantic import BaseModel, Field+++class Model(BaseModel):+    value: int = Field()+"""+++@pytest.mark.xfail(is_free_threaded and sys.version_info < (3, 14), reason='GC leaks on free-threaded (<3.14)')+@pytest.mark.xfail(+    condition=platform.python_implementation() == 'PyPy', reason='https://foss.heptapod.net/pypy/pypy/-/issues/3899'+)+@pytest.mark.skipif(platform.python_implementation() == 'GraalVM', reason='Cannot reliably trigger GC on GraalPy')+def test_gc_enum_with_method() -> None:+    """A field referencing an ``Enum`` class with a Python method must not leak.++    Both the enum class and the model class should be collected once all strong+    references are dropped.+    """+    model_ref, enum_ref = transient_module(+        'transient_enum_with_method', ENUM_WITH_METHOD_SOURCE, ('Model', 'Membership')+    )++    assert_gc(lambda: model_ref() is None and enum_ref() is None)+++@pytest.mark.xfail(is_free_threaded and sys.version_info < (3, 14), reason='GC leaks on free-threaded (<3.14)')+@pytest.mark.xfail(+    condition=platform.python_implementation() == 'PyPy', reason='https://foss.heptapod.net/pypy/pypy/-/issues/3899'+)+@pytest.mark.skipif(platform.python_implementation() == 'GraalVM', reason='Cannot reliably trigger GC on GraalPy')+def test_gc_field_exclude_if() -> None:+    """A field using ``Field(exclude_if=<callable>)`` must not leak the model class."""+    (model_ref,) = transient_module('transient_exclude_if', EXCLUDE_IF_SOURCE, ('Model',))++    assert_gc(lambda: model_ref() is None)+++@pytest.mark.xfail(is_free_threaded and sys.version_info < (3, 14), reason='GC leaks on free-threaded (<3.14)')+@pytest.mark.xfail(+    condition=platform.python_implementation() == 'PyPy', reason='https://foss.heptapod.net/pypy/pypy/-/issues/3899'+)+@pytest.mark.skipif(platform.python_implementation() == 'GraalVM', reason='Cannot reliably trigger GC on GraalPy')+def test_gc_controls() -> None:+    """Control cases that collect normally both before and after the fix.++    An enum *without* methods and a field *without* ``exclude_if`` should always+    be garbage-collected; these guard against the tests above passing for the+    wrong reason (e.g. GC being globally broken in the test environment).+    """+    model_ref, enum_ref = transient_module(+        'transient_enum_without_method', ENUM_WITHOUT_METHOD_SOURCE, ('Model', 'Membership')+    )+    assert_gc(lambda: model_ref() is None and enum_ref() is None)++    (plain_model_ref,) = transient_module('transient_no_exclude_if', NO_EXCLUDE_IF_SOURCE, ('Model',))+    assert_gc(lambda: plain_model_ref() is None) 
Merged fix · PR #+118 −21
pydantic-core/src/serializers/fields.rsindex ba18ee4f3..8631d0b09 100644@@ -35,7 +35,10 @@ pub(super) struct SerField {     pub serialization_exclude_if: Option<Py<PyAny>>, } -impl_py_gc_traverse!(SerField { serializer });+impl_py_gc_traverse!(SerField {+    serializer,+    serialization_exclude_if+});  impl SerField {     pub fn new(pydantic-core/src/serializers/type_serializers/enum_.rsindex 0d2819ac2..b4e76133c 100644@@ -23,6 +23,8 @@ pub struct EnumSerializer {     serializer: Option<Arc<CombinedSerializer>>, } +impl_py_gc_traverse!(EnumSerializer { class, serializer });+ impl BuildSerializer for EnumSerializer {     const EXPECTED_TYPE: &'static str = "enum"; @@ -48,8 +50,6 @@ impl BuildSerializer for EnumSerializer {     } } -impl_py_gc_traverse!(EnumSerializer { serializer });- impl TypeSerializer for EnumSerializer {     fn to_python<'py>(&self, value: &Bound<'py, PyAny>, state: &mut SerializationState<'py>) -> PyResult<Py<PyAny>> {         let py = value.py();pydantic-core/src/validators/enum_.rsindex 6ef685daf..28a32a874 100644@@ -168,7 +168,7 @@ impl<T: EnumValidateValue> Validator for EnumValidator<T> { #[derive(Debug, Clone)] pub struct PlainEnumValidator; -impl_py_gc_traverse!(EnumValidator<PlainEnumValidator> { class, missing });+impl_py_gc_traverse!(EnumValidator<PlainEnumValidator> { class, lookup, missing });  impl EnumValidateValue for PlainEnumValidator {     fn validate_value<'py, I: Input<'py> + ?Sized>(@@ -200,7 +200,7 @@ impl EnumValidateValue for PlainEnumValidator { #[derive(Debug, Clone)] pub struct IntEnumValidator; -impl_py_gc_traverse!(EnumValidator<IntEnumValidator> { class, missing });+impl_py_gc_traverse!(EnumValidator<IntEnumValidator> { class, lookup, missing });  impl EnumValidateValue for IntEnumValidator {     fn validate_value<'py, I: Input<'py> + ?Sized>(@@ -216,7 +216,7 @@ impl EnumValidateValue for IntEnumValidator { #[derive(Debug, Clone)] pub struct StrEnumValidator; -impl_py_gc_traverse!(EnumValidator<StrEnumValidator> { class, missing });+impl_py_gc_traverse!(EnumValidator<StrEnumValidator> { class, lookup, missing });  impl EnumValidateValue for StrEnumValidator {     fn validate_value<'py, I: Input<'py> + ?Sized>(@@ -232,7 +232,7 @@ impl EnumValidateValue for StrEnumValidator { #[derive(Debug, Clone)] pub struct FloatEnumValidator; -impl_py_gc_traverse!(EnumValidator<FloatEnumValidator> { class, missing });+impl_py_gc_traverse!(EnumValidator<FloatEnumValidator> { class, lookup, missing });  impl EnumValidateValue for FloatEnumValidator {     fn validate_value<'py, I: Input<'py> + ?Sized>(pydantic-core/tests/test_garbage_collection.pyindex e53cdc564..7ac338f77 100644@@ -1,6 +1,6 @@ import platform-import sys from collections.abc import Iterable+from enum import Enum from typing import Any from weakref import WeakValueDictionary @@ -8,7 +8,7 @@ import pytest  from pydantic_core import SchemaSerializer, SchemaValidator, core_schema -from .conftest import assert_gc, is_free_threaded+from .conftest import assert_gc  GC_TEST_SCHEMA_INNER = core_schema.definitions_schema(     core_schema.definition_reference_schema(schema_ref='model'),@@ -21,18 +21,18 @@ GC_TEST_SCHEMA_INNER = core_schema.definitions_schema( )  -@pytest.mark.xfail(is_free_threaded and sys.version_info < (3, 14), reason='GC leaks on free-threaded (<3.14)') @pytest.mark.xfail(-    condition=platform.python_implementation() == 'PyPy', reason='https://foss.heptapod.net/pypy/pypy/-/issues/3899'+    condition=platform.python_implementation() == 'PyPy', reason='https://github.com/pypy/pypy/issues/3898' ) @pytest.mark.skipif(platform.python_implementation() == 'GraalVM', reason='Cannot reliably trigger GC on GraalPy') def test_gc_schema_serializer() -> None:-    # test for https://github.com/pydantic/pydantic/issues/5136+    """https://github.com/pydantic/pydantic/issues/5136"""+     class BaseModel:-        __schema__: SchemaSerializer+        __pydantic_core_schema__: SchemaSerializer          def __init_subclass__(cls) -> None:-            cls.__schema__ = SchemaSerializer(+            cls.__pydantic_core_schema__ = SchemaSerializer(                 core_schema.model_schema(cls, GC_TEST_SCHEMA_INNER), config={'ser_json_timedelta': 'float'}             ) @@ -50,18 +50,18 @@ def test_gc_schema_serializer() -> None:     assert_gc(lambda: len(cache) == 0)  -@pytest.mark.xfail(is_free_threaded and sys.version_info < (3, 14), reason='GC leaks on free-threaded (<3.14)') @pytest.mark.xfail(-    condition=platform.python_implementation() == 'PyPy', reason='https://foss.heptapod.net/pypy/pypy/-/issues/3899'+    condition=platform.python_implementation() == 'PyPy', reason='https://github.com/pypy/pypy/issues/3898' ) @pytest.mark.skipif(platform.python_implementation() == 'GraalVM', reason='Cannot reliably trigger GC on GraalPy') def test_gc_schema_validator() -> None:-    # test for https://github.com/pydantic/pydantic/issues/5136+    """https://github.com/pydantic/pydantic/issues/5136"""+     class BaseModel:-        __validator__: SchemaValidator+        __pydantic_validator__: SchemaValidator          def __init_subclass__(cls) -> None:-            cls.__validator__ = SchemaValidator(+            cls.__pydantic_validator__ = SchemaValidator(                 schema=core_schema.model_schema(cls, GC_TEST_SCHEMA_INNER),                 config=core_schema.CoreConfig(extra_fields_behavior='allow'),             )@@ -81,11 +81,12 @@ def test_gc_schema_validator() -> None:   @pytest.mark.xfail(-    condition=platform.python_implementation() == 'PyPy', reason='https://foss.heptapod.net/pypy/pypy/-/issues/3899'+    condition=platform.python_implementation() == 'PyPy', reason='https://github.com/pypy/pypy/issues/3898' ) @pytest.mark.skipif(platform.python_implementation() == 'GraalVM', reason='Cannot reliably trigger GC on GraalPy') def test_gc_validator_iterator() -> None:-    # test for https://github.com/pydantic/pydantic/issues/9243+    """https://github.com/pydantic/pydantic/issues/9243"""+     class MyModel:         iter: Iterable[int] @@ -114,3 +115,96 @@ def test_gc_validator_iterator() -> None:         del iterable      assert_gc(lambda: len(cache) == 0)+++@pytest.mark.xfail(+    condition=platform.python_implementation() == 'PyPy', reason='https://github.com/pypy/pypy/issues/3898'+)+@pytest.mark.skipif(platform.python_implementation() == 'GraalVM', reason='Cannot reliably trigger GC on GraalPy')+def test_gc_enum_serializer_class() -> None:+    """https://github.com/pydantic/pydantic/issues/13621"""++    class EnumBase:+        __pydantic_serializer__: SchemaSerializer++    cache: WeakValueDictionary[int, Any] = WeakValueDictionary()++    for _ in range(10_000):++        class MyEnum(EnumBase, str, Enum):+            FULL = 'full'++        MyEnum.__pydantic_serializer__ = SchemaSerializer(core_schema.enum_schema(MyEnum, list(MyEnum), sub_type='str'))++        cache[id(MyEnum)] = MyEnum++        del MyEnum++    assert_gc(lambda: len(cache) == 0)+++@pytest.mark.xfail(+    condition=platform.python_implementation() == 'PyPy', reason='https://github.com/pypy/pypy/issues/3898'+)+@pytest.mark.skipif(platform.python_implementation() == 'GraalVM', reason='Cannot reliably trigger GC on GraalPy')+def test_gc_enum_validator_lookup() -> None:+    """https://github.com/pydantic/pydantic/issues/13621"""++    class EnumBase:+        __pydantic_validator__: SchemaValidator++    cache: WeakValueDictionary[int, Any] = WeakValueDictionary()++    for _ in range(10_000):++        class MyEnum(EnumBase, str, Enum):+            FULL = 'full'++        MyEnum.__pydantic_validator__ = SchemaValidator(core_schema.enum_schema(MyEnum, list(MyEnum), sub_type='str'))++        cache[id(MyEnum)] = MyEnum++        del MyEnum++    assert_gc(lambda: len(cache) == 0)+++@pytest.mark.xfail(+    condition=platform.python_implementation() == 'PyPy', reason='https://github.com/pypy/pypy/issues/3898'+)+@pytest.mark.skipif(platform.python_implementation() == 'GraalVM', reason='Cannot reliably trigger GC on GraalPy')+def test_gc_field_exclude_if() -> None:+    """https://github.com/pydantic/pydantic/issues/13621"""++    class Dummy:+        pass++    class BaseModel:+        __pydantic_serializer__: SchemaSerializer++        def __init_subclass__(cls) -> None:+            cls.__pydantic_serializer__ = SchemaSerializer(+                core_schema.model_schema(+                    Dummy,+                    core_schema.model_fields_schema(+                        {+                            'value': core_schema.model_field(+                                core_schema.int_schema(), serialization_exclude_if=lambda value, _cls=cls: False+                            )+                        }+                    ),+                )+            )++    cache: WeakValueDictionary[int, Any] = WeakValueDictionary()++    for _ in range(10_000):++        class MyModel(BaseModel):+            pass++        cache[id(MyModel)] = MyModel++        del MyModel++    assert_gc(lambda: len(cache) == 0) 

What the agent reported

The reviewer confirms the diff is correct and minimal, and I already verified via git status that only the three Rust files plus the new test changed. The work is complete.

Summary

What was wrong

Transient BaseModel classes leaked (survived GC) when a field referenced an Enum whose class defines a Python method, or used Field(exclude_if=<callable>). The root cause was missing PyGcTraverse edges in pydantic-core: Rust structs held strong references to Python objects but didn't report them to CPython's cyclic collector, so reference cycles running through those objects were never collectible.

What I changed

Three minimal Rust edits, exactly as the report prescribed (adding fields to the impl_py_gc_traverse! macro invocations):

  • pydantic-core/src/serializers/fields.rs:38 — added serialization_exclude_if to SerField traversal.
  • pydantic-core/src/serializers/type_serializers/enum_.rs:51 — added class to EnumSerializer traversal.
  • pydantic-core/src/validators/enum_.rs — added lookup to all four EnumValidator<T> traversal impls (Plain/Int/Str/Float, lines 171/203/219/235).

Added a regression test tests/test_gc.py reproducing the report's exact scenario (transient modules, weakrefs, retry-based assert_gc) with three tests covering the enum-with-method leak, the exclude_if leak, and a control (enum without methods / field without exclude_if).

Test evidence (each ./bt-test run rebuilt/used the mounted editable .so; I recompiled the extension in the container with maturin develop after the fix since the gate runs --no-sync)

  • Before fix (stale binary reflecting unmodified source): test_gc_enum_with_method and test_gc_field_exclude_if failed ("Timeout waiting for GC"); test_gc_controls passed — reproducing the report.
  • After fix (rebuilt binary): all 3 tests in tests/test_gc.py passed.
  • Blast radius / adjacent tests: pydantic-core/tests/test_garbage_collection.py, pydantic-core/tests/validators/test_enums.py, pydantic-core/tests/serializers/test_enum.py → 30 passed, 1 skipped; top-level tests/types/test_enum.py → 19 passed. Adding traversal edges only exposes references to the collector and cannot change validation/serialization behavior.

Requirements disposition

  1. Enum-with-method field leak fixed → implemented (class on EnumSerializer + lookup on EnumValidator), test test_gc_enum_with_method fails before / passes after.
  2. Field(exclude_if=...) leak fixed → implemented (serialization_exclude_if on SerField), test test_gc_field_exclude_if fails before / passes after.
  3. Report's note that both enum edges (serializer class + validator lookup) are required → honored: all four validator impls and the serializer were patched together.
  4. Controls (enum without methods / field without exclude_if) collect normally → verified by test_gc_controls (passes before and after).

All changes are left uncommitted in the working tree.