python / python/cpython

sum() deallocates float subclass instances as exact floats in the complex fast path

Open
#150,868 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

interpreter-core type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

Bug report

Description

In builtin_sum_impl() (Python/bltinmodule.c), the complex-number fast
path tests items with PyFloat_Check() but releases them with
_Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc).

PyFloat_Check() also matches subclasses of float, whereas
_PyFloat_ExactDealloc is only valid for exact float objects. When a
float subclass instance reaches refcount 0 through this path, it is
deallocated as an exact float, bypassing its real tp_dealloc
(instance __dict__, weakref list, and GC bookkeeping). This can leak
memory and leave the cyclic GC in an inconsistent state.

The adjacent float fast path in the same function already guards the
identical specialized dealloc with PyFloat_CheckExact(); only the
complex branch uses the broader PyFloat_Check().

Reproducer

class F(float):
    pass

# complex start value selects the complex fast path
sum([F(1.0), F(2.0)], 0j)

Proposed fix

In the complex branch, use PyFloat_CheckExact(item) instead of
PyFloat_Check(item), so subclass instances fall through to the generic
PyNumber_Add path with a normal Py_DECREF. Numeric behavior is
unchanged.

Environment

  • CPython: main branch (please confirm the line is still present)
CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-150869
  • gh-151063

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in Python/bltinmodule.c at builtin_sum_impl() and compare the complex fast path with the adjacent float fast path. Verify the specialized deallocation check for float subclasses and confirm that the reproducer completes without the subclass being deallocated incorrectly; linked PRs gh-150869 and gh-151063 indicate work may already be underway.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.