Repository navigation
Description
Bug report
Bug description:
The segfault described here is related to PEP-667 and PEP-709.
I think I experienced a couple of similar but not same segfaults, and this here is just one of a few of them. I might be wrong though.
I'd like to start working on fixing this in order to possibly find more unhappy paths.
Reproduction
Here are a bunch of reproductions:
def f():
lambda: k
k: int
[k for k in [0] if locals()]
f()def f():
lambda: k
k = [sys._getframe(0).f_locals["k"] for k in [0]]
f()def f():
lambda: k
k = 1
[eval("") for k in [0]]
f()@alexmojaki also found
def f():
lambda: k
k = 1
[locals() for k in [0]]
f()def f():
lambda: k
k: int
[locals() for k in [0]]
f()This one shows the problem the best:
def fetch_locals_proxy():
# anything that fetches PEP 667 FrameLocalsProxy contents
# causes the crash
sys._getframe(1).f_locals.items()
def f():
lambda: k
k = 1
[fetch_locals_proxy() for k in [0]]
f()Traceback
Fatal Python error: Segmentation fault
Current thread 0x00007fd059596740 (most recent call first):
File "/tmp/repro/dump-1.py", line 9 in fetch_locals_proxy
File "/tmp/repro/dump-1.py", line 14 in f
File "/tmp/repro/dump-1.py", line 17 in <module>
Segmentation fault (core dumped)
Conclusions
-
There must be a statement that allows to create a closure for a variable, for instance
k, in a scope ("target scope"). It's eitherk = ...ork: intin the repros. -
There must be an inlined comprehension that binds
kas target (e.g.k = 1; [x for x in [0] if locals()]doesn't cause segfault). -
After binding the variable during the evaluation of the inlined comprehension, something must fetch the contents of the PEP 667 proxy of the target scope.
-
The target scope must be any optimized scope (not confirmed for generator expressions), since only those involve PEP 667
FrameLocalsProxy. That's the reason why the crash doesn't happen at a module/class level:class Spam: lambda: k k = [k for k in [0] if locals()]
or on Python <3.13, before PEP 667 had been introduced.
-
The iterable traversed in the comprehension isn't special (the crash doesn't happen for certain objects, e.g.
[None]1,(...,), but happens for others, e.g.[0],range(1)). Not confirmed for every platform.
Thanks @Eclips4 for hints to finding the best reproduction. Thanks @trag1c for reporting the problem after accidentally running into it in a real-life use case.
I'm delighted to accept any help or guidance (cc @JelleZijlstra @carljm), as I want to author the patch to fix this issue and learn something in the process. Thanks!
CPython versions tested on:
3.13, 3.14, CPython main branch
Operating systems tested on:
Linux
Linked PRs
- gh-128396: Fix a crash when inline comprehension has the same local variable as the outside scope #130235
- [3.13] gh-128396: Fix a crash when inline comprehension has the same … #130311
Activity
ZeroIntensity commentedon Jan 1, 2025
On a debug build, an assertion fails for all three reproducers:
[-]PEP 667 + PEP 709 segfault of access to local variables in a closure variable with an inlined comprehension shadowing itself[/-][+]PEP 667 + PEP 709 segfaults from accessing closure variables bound by any inlined comprehensions[/+]ZeroIntensity commentedon Jan 8, 2025
@bswck Need any help here?
carljm commentedon Jan 8, 2025
I'm very short on time at the moment, but @bswck if you have specific questions that you run into when looking into this, I'm happy to help try to answer them. (You can contact me on Discord or here.)
johnslavik commentedon Feb 13, 2025
To reach the root cause, I started working on this by disabling assertions but keeping debug symbols and no optimizations:
./configure --with-{pydebug,trace-refs} CFLAGS="-DNDEBUG -O0 -g3" --prefix=/home/bswck/.local.I'm posting this as these are my beginnings in C and I'm open to improvements of my workflow.
johnslavik commentedon Feb 13, 2025
The segfault happens at
refcount.h:275:17, in an#elifafter#if defined(Py_GIL_DISABLED):cpython/Include/refcount.h
Lines 274 to 276 in c357d69
So if I'm guessing correctly, there is a probability it won't happen in free-threaded builds?
ZeroIntensity commentedon Feb 13, 2025
I doubt it. In general, crashes from macros and common operations (i.e.,
Py_INCREFin this case) are generally incidental, and not the actual cause of the crash. Here, an object is invalid, and that only shows up when something tries to increment its reference count.johnslavik commentedon Feb 13, 2025
Indeed! After running in the free-threaded build, the segfault also happens but in
pyatomic_gcc.h:367:10.cpython/Include/cpython/pyatomic_gcc.h
Lines 365 to 368 in c357d69
gaogaotiantian commentedon Feb 16, 2025
I can take a look at it. I'm familiar with both PEPs (seems like the assertion failure was written by me :)).
johnslavik commentedon Feb 16, 2025
@gaogaotiantian Hey! Thanks. I'd really like to give it a shot myself. If I can't find the fix, I'd at least like to be walked through your investigation. I can share my progress so far. Do you have Discord?
gaogaotiantian commentedon Feb 16, 2025
@bswck sure feel free to investigate it. I only offered help because it's been more than a month and it's a segfault. You don't have to share your progress with me. I have not looked into it yet. I'll leave it to you and if you can't figure it out in some time I can take it over. This is a crashing bug in a released version. I'd suggest investigating from the assertion failure.
johnslavik commentedon Feb 16, 2025
@gaogaotiantian Hey, I took some time to poke around, also talked with Carl, and decided to hand it over, given the urgency. Can't wait to see the fix and learn from that. :)
gaogaotiantian commentedon Feb 17, 2025
@bswck sure. I'll take it over. I don't know the exact reason yet but if I can figure it out, it would be in my PR :)
johnslavik commentedon Feb 17, 2025
@gaogaotiantian (This won't be technically precise)
For
My thinking is that some code responsible for setting
existingin the local namespace in the inlined comprehension offis reaching a code path specialized for cases where a cell for a name is reserved in the local scope. I found such a distinction incpython/Python/symtable.c
Lines 845 to 878 in e7f00cd
And that code path, to my mind, overwrites that name with a value instead of populating the cell; an effect that you can see here:
This won't segfault, and it makes sense when you see the assertion.
gaogaotiantian commentedon Feb 17, 2025
I tried to explain what happend in #130235 - let me know if that's not clear. A fix is also provided in that PR (which is actually pretty trivial).
gh-128396: Fix a crash when inline comprehension has the same local v…
[3.13] pythongh-128396: Fix a crash when inline comprehension has the…
[3.13] gh-128396: Fix a crash when inline comprehension has the same … (
picnixz commentedon Feb 22, 2025
@gaogaotiantian Nothing left to be done?
gaogaotiantian commentedon Feb 22, 2025
Well we solved the segfault, but the fundamental issue is still there. We can either keep this one or create a new issue for it.
ncoghlan commentedon Feb 23, 2025
@gaogaotiantian I think the PEP 709 "cells stored in iteration variables that shadow cell variables get resolved when reporting
locals()" issue should be a separate issue, since it's entirely unrelated to the segfault reported here.The experiment that convinced me of that (the example intentionally avoids creating cells explicitly, since even in the already rare case where folks are manipulating cells directly in the first place, it's still far more common to let the compiler create them, and then grab them from the relevant function closure):
3.11 (without inline comprehensions) correctly reports the cell instance during iteration:
3.12 (with inline comprehensions) introduced the incorrect cell resolution:
3.13 added the incorrect assertion that cell variables wouldn't be overridden by the iteration variable:
Finally, the bug fix gets us back to the same state as we had in 3.12 (so the PEP 667 segfault is resolved, but the incorrect cell dereferencing from PEP 709 is still present):
I don't have any good ideas on how we can reasonably distinguish the actual cell from a cell that happens to have been stored in the same position in the fast locals array by an inline comprehension (if it was easy, PEP 709 would have avoided the problem!), I just don't think it's in scope for the bug the OP reported here.
gaogaotiantian commentedon Feb 23, 2025
Yeah that makes sense. We can close this issue for now and solve the rest later.