Skip to content

PEP 667 + PEP 709 segfaults from accessing closure variables bound by any inlined comprehensions #128396

Closed

Description

@johnslavik

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

  1. There must be a statement that allows to create a closure for a variable, for instance k, in a scope ("target scope"). It's either k = ... or k: int in the repros.

  2. There must be an inlined comprehension that binds k as target (e.g. k = 1; [x for x in [0] if locals()] doesn't cause segfault).

  3. 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.

  4. 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.

  5. 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

Footnotes

  1. Const lists (from displays) are compiled into tuples under the hood before the loop begins, so [None] here is equivalent to (None,). ↩

Activity

  1. added
    type-bug
    on Jan 1, 2025
  2. added
    type-crash
    3.13
    3.14
    on Jan 1, 2025
  3. added
    interpreter-core
    on Jan 1, 2025
  4. ZeroIntensity commented on Jan 1, 2025

    @ZeroIntensity
    Member

    On a debug build, an assertion fails for all three reproducers:

    python: Objects/frameobject.c:40: framelocalsproxy_getval: Assertion `PyCell_Check(value)' failed.
    
  5. changed the title [-]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[/+] on Jan 2, 2025
  6. ZeroIntensity commented on Jan 8, 2025

    @ZeroIntensity
    Member

    @bswck Need any help here?

  7. carljm commented on Jan 8, 2025

    @carljm
    Member

    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.)

  8. johnslavik commented on Feb 13, 2025

    @johnslavik
    MemberAuthor

    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.

  9. johnslavik commented on Feb 13, 2025

    @johnslavik
    MemberAuthor

    The segfault happens at refcount.h:275:17, in an #elif after #if defined(Py_GIL_DISABLED):

    cpython/Include/refcount.h

    Lines 274 to 276 in c357d69

    #elif SIZEOF_VOID_P > 4
    PY_UINT32_T cur_refcnt = op->ob_refcnt;
    if (((int32_t)cur_refcnt) < 0) {

    So if I'm guessing correctly, there is a probability it won't happen in free-threaded builds?

  10. ZeroIntensity commented on Feb 13, 2025

    @ZeroIntensity
    Member

    I doubt it. In general, crashes from macros and common operations (i.e., Py_INCREF in 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.

  11. johnslavik commented on Feb 13, 2025

    @johnslavik
    MemberAuthor

    Indeed! After running in the free-threaded build, the segfault also happens but in pyatomic_gcc.h:367:10.

    static inline uint32_t
    _Py_atomic_load_uint32_relaxed(const uint32_t *obj)
    { return __atomic_load_n(obj, __ATOMIC_RELAXED); }

  12. gaogaotiantian commented on Feb 16, 2025

    @gaogaotiantian
    Member

    I can take a look at it. I'm familiar with both PEPs (seems like the assertion failure was written by me :)).

  13. johnslavik commented on Feb 16, 2025

    @johnslavik
    MemberAuthor

    @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?

  14. gaogaotiantian commented on Feb 16, 2025

    @gaogaotiantian
    Member

    @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.

  15. johnslavik commented on Feb 16, 2025

    @johnslavik
    MemberAuthor

    @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. :)

  16. gaogaotiantian commented on Feb 17, 2025

    @gaogaotiantian
    Member

    @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 :)

  17. johnslavik commented on Feb 17, 2025

    @johnslavik
    MemberAuthor

    @gaogaotiantian (This won't be technically precise)

    For

    def f():
        lambda: existing
        existing: object
        [locals() for existing in ["foobar"]]
    
    
    f()

    My thinking is that some code responsible for setting existing in the local namespace in the inlined comprehension of f is reaching a code path specialized for cases where a cell for a name is reserved in the local scope. I found such a distinction in

    cpython/Python/symtable.c

    Lines 845 to 878 in e7f00cd

    if (!existing) {
    // name does not exist in scope, copy from comprehension
    assert(scope != FREE || PySet_Contains(comp_free, k) == 1);
    PyObject *v_flags = PyLong_FromLong(only_flags);
    if (v_flags == NULL) {
    return 0;
    }
    int ok = PyDict_SetItem(ste->ste_symbols, k, v_flags);
    Py_DECREF(v_flags);
    if (ok < 0) {
    return 0;
    }
    SET_SCOPE(scopes, k, scope);
    }
    else {
    long flags = PyLong_AsLong(existing);
    if (flags == -1 && PyErr_Occurred()) {
    return 0;
    }
    if ((flags & DEF_BOUND) && ste->ste_type != ClassBlock) {
    // free vars in comprehension that are locals in outer scope can
    // now simply be locals, unless they are free in comp children,
    // or if the outer scope is a class block
    int ok = is_free_in_any_child(comp, k);
    if (ok < 0) {
    return 0;
    }
    if (!ok) {
    if (PySet_Discard(comp_free, k) < 0) {
    return 0;
    }
    }
    }
    }

    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:

    from types import CellType
    
    def f():
        lambda: existing
        existing: object
        [locals() for existing in [CellType()]]
    
    f()

    This won't segfault, and it makes sense when you see the assertion.

  18. gaogaotiantian commented on Feb 17, 2025

    @gaogaotiantian
    Member

    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).

  19. added 3 commits that reference this issue on Feb 19, 2025
  20. picnixz commented on Feb 22, 2025

    @picnixz
    Member

    @gaogaotiantian Nothing left to be done?

  21. gaogaotiantian commented on Feb 22, 2025

    @gaogaotiantian
    Member

    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.

  22. ncoghlan commented on Feb 23, 2025

    @ncoghlan
    Contributor

    @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):

    from pprint import pprint
    
    def f():
        def g():
            return x, y
        cell1 = g.__closure__[0]
        cell2 = g.__closure__[1]
        x, y = 1, 2
        del g
        pprint(locals())
        # In 3.12+, these erroneously resolve the cell stored
        # in the iteration variable due to inline comprehensions
        pprint([locals() for x in [cell2]])
        pprint([locals() for y in [cell1]])
        # These segfault in 3.13+ (prior to the bug fix)
        # After the bug fix, they work as expected, since the
        # iterating-over-cells-as-values issue doesn't apply
        pprint([locals() for x in ["not a cell"]])
        pprint([locals() for y in ["not a cell"]])
    
    f()

    3.11 (without inline comprehensions) correctly reports the cell instance during iteration:

    $ python3.11 inline_cell.py
    {'cell1': <cell at 0x7f4b69473520: int object at 0x7f4b776fc688>,
     'cell2': <cell at 0x7f4b69471d20: int object at 0x7f4b776fc6a8>,
     'x': 1,
     'y': 2}
    [{'.0': <tuple_iterator object at 0x7f4b69273580>,
      'x': <cell at 0x7f4b69471d20: int object at 0x7f4b776fc6a8>}]
    [{'.0': <tuple_iterator object at 0x7f4b69273580>,
      'y': <cell at 0x7f4b69473520: int object at 0x7f4b776fc688>}]
    [{'.0': <tuple_iterator object at 0x7f4b69273580>, 'x': 'not a cell'}]
    [{'.0': <tuple_iterator object at 0x7f4b69273580>, 'y': 'not a cell'}]

    3.12 (with inline comprehensions) introduced the incorrect cell resolution:

    $ python3.12 inline_cell.py
    {'cell1': <cell at 0x7fe06104fac0: int object at 0x7fe06f600c68>,
     'cell2': <cell at 0x7fe06104f970: int object at 0x7fe06f600c88>,
     'x': 1,
     'y': 2}
    [{'cell1': <cell at 0x7fe06104fac0: int object at 0x7fe06f600c68>,
      'cell2': <cell at 0x7fe06104f970: int object at 0x7fe06f600c88>,
      'x': 2,  # <- Should be cell2 itself, not cell2's value!
      'y': 2}]
    [{'cell1': <cell at 0x7fe06104fac0: int object at 0x7fe06f600c68>,
      'cell2': <cell at 0x7fe06104f970: int object at 0x7fe06f600c88>,
      'x': 1,  # <- Should be cell1 itself, not cell1's value!
      'y': 1}]
    [{'cell1': <cell at 0x7fe06104fac0: int object at 0x7fe06f600c68>,
      'cell2': <cell at 0x7fe06104f970: int object at 0x7fe06f600c88>,
      'x': 'not a cell',
      'y': 2}]
    [{'cell1': <cell at 0x7fe06104fac0: int object at 0x7fe06f600c68>,
      'cell2': <cell at 0x7fe06104f970: int object at 0x7fe06f600c88>,
      'x': 1,
      'y': 'not a cell'}]

    3.13 added the incorrect assertion that cell variables wouldn't be overridden by the iteration variable:

    $ python3.13 inline_cell.py
    {'cell1': <cell at 0x7f1d1ddd9810: int object at 0x7f1d2c25ddd0>,
     'cell2': <cell at 0x7f1d1ddd9a50: int object at 0x7f1d2c25ddf0>,
     'x': 1,
     'y': 2}
    [{'cell1': <cell at 0x7f1d1ddd9810: int object at 0x7f1d2c25ddd0>,
      'cell2': <cell at 0x7f1d1ddd9a50: int object at 0x7f1d2c25ddf0>,
      'x': 2,  # <- cell resolution bug is still present
      'y': 2}]
    [{'cell1': <cell at 0x7f1d1ddd9810: int object at 0x7f1d2c25ddd0>,
      'cell2': <cell at 0x7f1d1ddd9a50: int object at 0x7f1d2c25ddf0>,
      'x': 1,  # <- cell resolution bug is still present
      'y': 1}]
    Segmentation fault (core dumped)

    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):

    $ ../cpython/python inline_cell.py
    {'cell1': <cell at 0x7f046f9dffd0: int object at 0x911e18>,
     'cell2': <cell at 0x7f046fa213c0: int object at 0x911e38>,
     'x': 1,
     'y': 2}
    [{'cell1': <cell at 0x7f046f9dffd0: int object at 0x911e18>,
      'cell2': <cell at 0x7f046fa213c0: int object at 0x911e38>,
      'x': 2,  # <- cell resolution bug is still present
      'y': 2}]
    [{'cell1': <cell at 0x7f046f9dffd0: int object at 0x911e18>,
      'cell2': <cell at 0x7f046fa213c0: int object at 0x911e38>,
      'x': 1,  # <- cell resolution bug is still present
      'y': 1}]
    [{'cell1': <cell at 0x7f046f9dffd0: int object at 0x911e18>,
      'cell2': <cell at 0x7f046fa213c0: int object at 0x911e38>,
      'x': 'not a cell',
      'y': 2}]
    [{'cell1': <cell at 0x7f046f9dffd0: int object at 0x911e18>,
      'cell2': <cell at 0x7f046fa213c0: int object at 0x911e38>,
      'x': 1,
      'y': 'not a cell'}]

    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.

  23. gaogaotiantian commented on Feb 23, 2025

    @gaogaotiantian
    Member

    Yeah that makes sense. We can close this issue for now and solve the rest later.

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

Metadata

Metadata

Assignees

Labels

3.133.14interpreter-coretype-bugtype-crash

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions