Skip to content

gh-163183: Fix crash in itertools.groupby when __eq__ consumes the current key - #163211

Open
abedalawieh wants to merge 1 commit into
python:mainfrom
abedalawieh:gh-163183-groupby-reentrant-currkey
Open

abedalawieh wants to merge 1 commit into
python:mainfrom
abedalawieh:gh-163183-groupby-reentrant-currkey

Conversation

@abedalawieh

Copy link
Copy Markdown

When a key's __eq__ re-enters groupby during the comparison in groupby_next() and advances the new group (next(g) and then next(grouper)), _grouper_next() clears gbo->currkey. If __eq__ then returns false, the loop breaks and Py_INCREF(gbo->currkey) dereferences NULL.

The fix:

  • If the comparison is false but gbo->currkey was cleared, the loop goes on to groupby_step() to fetch the next key, the same as it does at the top of the loop when currkey is NULL.
  • After the loop, the new key is held in a local strong reference and used for tgtkey, the grouper and the returned tuple. Releasing the old tgtkey can run arbitrary code (__del__) that could clear currkey again.

The new test in test_itertools segfaults under ASan without the fix. The reproducer from the issue now ends in StopIteration without crashing. test_itertools and test_functools pass on a --with-pydebug --with-address-sanitizer build.

The same code is on 3.14 and 3.15, so this probably needs backports there.

@python-cla-bot

python-cla-bot Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

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.

1 participant