Skip to content

Reference leak in is_namedtuple_class when _fields is not exactly a tuple #1376

Done

Description

@shashank11yadav

Description

Building a decoder for a tuple subclass whose _fields attribute is not exactly a tuple leaks one reference to that _fields object per build. In is_namedtuple_class (src/msgspec/_core.c), the early return false after if (!PyTuple_CheckExact(fields)) skips the Py_DECREF(fields) that the other paths perform. The check was added in 76d4402 (#1259). Release 0.22.0 does not show the leak, so this is only on main.

Reproducer:

import sys
import msgspec

N = 2000


class C(tuple):
    _fields = ["a"]


fields = C._fields
base = sys.getrefcount(fields)

for _ in range(N):
    try:
        msgspec.json.Decoder(C)
    except Exception:
        pass

after = sys.getrefcount(fields)
growth = after - base
print("msgspec", msgspec.__version__)
print(f"refcount before={base} after={after} growth={growth} over {N} builds")
print("EXPECTED: growth == 0")
print(f"ACTUAL: growth == {growth}")
sys.exit(1 if growth >= N // 2 else 0)

Output on main (39a0859):

msgspec 0.22.1.dev85+g39a085961
refcount before=3 after=2003 growth=2000 over 2000 builds
EXPECTED: growth == 0
ACTUAL: growth == 2000

Expected: the refcount of _fields does not grow. There is no exception or traceback; the exception from the Decoder call is caught in the script. With msgspec 0.22.0 the same script prints growth == 0.

Versions

  • msgspec main @ 39a0859 (0.22.1.dev85)
  • Python 3.12, Linux

Additional context

The fix is to Py_DECREF(fields) before that early return (src/msgspec/_core.c:5171).

I have a fix with a regression test ready and will open a pull request for it right after filing this issue; it will link back here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions