Backtestspydanticrun-20261005-183002#13621

Issue #13621 Merged fix PR #13624 Run 5 Oct 2026 · run-20261005-183002 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 B = our agent, Patch A = the merged fix.

Both patches make the three core changes the issue identifies: they add `serialization_exclude_if` to the `SerField` traversal, `class` to the `EnumSerializer` traversal, and `lookup` to all four `EnumValidator<T>` traversals. Both therefore fix the reported root cause.

Patch B also adds traversal edges for closely related fields that hold Python objects:
- `ComputedField.serialization_exclude_if`
- `GeneralFieldsSerializer.extra_serializer`
- `ModelFieldsValidator.extras_keys_validator`
- `DataclassArgsValidator.extras_validator`
- the unhashable and primitive stores in `LiteralLookup`

This is the same class of bug, and each addition is small and low-risk. Patch B adds a test for each one, so the additions are not unverified churn.

B's tests follow the issue's reproduction closely. They build models in a disposable module so that enum methods and lambdas create the cycle through `__globals__`, then assert the weakrefs are cleared. They cover str, int, float and plain enums, `Field(exclude_if)`, and the extra fixes. B also keeps the existing free-threaded xfail and marks its tests thread-unsafe.

Patch A's new pydantic-core tests are reasonable. The enum serializer and validator tests each isolate one missing edge, and the `exclude_if` test captures `cls` in its lambda. Each would plausibly fail before the fix.

However, Patch A also changes existing tests in ways unrelated to the issue:
- It removes the `is_free_threaded` xfail markers from `test_gc_schema_serializer` and `test_gc_schema_validator`, which may cause failures on free-threaded Python older than 3.14.
- It renames attributes such as `__schema__` to `__pydantic_core_schema__`.
- It converts comments to docstrings and moves the `EnumSerializer` macro.

This churn adds risk and obscures the fix.

Overall, B is the stronger patch: it has equal core correctness, more thorough end-to-end tests matching the issue scenario, no regressions to existing test markers, and related hardening that is backed by tests.

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

17m 9s

Wall-clock time in the container

Full test suite

No new failures

12,332 passed · 500 skipped · 12,832 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

252vs 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+242 −10
pydantic-core/src/serializers/computed_fields.rsindex 5bb3841b..4e1946dd 100644@@ -110,7 +110,10 @@ impl ComputedField {     } } -impl_py_gc_traverse!(ComputedField { serializer });+impl_py_gc_traverse!(ComputedField {+    serializer,+    serialization_exclude_if+});  impl PyGcTraverse for ComputedFields {     fn py_gc_traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {pydantic-core/src/serializers/fields.rsindex ba18ee4f..37a983f2 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(@@ -337,7 +340,8 @@ pub fn exclude_field_by_value<'py>(  impl_py_gc_traverse!(GeneralFieldsSerializer {     fields,-    computed_fields+    computed_fields,+    extra_serializer });  impl TypeSerializer for GeneralFieldsSerializer {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/dataclass.rsindex 93f9c56c..87c9d836 100644@@ -136,7 +136,10 @@ impl BuildValidator for DataclassArgsValidator {  impl_py_gc_traverse!(Field { validator }); -impl_py_gc_traverse!(DataclassArgsValidator { fields });+impl_py_gc_traverse!(DataclassArgsValidator {+    fields,+    extras_validator+});  impl Validator for DataclassArgsValidator {     fn validate<'py>(pydantic-core/src/validators/enum_.rsindex 6ef685da..28a32a87 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/src/validators/literal.rsindex c9195a78..681137fc 100644@@ -230,6 +230,12 @@ impl<T: Debug> LiteralLookup<T> { impl<T: PyGcTraverse + Debug> PyGcTraverse for LiteralLookup<T> {     fn py_gc_traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {         self.expected_py_dict.py_gc_traverse(visit)?;+        if let Some(expected_py_values) = &self.expected_py_values {+            for (value, _) in expected_py_values {+                value.py_gc_traverse(visit)?;+            }+        }+        self.expected_py_primitives.py_gc_traverse(visit)?;         self.values.py_gc_traverse(visit)?;         Ok(())     }pydantic-core/src/validators/model_fields.rsindex 5e8fe034..d9078f13 100644@@ -126,7 +126,8 @@ impl BuildValidator for ModelFieldsValidator {  impl_py_gc_traverse!(ModelFieldsValidator {     fields,-    extras_validator+    extras_validator,+    extras_keys_validator });  impl Validator for ModelFieldsValidator {tests/test_garbage_collection.pynew file mode 100644index 00000000..89037c49@@ -0,0 +1,215 @@+"""Tests that transient models are collectable by the garbage collector.++The models below are defined in a disposable module namespace, so callables defined alongside them+(enum methods, lambdas, ...) reference the namespace through their `__globals__`, which in turn references+the model. Such reference cycles go through objects held by pydantic-core validators and serializers, and+can only be collected if those report all the Python objects they hold to the garbage collector.+"""++import gc+import platform+import sys+import types+import typing+import weakref++import pytest++pytestmark = [+    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'+    ),+    pytest.mark.xfail(+        getattr(sys, '_is_gil_enabled', lambda: True)() is False and sys.version_info < (3, 14),+        reason='GC leaks on free-threaded (<3.14)',+    ),+    pytest.mark.thread_unsafe(reason='Uses a shared `sys.modules` entry and clears process-wide `typing` caches'),+]+++def transient_module(source: str, class_names: tuple[str, ...]) -> tuple[weakref.ref, ...]:+    name = '_pydantic_transient_gc_module'+    module = types.ModuleType(name)+    sys.modules[name] = module+    try:+        exec(compile(source, f'<{name}>', 'exec'), module.__dict__)+        refs = tuple(weakref.ref(module.__dict__[class_name]) for class_name in class_names)+    finally:+        del sys.modules[name]+    del module+    return refs+++def assert_collected(refs: tuple[weakref.ref, ...]) -> None:+    # `typing` caches parametrized aliases such as `Annotated[str, AfterValidator(...)]`, which would otherwise+    # keep the metadata (and the namespace it references) alive, independently of pydantic:+    for cleanup in typing._cleanups:  # pyright: ignore[reportAttributeAccessIssue]+        cleanup()+    for _ in range(5):+        gc.collect()+    assert [ref() for ref in refs] == [None] * len(refs)+++def test_enum_with_method_collected() -> None:+    refs = transient_module(+        """+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++assert Model(membership='full').model_dump() == {'membership': Membership.FULL}+""",+        ('Membership', 'Model'),+    )+    assert_collected(refs)+++@pytest.mark.parametrize('enum_base', ['int, Enum', 'float, Enum', 'Enum'])+def test_other_enum_kinds_with_method_collected(enum_base: str) -> None:+    refs = transient_module(+        f"""+from enum import Enum+from pydantic import BaseModel++class Membership({enum_base}):+    FULL = 1++    def label(self) -> str:+        return str(self.value)++class Model(BaseModel):+    membership: Membership++assert Model(membership=1).membership is Membership.FULL+""",+        ('Membership', 'Model'),+    )+    assert_collected(refs)+++def test_field_exclude_if_collected() -> None:+    refs = transient_module(+        """+from pydantic import BaseModel, Field++class Model(BaseModel):+    value: int = Field(exclude_if=lambda value: value == 0)++assert Model(value=0).model_dump() == {}+""",+        ('Model',),+    )+    assert_collected(refs)+++def test_computed_field_exclude_if_collected() -> None:+    refs = transient_module(+        """+from pydantic import BaseModel, computed_field++class Model(BaseModel):+    value: int++    @computed_field(exclude_if=lambda value: value == 0)+    @property+    def double(self) -> int:+        return self.value * 2++assert Model(value=0).model_dump() == {'value': 0}+""",+        ('Model',),+    )+    assert_collected(refs)+++def test_extra_items_serializer_collected() -> None:+    refs = transient_module(+        """+from typing import Annotated+from pydantic import BaseModel, ConfigDict, PlainSerializer++class Model(BaseModel):+    model_config = ConfigDict(extra='allow')+    __pydantic_extra__: dict[str, Annotated[int, PlainSerializer(lambda v: v + 1)]]++assert Model(a=1).model_dump() == {'a': 2}+""",+        ('Model',),+    )+    assert_collected(refs)+++def test_extra_keys_validator_collected() -> None:+    refs = transient_module(+        """+from typing import Annotated+from pydantic import AfterValidator, BaseModel, ConfigDict++class Model(BaseModel):+    model_config = ConfigDict(extra='allow')+    __pydantic_extra__: dict[Annotated[str, AfterValidator(lambda v: v.upper())], int]++assert Model(a=1).model_extra == {'A': 1}+""",+        ('Model',),+    )+    assert_collected(refs)+++def test_literal_unhashable_value_collected() -> None:+    # unhashable literal values are stored separately from hashable ones in pydantic-core+    refs = transient_module(+        """+from pydantic_core import SchemaValidator, core_schema++class Unhashable:+    __hash__ = None++    def __eq__(self, other):+        return isinstance(other, Unhashable)++VALUE = Unhashable()++class Holder:+    validator = SchemaValidator(core_schema.literal_schema([VALUE]))++assert Holder.validator.validate_python(Unhashable()) is VALUE+""",+        ('Unhashable', 'Holder'),+    )+    assert_collected(refs)+++def test_dataclass_args_extras_validator_collected() -> None:+    refs = transient_module(+        """+from pydantic_core import SchemaValidator, core_schema++class Extra:+    def method(self):+        return Holder++args_schema = core_schema.dataclass_args_schema('Holder', [], extra_behavior='allow')+args_schema['extras_schema'] = core_schema.is_instance_schema(Extra)++class Holder:+    validator = SchemaValidator(args_schema)++extra = Extra()+assert Holder.validator.validate_python({'a': extra}) == ({'a': extra}, None)+""",+        ('Extra', 'Holder'),+    )+    assert_collected(refs) 
Merged fix · PR #13624+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)