Backtestspydanticrun-20260930-144322#13621
Memory leak: transient models using Enum methods or Field(exclude_if=...) survive GC
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
The Rust changes are the same in both patches. Each adds `serialization_exclude_if` to `SerField` traversal, `class` to `EnumSerializer` traversal, and `lookup` to all four `EnumValidator<T>` traversals. That matches the root cause the issue identified, so the two are equally correct, and the difference comes down to tests and scope. Patch B's tests are stronger: - It parametrizes the enum GC test over all four validator variants (plain, int, str, float) and over both `SchemaValidator` and `SchemaSerializer`. So each changed traversal impl is exercised. - Its enum test builds the exact cycle from the issue: enum method closure -> model -> schema -> enum. - Its `exclude_if` test uses a closure cycle back to the model. - It adds end-to-end tests in `tests/test_main.py` using real `BaseModel`, `Enum`-with-method and `Field(exclude_if=...)`, mirroring the reported reproduction. - It keeps the existing free-threaded xfail convention on its new core tests. Patch A's new tests are valid regression tests: - The enum class is kept alive through the untraversed `class` and `lookup` edges. - The `exclude_if` lambda captures `cls` through a default argument. However, Patch A only covers the `str` sub_type and adds no high-level pydantic test. It also churns the existing tests in ways the issue does not ask for: - It removes the `is_free_threaded` xfail markers from the existing GC tests, which risks new failures on free-threaded Python below 3.14. - It drops the `sys` and `is_free_threaded` imports. - It renames the `__schema__`/`__validator__` attributes and rewrites comments as docstrings. That churn adds risk and obscures the fix. B wins on test coverage and scope discipline.
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
8m 16s14 turns
Wall-clock time in the container
Full test suite
No new failures
12,333 passed · 500 skipped · 12,833 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
152vs 139 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
Transient BaseModel classes are not collected when either:
- A model field references an
Enumwhose 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:
SerFieldownsserialization_exclude_if, but traverses onlyserializer: https://github.com/pydantic/pydantic/blob/c67a1397327c6abc1a2e2e921af01aebbbeedf1c/pydantic-core/src/serializers/fields.rs#L26-L38EnumSerializerownsclass, but traverses onlyserializer: https://github.com/pydantic/pydantic/blob/c67a1397327c6abc1a2e2e921af01aebbbeedf1c/pydantic-core/src/serializers/type_serializers/enum_.rs- Each
EnumValidator<T>ownslookup, but traverses onlyclassandmissing: https://github.com/pydantic/pydantic/blob/c67a1397327c6abc1a2e2e921af01aebbbeedf1c/pydantic-core/src/validators/enum_.rs
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_iftoSerFieldtraversal. - Add
classtoEnumSerializertraversal. - Add
lookupto everyEnumValidator<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:
- https://github.com/pydantic/pydantic/issues/5136
- https://github.com/pydantic/pydantic-core/pull/787
- https://github.com/pydantic/pydantic-core/pull/1100
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: unknownThe two patches
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..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/tests/test_garbage_collection.pyindex e53cdc56..8e557781 100644@@ -1,6 +1,7 @@ import platform import sys from collections.abc import Iterable+from enum import Enum from typing import Any from weakref import WeakValueDictionary @@ -114,3 +115,94 @@ def test_gc_validator_iterator() -> None: del iterable 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'+)+@pytest.mark.skipif(platform.python_implementation() == 'GraalVM', reason='Cannot reliably trigger GC on GraalPy')+@pytest.mark.parametrize(+ 'enum_base,sub_type,value',+ [+ pytest.param((), None, 1, id='plain'),+ pytest.param((int,), 'int', 1, id='int'),+ pytest.param((str,), 'str', 'a', id='str'),+ pytest.param((float,), 'float', 1.5, id='float'),+ ],+)+@pytest.mark.parametrize('schema_cls', [SchemaValidator, SchemaSerializer])+def test_gc_enum(schema_cls: Any, enum_base: tuple[type, ...], sub_type: Any, value: Any) -> None:+ # test that enum validators/serializers traverse the enum class and its members+ def create_model() -> type:+ class MyEnum(*enum_base, Enum):+ A = value++ def get_model(self) -> type:+ # reference cycle: enum -> function -> closure -> model -> schema -> enum+ return MyModel++ class MyModel:+ __schema__: Any++ MyModel.__schema__ = schema_cls(+ core_schema.model_schema(+ MyModel,+ core_schema.model_fields_schema(+ {+ 'e': core_schema.model_field(+ core_schema.enum_schema(MyEnum, list(MyEnum.__members__.values()), sub_type=sub_type)+ )+ }+ ),+ )+ )+ return MyModel++ cache: WeakValueDictionary[int, Any] = WeakValueDictionary()++ for _ in range(1_000):+ MyModel = create_model()++ cache[id(MyModel)] = MyModel++ del MyModel++ 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'+)+@pytest.mark.skipif(platform.python_implementation() == 'GraalVM', reason='Cannot reliably trigger GC on GraalPy')+def test_gc_serialization_exclude_if() -> None:+ # test that fields traverse their `serialization_exclude_if` callable+ def create_model() -> type:+ class MyModel:+ __schema__: SchemaSerializer++ def exclude_if(value: Any) -> bool:+ # reference cycle: model -> serializer -> exclude_if -> closure -> model+ return isinstance(value, MyModel)++ MyModel.__schema__ = SchemaSerializer(+ core_schema.model_schema(+ MyModel,+ core_schema.model_fields_schema(+ {'x': core_schema.model_field(core_schema.int_schema(), serialization_exclude_if=exclude_if)}+ ),+ )+ )+ return MyModel++ cache: WeakValueDictionary[int, Any] = WeakValueDictionary()++ for _ in range(10_000):+ MyModel = create_model()++ cache[id(MyModel)] = MyModel++ del MyModel++ assert_gc(lambda: len(cache) == 0)tests/test_main.pyindex db2b8539..bbbcaef6 100644@@ -1,3 +1,4 @@+import gc import json import platform import re@@ -5,6 +6,7 @@ import sys import threading import typing import warnings+import weakref from collections import defaultdict from collections.abc import Callable, Mapping from copy import deepcopy@@ -3901,3 +3903,49 @@ def test_replace() -> None: m = Model(x=1, y=2) assert replace(m, x=3) == Model(x=3, y=2)+++@pytest.mark.thread_unsafe(reason='GC is flaky')+@pytest.mark.skipif(platform.python_implementation() == 'PyPy', reason='PyPy does not play nice with PyO3 gc')+def test_model_with_enum_with_method_gets_cleaned_up() -> None:+ def create_model() -> type[BaseModel]:+ class Membership(str, Enum):+ FULL = 'full'++ def label(self) -> str:+ # reference cycle: enum -> method -> closure -> model -> validator/serializer -> enum+ return f'{Model.__name__}: {self.value}'++ class Model(BaseModel):+ membership: Membership++ assert Model(membership='full').model_dump() == {'membership': Membership.FULL}+ return Model++ refs = [weakref.ref(create_model()) for _ in range(100)]++ gc.collect(0)+ gc.collect(1)+ gc.collect(2)++ assert all(ref() is None for ref in refs)+++@pytest.mark.thread_unsafe(reason='GC is flaky')+@pytest.mark.skipif(platform.python_implementation() == 'PyPy', reason='PyPy does not play nice with PyO3 gc')+def test_model_with_field_exclude_if_gets_cleaned_up() -> None:+ def create_model() -> type[BaseModel]:+ class Model(BaseModel):+ # reference cycle: model -> serializer -> exclude_if -> closure -> model+ value: int = Field(exclude_if=lambda value: isinstance(value, Model))++ assert Model(value=1).model_dump() == {'value': 1}+ return Model++ refs = [weakref.ref(create_model()) for _ in range(100)]++ gc.collect(0)+ gc.collect(1)+ gc.collect(2)++ assert all(ref() is None for ref in refs)
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
I fixed the leak: transient models whose fields use an Enum with methods, or Field(exclude_if=...), are now garbage-collected. The issue's script now prints False False False; before the fix it printed True True True. The changes are uncommitted in the working tree.
What was wrong: three pydantic-core objects hold references to Python objects but don't declare them to Python's cycle collector (the impl_py_gc_traverse! lists). The collector couldn't see those references, so it treated anything in a cycle through them as still in use, and the cycle was never freed.
SerFielddidn't listserialization_exclude_if.EnumSerializerdidn't listclass.- None of the four
EnumValidator<T>versions (plain, int, str, float) listedlookup, which holds the enum members.
What I changed: I added those fields to the traversal lists, and nothing else in production code:
pydantic-core/src/serializers/fields.rs:38:SerField { serializer, serialization_exclude_if }pydantic-core/src/serializers/type_serializers/enum_.rs:51:EnumSerializer { class, serializer }pydantic-core/src/validators/enum_.rs:171, 203, 219, 235:{ class, lookup, missing }
The extension was rebuilt with make build-dev.
Tests added:
pydantic-core/tests/test_garbage_collection.py:test_gc_enum: 8 cases, covering validator and serializer for each of the four enum kinds.test_gc_serialization_exclude_if.- Both copy the existing tests in that file.
tests/test_main.py:test_model_with_enum_with_method_gets_cleaned_up: aBaseModelwith astrEnum field whose class has a method.test_model_with_field_exclude_if_gets_cleaned_up: aBaseModelfield withField(exclude_if=lambda ...).- Both assert the model classes are collected.
The new tests build the reference cycle explicitly: the enum method or the exclude_if callable points back at the model. The issue's script gets the same cycle through the module's globals.
Test results:
- Before the fix: all 11 new tests failed ("Timeout waiting for GC" in core,
assert Falseintest_main.py). The 3 existing GC tests passed. - After the fix:
- The core GC tests, the core enum validator tests and all core serializer tests: 835 passed, 6 skipped, 1 xfailed.
tests/test_main.py,tests/test_types.pyandtests/test_serialize.py: 627 passed, 29 skipped, 2 xfailed.- No failures in either run, and no existing test was changed.
cargo fmt and clippy aren't installed here, so neither was run; each edit is a one-line change to a macro's field list.
Requirements:
- Enum with methods leaks: fixed and covered by tests; the issue's script now reports the enum and its model as collected.
Field(exclude_if=...)leaks: fixed and covered by tests.- Controls (enum without methods, field without
exclude_if) are collected: confirmed by the test-writer's manual check before the fix, with 0 leaked. These aren't separate tests: they pass both before and after, so they wouldn't catch a regression. - Add
serialization_exclude_iftoSerField: done. - Add
classtoEnumSerializer: done. - Add
lookupto everyEnumValidator<T>: done, all four. - "Both enum edges are required": not tested separately. The combined fix is in and tested; the serializer cases need the
EnumSerializeredge and the validator cases need thelookupedge.
The reviewer found no problems. It noted one existing gap outside this fix: LiteralLookup's own traversal skips two of its internal fields that hold values. For enums those are the member values, and simple values like strings and ints can't form cycles, so the reported cases aren't affected. I left it alone to keep the change minimal.