Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GH-38626: [Python] Fix segfault when PyArrow is imported at shutdown #38637

Merged
merged 1 commit into from
Nov 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions python/pyarrow/src/arrow/python/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,12 @@ class ARROW_PYTHON_EXPORT OwnedRef {
return *this;
}

~OwnedRef() { reset(); }
~OwnedRef() {
// GH-38626: destructor may be called after the Python interpreter is finalized.
if (Py_IsInitialized()) {
reset();
}
}

void reset(PyObject* obj) {
Py_XDECREF(obj_);
Expand Down Expand Up @@ -225,13 +230,11 @@ class ARROW_PYTHON_EXPORT OwnedRefNoGIL : public OwnedRef {
explicit OwnedRefNoGIL(PyObject* obj) : OwnedRef(obj) {}

~OwnedRefNoGIL() {
// This destructor may be called after the Python interpreter is finalized.
// At least avoid spurious attempts to take the GIL when not necessary.
if (obj() == NULLPTR) {
return;
// GH-38626: destructor may be called after the Python interpreter is finalized.
if (Py_IsInitialized() && obj() != NULLPTR) {
PyAcquireGIL lock;
reset();
}
PyAcquireGIL lock;
reset();
}
};

Expand Down
13 changes: 13 additions & 0 deletions python/pyarrow/tests/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,19 @@ def test_runtime_info():
subprocess.check_call([sys.executable, "-c", code], env=env)


def test_import_at_shutdown():
# GH-38626: importing PyArrow at interpreter shutdown would crash
code = """if 1:
import atexit

def import_arrow():
import pyarrow

atexit.register(import_arrow)
"""
subprocess.check_call([sys.executable, "-c", code])


@pytest.mark.skipif(sys.platform == "win32",
reason="Path to timezone database is not configurable "
"on non-Windows platforms")
Expand Down