Skip to content

gh-149557: Make itertools.pairwise safe under re-entry and concurrency #150589

Open
eendebakpt wants to merge 1 commit into
python:mainfrom
eendebakpt:pairwise-reentry-guard
Open

gh-149557: Make itertools.pairwise safe under re-entry and concurrency #150589
eendebakpt wants to merge 1 commit into
python:mainfrom
eendebakpt:pairwise-reentry-guard

Conversation

@eendebakpt
Copy link
Copy Markdown
Contributor

@eendebakpt eendebakpt commented May 29, 2026

  • Add a re-entrancy guard so a same-thread re-entrant call (e.g. when the input iterator's __next__ calls back into pairwise.__next__) raises RuntimeError instead of crashing or producing garbled output. Matches the behavior of itertools.tee and of generators, and fixes the use-after-free crash reported in Single-threaded re-entrancy via a recursive generator causes an access violation (segfault) in pairwise_next #149557. (instead of raising RuntimeError we could consider raising ValueError)
  • Wrap pairwise.__next__ in a critical section so concurrent callers from different threads serialize cleanly in the free-threaded build.

Also addresses #123471

…concurrency and re-entry

Wrap pairwise.__next__ in a critical section so concurrent callers from
different threads serialize cleanly in the free-threaded build, and add
a re-entrancy guard so a same-thread re-entrant call (e.g. when the
input iterator's __next__ calls back into pairwise.__next__) raises
RuntimeError instead of crashing or producing garbled output. Matches
the long-standing behavior of itertools.tee and of generators, and
fixes the use-after-free crash reported in pythongh-149557.

With re-entry blocked, po->old is safe as a borrowed reference for the
duration of __next__, so the defensive incref/decref and re-read guard
added by pythongh-109788 are no longer needed and have been removed.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@eendebakpt eendebakpt requested a review from rhettinger as a code owner May 29, 2026 19:35
@eendebakpt eendebakpt changed the title gh-149557, gh-123471: Make itertools.pairwise safe under re-entry and concurrency gh-149557: Make itertools.pairwise safe under re-entry and concurrency May 29, 2026
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