Skip to content

Instantly share code, notes, and snippets.

@devdanzin
Last active June 20, 2026 01:08
Show Gist options
  • Select an option

  • Save devdanzin/3c6690d0561acc62752a953e12b20197 to your computer and use it in GitHub Desktop.

Select an option

Save devdanzin/3c6690d0561acc62752a953e12b20197 to your computer and use it in GitHub Desktop.
OOM-0008: Abort: `assert(!PyErr_Occurred())` in `_PyType_LookupStackRefAndVersion` (`typeobject.c:6343`)
# Authoritative backtrace, free-threaded debug+ASan build
# (~/projects/3.16_ft_debug_asan_cpython/python), commit 15d7406
# Original vehicle: ~/crashers/python-4/gettext-assertion/source.py
python: Objects/typeobject.c:6343: unsigned int _PyType_LookupStackRefAndVersion(PyTypeObject *, PyObject *, _PyStackRef *): Assertion `!PyErr_Occurred()' failed.
Program received signal SIGABRT, Aborted.
#0 __pthread_kill_implementation () at ./nptl/pthread_kill.c:44
#1 __pthread_kill_internal () at ./nptl/pthread_kill.c:89
#2 __GI___pthread_kill () at ./nptl/pthread_kill.c:100
#3 __GI_raise (sig=...) at ../sysdeps/posix/raise.c:26
#4 __GI_abort () at ./stdlib/abort.c:77
#5 __libc_message_impl () at ../sysdeps/posix/libc_fatal.c:138
#6 __libc_message_wrapper () at ../include/stdio.h:203
#7 __assert_fail () at ./assert/assert.c:37
#8 _PyType_LookupStackRefAndVersion (type=..., name=..., out=...) at Objects/typeobject.c:6343 <- assert !PyErr_Occurred()
#9 _PyObject_GenericGetAttrWithDict (obj=..., name=..., dict=..., suppress=...) at Objects/object.c:1919
#10 _PyObject_GetAttrStackRef (v=..., name=...) at Objects/object.c:1369
#11 _PyEval_EvalFrameDefault (tstate=..., frame=..., throwflag=...) at Python/generated_cases.c.h:8786 (LOAD_ATTR)
#12 _PyEval_EvalFrame (tstate=..., frame=..., throwflag=...) at ./Include/internal/pycore_ceval.h:122
#13 _PyEval_Vector (tstate=..., func=..., locals=..., args=..., argcount=..., kwnames=...) at Python/ceval.c:2141
#14 PyEval_EvalCode (co=..., globals=..., locals=...) at Python/ceval.c:679
# Python stack (faulthandler) for the original gettext vehicle:
# File ".../Lib/gettext.py", line 190 in _as_int2 (n.__class__.__name__ after an f.f_back walk)
# File ".../Lib/gettext.py", line 620 in dnpgettext
# Minimal reproducer (repro.py) produces the identical C site via:
# #10 _Py_module_getattro_impl Objects/moduleobject.c:1334 (sys.maxsize LOAD_ATTR)
# #9 _PyObject_GenericGetAttrWithDict Objects/object.c:1919
# #8 _PyType_LookupStackRefAndVersion Objects/typeobject.c:6343 (assert !PyErr_Occurred())

Abort: assert(!PyErr_Occurred()) in _PyType_LookupStackRefAndVersion (typeobject.c:6343)

Under OOM, frame.f_back's lazy parent-frame allocation fails and sets MemoryError, but PyFrame_GetBack returns NULL and frame_back_get_impl reports it as None, leaving the exception pending; the next LOAD_ATTR then trips assert(!PyErr_Occurred()).

AI Disclaimer: this gist was drafted by Claude Code, which also generated the reduced reproducer.

Crash report

Reading frame.f_back lazily materializes the parent PyFrameObject. Under OOM that allocation fails and sets MemoryError, but PyFrame_GetBack() does not check for it: it returns NULL, and frame_back_get_impl() interprets NULL as "no parent frame" and returns None successfully -- swallowing the pending exception. The LOAD_ATTR opcode therefore completes "successfully" with a MemoryError still set, and the next attribute lookup enters _PyType_LookupStackRefAndVersion, which asserts !PyErr_Occurred() and aborts. On release builds (assert compiled out) the dangling exception surfaces later as a spurious SystemError: ... returned a result with an exception set.

Reproducer

import sys, _testcapi, faulthandler
faulthandler.enable()
def walk():
    f = sys._getframe()
    while f is not None:
        f = f.f_back          # under OOM, materializing the parent frame fails:
                              # MemoryError is set but f.f_back returns None
_testcapi.set_nomemory(1, 0)  # fail every allocation from #1
try:
    try:
        walk()                # returns with a pending MemoryError after yielding None
        x = sys.maxsize       # next LOAD_ATTR -> _PyType_LookupStackRefAndVersion
                              # -> assert(!PyErr_Occurred()) fails -> SIGABRT
    finally:
        _testcapi.remove_mem_hooks()
except MemoryError:
    pass

Deterministic at start=1 on the free-threaded debug+ASan build (and on the JIT debug build). The frame-walk just guarantees at least one f.f_back access whose lazy PyFrameObject allocation fails; the trailing sys.maxsize is any subsequent LOAD_ATTR that then trips the assert.

Backtrace

#8  _PyType_LookupStackRefAndVersion   Objects/typeobject.c:6343   <- assert !PyErr_Occurred()
#9  _PyObject_GenericGetAttrWithDict    Objects/object.c:1919
#10 _PyObject_GetAttrStackRef           Objects/object.c:1369
#11 _PyEval_EvalFrameDefault            Python/generated_cases.c.h:8786   (LOAD_ATTR)
#12 _PyEval_Vector                      Python/ceval.c:2141
#13 PyEval_EvalCode                     Python/ceval.c:679

The faulting object is valid; the invariant violated is "no live exception on entry to a type lookup". (gdb) p (int)PyErr_Occurred() at frame 8 is nonzero (a MemoryError set during the previous frame.f_back).

Root cause

Objects/frameobject.c, PyFrame_GetBack() (L2395):

PyFrameObject*
PyFrame_GetBack(PyFrameObject *frame)
{
    PyFrameObject *back = frame->f_back;
    if (back == NULL) {
        _PyInterpreterFrame *prev = frame->f_frame->previous;
        prev = _PyFrame_GetFirstComplete(prev);
        if (prev) {
            back = _PyFrame_GetFrameObject(prev);   /* L2404: may fail + set MemoryError, returns NULL */
        }
    }
    return (PyFrameObject*)Py_XNewRef(back);          /* L2407: returns NULL, error NOT cleared/propagated */
}

_PyFrame_GetFrameObject() (Include/internal/pycore_interpframe.h:340) lazily creates the PyFrameObject via _PyFrame_MakeAndSetFrameObject(), whose PyObject_GC_New fails under OOM and returns NULL with MemoryError set. PyFrame_GetBack does not distinguish "no parent frame" (back == NULL, no error) from "allocation failed" (back == NULL, error set). The getter frame_back_get_impl() (Objects/frameobject.c:1116) then does:

    PyObject *res = (PyObject *)PyFrame_GetBack(self);
    if (res == NULL) {
        Py_RETURN_NONE;          /* L1118: treats the OOM failure as "top frame" -> None */
    }

So frame.f_back evaluates to None while a MemoryError is left pending. The LOAD_ATTR reports success; the next type lookup hits assert(!PyErr_Occurred()) (typeobject.c:6343). The defect is a swallowed/unpropagated exception, not a bad pointer.

Suggested fix

Propagate the allocation failure instead of masking it. In PyFrame_GetBack(), distinguish the error case:

        if (prev) {
            back = _PyFrame_GetFrameObject(prev);
            if (back == NULL) {
                return NULL;     /* MemoryError already set; let it propagate */
            }
        }

and in frame_back_get_impl() only convert a clean NULL to None:

    PyObject *res = (PyObject *)PyFrame_GetBack(self);
    if (res == NULL && !PyErr_Occurred()) {
        Py_RETURN_NONE;
    }
    return res;                  /* NULL with error set -> propagate */

This turns the OOM into a normal MemoryError raised from the f.f_back access, which the eval loop handles correctly.

Notes

Found by OOM-injection fuzzing (set_nomemory). The C defect is build-agnostic, but the symptom differs by build:

  • ft_debug_asan: abort at the assert(!PyErr_Occurred()) (typeobject.c:6343).
  • jit (debug, assertions on): identical abort at the same assertion.
  • ft_release / upstream (-DNDEBUG, assert compiled out): no abort; the swallowed MemoryError instead surfaces later as SystemError: <built-in function ...> returned a result with an exception set (a dangling-exception symptom). Per the OOM-catalog convention for assert-based aborts, these are recorded as n/a.

The 16 fuzzer vehicles all abort at the identical typeobject.c:6343 assertion but via diverse stdlib stack-walkers that read frame.f_back: gettext._as_int2 (warning stacklevel walk), logging.findCaller, asyncio.format_helpers.extract_stack / traceback.walk_stack, argparse, optparse, and concurrent.futures. Each merely walks frames (for a warning or traceback) while a MemoryError is injected, so any subsequent LOAD_ATTR trips the assert. The same swallow-on-OOM pattern likely affects other lazy frame getters (f_globals/f_locals raise cleanly here, but f_back does not).

Versions

  • main (3.16.0a0, commit 15d7406); aborts on the free-threaded debug+ASan build and the JIT debug build. Release/upstream builds: assertion compiled out (n/a); the bug instead leaks a MemoryError into an unrelated SystemError.

Part of python/cpython#151763 — an umbrella tracking 35 OOM-related crash findings.

"""
Minimal reproducer: abort on assert(!PyErr_Occurred()) in
_PyType_LookupStackRefAndVersion() (Objects/typeobject.c:6343) when reading
frame.f_back under OOM swallows a MemoryError.
Affected: CPython 3.16.0a0 (main). The assert is compiled in on DEBUG builds
(ft_debug_asan, jit); release builds define NDEBUG so the assert is a
no-op -- there the swallowed MemoryError instead surfaces later as a
spurious "SystemError: ... returned a result with an exception set".
Crash: SIGABRT, Objects/typeobject.c:6343
Assertion `!PyErr_Occurred()' failed.
Requires: a debug build exposing _testcapi.set_nomemory.
Backtrace (gdb):
#8 _PyType_LookupStackRefAndVersion Objects/typeobject.c:6343 (assert !PyErr_Occurred())
#9 _PyObject_GenericGetAttrWithDict Objects/object.c:1919
#10 _PyObject_GetAttrStackRef Objects/object.c:1369
#11 _PyEval_EvalFrameDefault Python/generated_cases.c.h:8786 (LOAD_ATTR)
Root cause (Objects/frameobject.c):
PyFrame_GetBack() (L2395) lazily materializes the parent PyFrameObject:
back = _PyFrame_GetFrameObject(prev); // L2404
...
return (PyFrameObject*)Py_XNewRef(back); // L2407
_PyFrame_GetFrameObject -> _PyFrame_MakeAndSetFrameObject allocates a new
PyFrameObject; under OOM that PyObject_GC_New fails and returns NULL with
MemoryError set. PyFrame_GetBack does NOT check for the error: it returns
NULL, and frame_back_get_impl() (L1116) treats NULL as "no parent frame":
if (res == NULL) {
Py_RETURN_NONE; // L1118: swallows the pending MemoryError
}
So `frame.f_back` evaluates to None while a MemoryError is still set. The
LOAD_ATTR opcode reports success; the *next* LOAD_ATTR enters
_PyType_LookupStackRefAndVersion, which asserts !PyErr_Occurred() and aborts.
The walk() below just guarantees at least one f.f_back access whose lazy frame
allocation fails under OOM; the trailing `sys.maxsize` is any subsequent
LOAD_ATTR that then trips the assert. Deterministic at start=1.
Likely fix: in PyFrame_GetBack, `return NULL;` (propagating the error) when
_PyFrame_GetFrameObject fails; in frame_back_get_impl, only convert a clean
NULL (no pending error) to None.
Original fuzzer vehicle: ~/crashers/python-4/gettext-assertion (gettext._as_int2
walked frames via f.f_back to compute a DeprecationWarning stacklevel under OOM).
Self-sweeping: `python repro.py` runs the trigger under set_nomemory(N, 0) for N in a
sweep, each in a FRESH subprocess (a fresh process avoids cache warm-up shifting the OOM
window), and stops at the first N that crashes. Needs a debug build (the check is compiled
out under NDEBUG). Bare trigger (fixed N=1):
import sys, _testcapi
def walk():
f = sys._getframe()
while f is not None:
f = f.f_back
_testcapi.set_nomemory(1, 0)
walk()
x = sys.maxsize # next LOAD_ATTR trips assert(!PyErr_Occurred())
"""
import os
import sys
import subprocess
TRIGGER = r"""
import sys
import _testcapi
import faulthandler
faulthandler.enable()
def walk():
f = sys._getframe()
while f is not None:
f = f.f_back # under OOM, materializing the parent frame fails:
# MemoryError is set but f.f_back returns None
_testcapi.set_nomemory({n}, 0) # fail every allocation from #{n} onward
try:
try:
walk() # returns with a pending MemoryError after yielding None
x = sys.maxsize # next LOAD_ATTR -> _PyType_LookupStackRefAndVersion
# -> assert(!PyErr_Occurred()) fails -> SIGABRT
finally:
_testcapi.remove_mem_hooks()
except MemoryError:
pass
"""
SIGNATURE = "Assertion `!PyErr_Occurred()' failed."
def main():
env = {**os.environ, "ASAN_OPTIONS": "detect_leaks=0:abort_on_error=0"}
# env["PYTHON_GIL"] = "0" # ONLY if this bug is free-threading-only
for n in range(80):
out = subprocess.run([sys.executable, "-c", TRIGGER.format(n=n)],
capture_output=True, text=True, env=env)
if SIGNATURE in out.stdout + out.stderr:
print("reproduced at set_nomemory(%d, 0):" % n)
sys.stdout.write(out.stderr or out.stdout)
return 1
print("no crash in range(80); widen it for your build")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment