Skip to content

gh-157176: Fix GC tracking in PyStructSequence_New - #157179

Open
ashm-dev wants to merge 2 commits into
python:mainfrom
ashm-dev:gh-157176
Open

gh-157176: Fix GC tracking in PyStructSequence_New#157179
ashm-dev wants to merge 2 commits into
python:mainfrom
ashm-dev:gh-157176

Conversation

@ashm-dev

@ashm-dev ashm-dev commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

@ashm-dev

ashm-dev commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

@sergey-miryanov, could you please review this PR?

Comment thread Objects/structseq.c
for (i = 0; i < size; i++)
obj->ob_item[i] = NULL;

_PyObject_GC_TRACK(obj);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks safe, but we usually try to avoid exposing partially constructed objects to the GC. I'm not sure I get why this change fixes your repro. Could you explain a bit?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Why it fixes the repro: time.gmtime() is not tracked by the GC. Because of that, the GC cannot see the cycle type(t) -> t -> type(t), so the entire heap type leaks at shutdown. Tracking t lets GC traverse t -> Py_TYPE(t) and collect the cycle.

  • Partially constructed object: All items are pre-initialized to NULL. Both structseq_traverse (Py_VISIT) and structseq_dealloc (Py_XDECREF) safely ignore NULL. This follows PyTuple_New(), which also tracks the object with NULL items since C API callers have no separate "finish" step.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, this change affects all call sites where PyStructSequence_New is called without a subsequent call to _PyObject_GC_TRACK. But at first glance, many of them don't seem to need tracking for PyStructSequence_New instances.

@vstinner Do we need frozen version of PyStructSequence?

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants