fix(serializer): avoid creating reference cycles on every call#6563
Merged
alexander-alderman-webb merged 1 commit intoJun 12, 2026
Merged
Conversation
alexander-alderman-webb
approved these changes
Jun 12, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
serialize()used to define eight nested functions referencing each other through closure cells, so every call left a reference cycle behind. Only the cyclic GC can free such cycles, so applications running withgc.disable()leak memory on every captured event, and everyone else pays collector pressure on the error path. On Python 3.14 the cycle is even bigger: PEP 649 adds a hidden__annotate__function per nested function, and those get caught in it too.As discussed in #6559: the helpers are moved as-is onto a private per-call class
_Serializer, andserialize()creates an instance of it. The publicserialize()and its signature are unchanged, the helper logic is untouched, so behaviour stays identical. Everything a call creates is now freed by plain reference counting.There is no performance cost. In an interleaved microbenchmark (medians of 9 rounds, small/medium/frame-vars sample events) the class version performs the same as the nested functions on Python 3.12. On Python 3.14 small events serialize ~1.5x faster (9.0 -> 5.7 us/call here), since a call no longer creates eight closures plus their PEP 649
__annotate__functions.Also adds a regression test asserting that
serialize()leaves no cyclic garbage behind (checked undergc.DEBUG_SAVEALLwith the GC disabled).Issues
serializer.serialize()creates reference cycles on every call #6559