python / python/cpython

GC: Implementation does not match behavior documented on `gc.set_threshold`

Open
#122,862 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

The documentation of gc.set_threshold states:

In order to decide when to run, the collector keeps track of the number object allocations and deallocations since the last collection. When the number of allocations minus the number of deallocations exceeds threshold0, collection starts

This doesn't seem to be accurate. Looking at the implementation, it appears that young.count is being used to track number of allocations minus the number of deallocations. However it doesn't actually track this due to the if (gcstate->young.count > 0) check here: https://github.com/python/cpython/blob/3.13/Python/gc.c#L2119.

As a concrete example, suppose threshold0=500. Suppose the GC runs and young.count is reset to 0, then 500 deallocations happen (by object ref counts dropping to 0), then 500 allocations happen. According to the documentation the GC would not run in this case, because the difference between allocations and deallocations is 0. However the actual tracked number in young.count will be 500, and GC will trigger.

I'm unsure which is the expected behavior; the documented one or the implemented one, but it does appear that the two do not currently agree.

CPython versions tested on:

3.13

Operating systems tested on:

macOS

Linked PRs
  • gh-156877

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 with the documented behavior of gc.set_threshold and the young.count handling in Python/gc.c around line 2119. Compare the reported allocation and deallocation scenario with the implementation, then review linked PR gh-156877; done means the implementation and documentation agree on the intended threshold behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.