Skip to content

[Python] Interpreter hangs at exit after pq.read_table(python_file_object) - thread pool teardown deadlock #50482

Open

Description

@imanhabib

Describe the bug, including details regarding any error messages, version, and platform.

Describe the bug, including details regarding any error messages, version, and platform.

Reading a parquet file by passing a Python file object to pyarrow.parquet.read_table
makes the interpreter hang forever at shutdown on my and other similar machines:

# repro.py - hangs at exit, every run
import pyarrow.parquet as pq

with open("any.parquet", "rb") as f:
    pq.read_table(f)
print("done, exiting...")  # prints - then the process never exits
$ python repro.py
done, exiting...
# hangs forever; SIGKILL required

Passing a path instead of a file object does not hang:

pq.read_table("any.parquet")   # exits cleanly, 8/8 runs

use_threads=False also avoids the hang even with a file object (8/8 clean), as does
pa.set_cpu_count(1), so this looks like a CPU thread-pool teardown deadlock that is
only triggered when the read went through a Python file handle (GIL interaction during
pool shutdown?).

How we found it

pandas.read_parquet (which internally opens the file and passes a handle to pyarrow)
was hanging intermittently (~50% of runs when reading 3 files, rarer with 1 file).
Bisecting pandas out of the equation led to the deterministic file-object reproducer
above. So this same bug likely explains "flaky CI hang" reports from pandas users.

Details

  • The script body completes and atexit handlers run; the hang is after that,
    during interpreter/C-level finalization. faulthandler (SIGABRT) produces no dump.
  • The file content doesn't matter - reproduces with a 5-row single-column file.
  • Closing the file object (or not) before exit makes no difference.
  • A hung process shows the main thread plus ~24 CPU-pool threads all in
    futex_do_wait (from /proc/<pid>/task/*/wchan), and a jemalloc_bg_thd:
python(futex_do_wait) jemalloc_bg_thd(futex_do_wait) python(futex_do_wait) x24 ...

Version matrix (same reproducer, 4 runs each; 124 = hung/timeout, 0 = clean exit)

pyarrow result
25.0.0 124 124 124 124
24.0.0 124 124 124 124
23.0.1 124 124 124 124
22.0.0 124 0 124 124
25.0.0 + use_threads=False 0 0 0 0
25.0.0 + path instead of file object 0 0 0 0

(22.0.0 being intermittent rather than deterministic suggests a timing-dependent race
that became reliably lost at some point.)

Second interpreter build

Also reproduces on the distro CPython (Python 3.14.4, GCC 15.2.0 build,
/usr/bin/python3.14, fresh venv, pyarrow 25.0.0 wheel) - intermittent there
(3/6 runs hang) instead of deterministic, path-based reads clean 6/6. So this is
not specific to one interpreter build; build/timing differences only shift how
often the race is lost.

Environment

  • pyarrow 25.0.0 (manylinux wheel from PyPI, installed via uv)
  • Python 3.13.13 (python-build-standalone, Clang 22.1.3) - deterministic hang
  • Python 3.14.4 (distro build, GCC 15.2.0) - intermittent hang (~50%)
  • Linux 7.0.0-22-generic x86_64, glibc 2.43
  • 24 CPUs
  • pandas 3.0.3 (only for the original discovery path; not needed for the reproducer)
  • Persists after OS upgrade + reboot (kernel 7.0.0-22 → 7.0.0-27, glibc 2.43-2ubuntu2)

Component(s)

Python

Component(s)

Python

Activity

  1. raulcd commented on Jul 13, 2026

    @raulcd
    Member

    Thank you very much for creating the issue.
    I am not sure I understand the Version matrix section above, can you help me understand clearly whether this:

    • Is a new issue given the latest 25.0.0 release
    • Has been happening since 22.0.0

    Is this only happening with a specific parquet file or is it reproducible with a minimal generated parquet file?

  2. mikamikasuki commented on Oct 2, 2026

    @mikamikasuki

    I have now independently reproduced this with a generated five-row Parquet file on macOS 15 (arm64), CPython 3.14.7, and the PyArrow 25.0.0 wheel. With 24 CPU threads, the file-object case timed out in 3 of 30 fresh processes; path reads exited cleanly in 12 of 12, and file-object reads with use_threads=False exited cleanly in 12 of 12.

    I captured native stacks from three hung processes. The main thread was waiting in Arrow's CPU ThreadPool::Shutdown; a worker was destroying a ParquetFileFragment / PyReadableFile, then blocked in PyGILState_Ensure → CPython thread-state attachment during finalization. This matches CPython's documented behavior that non-finalization threads attempting to attach during late interpreter finalization can be blocked permanently: https://docs.python.org/3.14/c-api/interp-lifecycle.html

    The source path leads to OwnedRefNoGIL in python/pyarrow/src/arrow/python/common.h, which reacquires the GIL to decref a retained Python object. I have a local candidate guard for the finalization path, but it still needs a source build and review of the check-to-GIL-acquire race, so I have not opened a PR.

    AI assistance was used to help trace the source and draft the candidate change; I ran the reproductions and examined the captured stacks. I would like to work on this issue.

  3. deepkilo commented on Oct 18, 2026

    @deepkilo

    Additional Linux evidence from compatibility testing of a quantitative-research runtime. This was an observed process-exit failure investigated back to native cleanup, not a finding from source review alone. Our reproducer uses generated files and a Python filesystem wrapper; it is related evidence, not a claim that every file-object case has exactly the same ownership path.

    With official PyArrow 26, a malformed fragment raises the expected ArrowInvalid, but the process can still fail during interpreter shutdown. On Linux x86_64 our reduced case aborted on CPython 3.12.15 (12/12 four-fragment runs and 12/12 eight-fragment runs), timed out on 3.13.16 (4/4), and also timed out on unmodified 26 with 3.15.0 (3/3). Upgrading Python alone did not repair it.

    Self-contained reduced case; run in fresh processes with a timeout, since the symptom is at exit:

    import tempfile
    from pathlib import Path
    import fsspec
    import pyarrow as pa
    import pyarrow.dataset as ds
    import pyarrow.fs as fs
    import pyarrow.parquet as pq
    
    root = Path(tempfile.mkdtemp())
    pq.write_table(pa.table({'value': [1, 2, 3]}), root / 'valid.parquet')
    (root / 'bad.parquet').write_bytes(b'not a parquet file')
    filesystem = fs.PyFileSystem(fs.FSSpecHandler(fsspec.filesystem('file')))
    paths = [str(root / name) for name in
             ['valid.parquet', 'bad.parquet', 'valid.parquet', 'valid.parquet']]
    dataset = ds.dataset(paths, filesystem=filesystem, format='parquet',
                         schema=pa.schema([('value', pa.int64())]),
                         exclude_invalid_files=False)
    try:
        dataset.to_table(use_threads=True, fragment_readahead=4)
    except pa.ArrowInvalid:
        pass
    else:
        raise AssertionError('Expected the malformed-fragment error')

    Our captured native stack passes through callback-capture destruction, MergedGenerator / SerialReadahead, the Parquet reader / ReadRangeCache, and PyBuffer::~PyBuffer, then PyGILState_Ensure during Py_FinalizeEx. On 3.12 the forced unwind crosses a noexcept boundary and terminates; newer Python parks the late worker while Arrow's pool shutdown joins it.

    This also relates to #46945: checking Py_IsInitialized or finalization before acquiring the GIL leaves a check-to-acquire race. A local candidate uses Python 3.15's PEP 788 view/token admission API for PyBuffer, NumPyBuffer, and OwnedRefNoGIL cleanup. The complete Python-native wheel was rebuilt, with the eight computational Arrow/Parquet DSOs retained byte-for-byte. Eighteen bounded subprocess checks then exited normally, including malformed-input and valid-input controls; the malformed fragment still raises rather than being suppressed.

    That candidate is qualified only for main-interpreter, GIL CPython 3.15, not older Python, free-threaded builds or subinterpreters. A failed admission can also mean allocation failure, so the candidate's skipped cleanup may leak a reference in that case. I am sharing the mechanism and verification boundary for discussion, not claiming a universally ready upstream fix or a newly introduced 26 regression.

    Disclosure: OpenAI Codex (GPT-6 family; exact variant/effort unavailable in this session) assisted with investigation, tool-driven reproduction, candidate work and this text. The stated runs and native stacks are recorded execution evidence, not a claim that the operator manually performed or reviewed every step. No maintainer ping or competing PR is intended.

  4. added a commit that references this issue on Oct 18, 2026
  5. MagicLex commented on Oct 22, 2026

    @MagicLex

    The same exit hang also happens when the scan goes through a pyarrow.fs.PyFileSystem instead of a Python file object (macOS arm64, CPython 3.12.12).

    # child.py DIR, where DIR is an absolute path holding 4 Parquet files of 1000 int64 rows
    import sys, fsspec
    import pyarrow.dataset as ds, pyarrow.fs as pafs
    fs = pafs.PyFileSystem(pafs.FSSpecHandler(fsspec.filesystem("file")))
    # control: fs = pafs.LocalFileSystem()
    print(ds.dataset(sys.argv[1], filesystem=fs, format="parquet").to_table().num_rows, flush=True)

    Result on pyarrow 26.0.0, fresh processes, 8 in parallel, hung = printed the count and still alive after 20 s: 15/200 hung with PyFileSystem, 0/200 with LocalFileSystem.

    Main thread of a hung process (sample):

    exit
    std::shared_ptr<arrow::internal::ThreadPool>::~shared_ptr
    arrow::internal::ThreadPool::~ThreadPool()
    arrow::internal::ThreadPool::Shutdown(bool)
    

    PR #54467 likely covers this path; not tested.

    Workaround: scan with a native filesystem (LocalFileSystem, or SubTreeFileSystem over it) instead of a Python-implemented one.

  6. AndreaBozzo commented on Oct 27, 2026

    @AndreaBozzo

    An early stop makes this deterministic, and close() avoids it, but releasing the C stream export does not, because ExportedArrayStream::Release (cpp/src/arrow/c/bridge.cc) drops its shared_ptr without calling reader->Close().

    import tempfile, fsspec
    import pyarrow as pa, pyarrow.dataset as ds, pyarrow.fs as pafs, pyarrow.parquet as pq
    
    root = tempfile.mkdtemp()
    for i in range(8):
        pq.write_table(pa.table({"x": range(1000)}), f"{root}/part{i}.parquet", row_group_size=100)
    fs = pafs.PyFileSystem(pafs.FSSpecHandler(fsspec.filesystem("file")))
    reader = ds.dataset(root, filesystem=fs, format="parquet").scanner().to_reader()
    reader.read_next_batch()
    # reader.close()  # with this line: clean exit

    Linux x86_64, PyArrow 26.0.0, CPython 3.12.3, 10 fresh processes each: no close, 10/10 fail at exit (aborts with PyGILState_Release ... finalizing, or hangs); reader.close(), 10/10 clean; reading through RecordBatchReader._import_from_c_capsule(reader.__arrow_c_stream__()) and closing that, 10/10 fail; then also reader.close() on the original, 10/10 clean. Not tested against #54467.

  7. daniel-leicht commented on Nov 11, 2026

    @daniel-leicht

    I hit the same thing through pyarrow.fs.PyFileSystem (first seen with deltalake's DeltaTable.to_pyarrow_table(), which reads through a PyFileSystem). Adding a reproducer that needs only pyarrow (no fsspec, no malformed file) and fails on every run here.

    The script writes 20 small Parquet files to a temp folder, then starts fresh child processes that each scan them through a PyFileSystem whose open_input_file returns pa.PythonFile(open(path, "rb")), and exit right after to_table(). --native-fs is the control (LocalFileSystem).

    Python pyarrow PyFileSystem --native-fs
    3.13.14 26.0.1 5/5 hung 0/5 failed
    3.12.13 26.0.1 5/5 aborted (exit code -6, terminate called without an active exception) not run

    Debian 12, x86_64, glibc 2.36, 72 CPUs, PyPI wheels.

    On 3.13.14 with 26.0.1 the stuck worker is still in PyBuffer::~PyBuffer (pystack, trimmed):

    arrow::acero::(anonymous namespace)::ExecPlanImpl::~ExecPlanImpl()
    ...
    parquet::arrow::(anonymous namespace)::FileReaderImpl::~FileReaderImpl()
    parquet::SerializedFile::~SerializedFile()
    arrow::io::internal::ReadRangeCache::LazyImpl::~LazyImpl()
    std::_Sp_counted_ptr<arrow::py::PyBuffer*, ...>::_M_dispose()
    arrow::py::PyBuffer::~PyBuffer()
    PyGILState_Ensure
    take_gil
    PyThread_hang_thread
    pause
    

    and the main thread is in arrow::internal::ThreadPool::Shutdown(bool) -> std::condition_variable::wait, reached from libc at process exit (the libc frames are not symbolized).

    atexit.register(time.sleep, 0.5) in the child avoids it here. I have not tested #54467.

    repro.py
    """Reproduces a hang (Python 3.13+) or abort (Python 3.11/3.12) at interpreter exit after a dataset scan through
    pyarrow.fs.PyFileSystem.
    
    Each run is a fresh child process that reads a small Parquet dataset through a PyFileSystem (file data comes back as
    Python bytes, held by arrow::py::PyBuffer) and then exits immediately.
    
        python repro.py              # PyFileSystem: runs hang (3.13+) or crash with SIGABRT (3.11/3.12)
        python repro.py --native-fs  # control, same files through pyarrow.fs.LocalFileSystem: every run exits normally
    """
    import argparse
    import os
    import subprocess
    import sys
    import tempfile
    
    import pyarrow as pa
    import pyarrow.dataset as ds
    import pyarrow.fs as pafs
    import pyarrow.parquet as pq
    
    
    class PythonFileHandler(pafs.FileSystemHandler):
        """Local files opened as Python file objects, like any Python handler (fsspec, deltalake's DeltaStorageHandler)."""
    
        def __init__(self):
            self._local = pafs.LocalFileSystem()
    
        def __eq__(self, other):
            return isinstance(other, PythonFileHandler)
    
        def __ne__(self, other):
            return not self == other
    
        def get_type_name(self):
            return "python-file"
    
        def normalize_path(self, path):
            return path
    
        def get_file_info(self, paths):
            return self._local.get_file_info(paths)
    
        def get_file_info_selector(self, selector):
            return self._local.get_file_info(selector)
    
        def open_input_file(self, path):
            return pa.PythonFile(open(path, "rb"), mode="r")
    
        def open_input_stream(self, path):
            return pa.PythonFile(open(path, "rb"), mode="r")
    
        def _read_only(self, *args, **kwargs):
            raise NotImplementedError("read-only")
    
        create_dir = delete_dir = delete_dir_contents = delete_root_dir_contents = delete_file = _read_only
        move = copy_file = open_output_stream = open_append_stream = _read_only
    
    
    def write_dataset(directory, files, rows):
        table = pa.table({
            "id": pa.array([f"doc-{i:08d}" for i in range(rows)]),
            "text": pa.array([f"some text for row {i} " * 4 for i in range(rows)]),
            "vector": pa.array([[float(i % 97)] * 256 for i in range(rows)], type=pa.list_(pa.float32())),
        })
        paths = []
        for n in range(files):
            paths.append(os.path.join(directory, f"part-{n:03d}.parquet"))
            pq.write_table(table, paths[-1], row_group_size=max(1, rows // 4))
        return paths
    
    
    def child(paths, native_fs=False):
        filesystem = pafs.LocalFileSystem() if native_fs else pafs.PyFileSystem(PythonFileHandler())
        dataset = ds.dataset(paths, filesystem=filesystem, format=ds.ParquetFileFormat(
            default_fragment_scan_options=ds.ParquetFragmentScanOptions(pre_buffer=True)))
        print(f"read {dataset.to_table().num_rows} rows", flush=True)
        # Return right away: the interpreter starts shutting down while Arrow may still be tearing the scan down.
    
    
    def main():
        parser = argparse.ArgumentParser()
        parser.add_argument("--runs", type=int, default=10)
        parser.add_argument("--files", type=int, default=20)
        parser.add_argument("--rows", type=int, default=5000, help="rows per file")
        parser.add_argument("--timeout", type=float, default=20, help="seconds before a run counts as hung")
        parser.add_argument("--native-fs", action="store_true", help="control: read through pyarrow's LocalFileSystem")
        parser.add_argument("--child", nargs="*", help=argparse.SUPPRESS)
        args = parser.parse_args()
        if args.child is not None:
            return child(args.child, args.native_fs)
    
        print(f"Python {sys.version.split()[0]}, pyarrow {pa.__version__}, Arrow threads: {pa.cpu_count()} CPU, "
              f"{pa.io_thread_count()} IO; "
              f"{'LocalFileSystem (control)' if args.native_fs else 'PyFileSystem'}")
        counts = {"ok": 0, "hung": 0, "crashed": 0}
        with tempfile.TemporaryDirectory() as directory:
            paths = write_dataset(directory, args.files, args.rows)
            for run in range(1, args.runs + 1):
                command = [sys.executable, __file__, *(["--native-fs"] if args.native_fs else []), "--child", *paths]
                proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
                try:
                    output, _ = proc.communicate(timeout=args.timeout)
                    result = "ok" if proc.returncode == 0 else "crashed"
                except subprocess.TimeoutExpired:
                    proc.kill()
                    output, _ = proc.communicate()
                    result = "hung"
                counts[result] += 1
                first_lines = " | ".join(line for line in output.strip().splitlines()[:3])
                print(f"run {run:3d}: {result:7s} exit code {proc.returncode:4d}  {first_lines[:150]}", flush=True)
        print(f"\n{counts['hung']} hung, {counts['crashed']} crashed, {counts['ok']} ok out of {args.runs} runs")
    
    
    if __name__ == "__main__":
        main()

    AI assistance (Claude) was used for the investigation and to draft this comment.

  8. masatakashiwagi commented on Nov 19, 2026

    @masatakashiwagi

    Another data point from macOS: the hang is not limited to Python file objects. Wrapping a Python bytes object in pa.BufferReader triggers it too, while the same data in an Arrow-owned buffer does not. It still reproduces on 26.0.1.

    Environment: macOS 15.7 (arm64, Apple M4, 10 cores), CPython 3.12.9 (python-build-standalone via uv), fresh venv with only the pyarrow wheel from PyPI.

    # repro.py SOURCE THREADS
    import io
    import sys
    
    import pyarrow as pa
    import pyarrow.parquet as pq
    
    source, threads = sys.argv[1], sys.argv[2] == "threads"
    stream = pa.BufferOutputStream()
    pq.write_table(pa.table({"a": pa.array([f"k{n}" for n in range(200_000)])}), stream)
    arrow_buffer = stream.getvalue()
    if source == "arrow_buffer":
        pq.read_table(pa.BufferReader(arrow_buffer), use_threads=threads)
    elif source == "python_bytes":
        pq.read_table(pa.BufferReader(arrow_buffer.to_pybytes()), use_threads=threads)
    elif source == "bytesio":
        pq.read_table(io.BytesIO(arrow_buffer.to_pybytes()), use_threads=threads)
    print("ok", flush=True)

    Fresh process per run; a run counts as hung when it printed ok but was still alive after 6 s.

    pyarrow 26.0.1, 30 runs each:

    source use_threads=True use_threads=False
    pa.BufferReader(pa.Buffer) (Arrow-owned) 0/30 0/30
    pa.BufferReader(bytes) (Python-owned) 21/30 0/30
    io.BytesIO(bytes) 16/30 0/30

    python_bytes with use_threads=True on older wheels, 30 runs each: 25.0.0 12/30, 24.0.0 15/30, 23.0.1 25/30, 22.0.0 22/30.

    In every hung process I sampled (sample), the main thread is in exit → __cxa_finalize_ranges → arrow::internal::ThreadPool::~ThreadPool() → ThreadPool::Shutdown(bool), waiting on a condition variable. No thread is in PyGILState_Ensure. For python_bytes, the only other thread is an idle libdispatch thread, so no CPU-pool worker is left at all. For bytesio, one worker remains, idle in the worker loop. My guess is that a worker that touched Python during finalization was terminated by CPython without leaving the pool's worker list, so Shutdown waits for it forever. I have not verified this.

  9. jasonhimmelstein commented on Nov 20, 2026

    @jasonhimmelstein

    Here's a Linux data point for the pa.BufferReader(bytes) case: on CPython 3.12 it aborts rather than hangs, even with the Py_IsInitialized() guard from #49943 in place.

    Environment: pyarrow 26.0.1 (PyPI wheel), CPython 3.12.16 and 3.13.18, Linux 7.0 x86_64, glibc 2.43 (GitHub Actions ubuntu-latest).

    # repro.py
    import io
    import threading
    import time
    
    import pyarrow as pa
    import pyarrow.parquet as pq
    
    
    def wake():
        while True:
            time.sleep(0.0005)
    
    
    for _ in range(8):
        threading.Thread(target=wake, daemon=True).start()
    
    sink = io.BytesIO()
    pq.write_table(pa.table({"x": list(range(1000)), "s": ["a"] * 1000}), sink)
    raw = sink.getvalue()
    
    for _ in range(4):
        pq.read_table(pa.BufferReader(raw), use_threads=False)

    Fresh processes, 5 at a time:

    Run Exited non-zero
    3.12.16 9 of 3000, all terminate called without an active exception
    3.12.16, raw copied into pa.allocate_buffer(len(raw)) first 0 of 3000
    3.12.16, without the 8 threads 0 of 600
    3.13.18 13 of 3000, with no output and no core dump (probably hung until our 60 s timeout; we didn't record exit codes)

    The other threads are what make it happen. Without them we couldn't trigger it. In our application, the native threads of another extension module (deltalake's tokio runtime) had the same effect, at about 2% of runs.

    Aborting thread (3.12, from a core dump):

    #7  std::terminate()
    #10 _Unwind_ForcedUnwind
    #13 __GI___pthread_exit
    #14 PyThread_exit_thread            Python/thread_pthread.h:370
    #15 take_gil                        Python/ceval_gil.c:353
    #16 PyEval_RestoreThread            Python/ceval_gil.c:708
    #17 PyGILState_Ensure               Python/pystate.c:2240
    #18 arrow::py::PyBuffer::~PyBuffer()
    #19 std::_Sp_counted_ptr<arrow::py::PyBuffer*, ...>::_M_dispose()
    #21 arrow::io::BufferReader::~BufferReader()
    #23 parquet::SerializedFile::~SerializedFile()
    #24 parquet::arrow::(anonymous namespace)::FileReaderImpl::~FileReaderImpl()
    #26 FnOnce<void (FutureImpl const&)>::FnImpl<Future<Empty>::WrapResultOnComplete::Callback<...>>
    #29 ConcreteFutureImpl::DoMarkFinishedOrFailed(FutureState)
    ...
    #34 FnOnce<void ()>::FnImpl<ThreadPool::SpawnReal(...)>
    #35 std::thread::_State_impl<... ThreadPool::LaunchWorkersUnlocked(int)::{lambda()#1} ...>::_M_run()
    

    The main thread is in Py_FinalizeEx (pylifecycle.c:1915), in PyGC_Collect. So the last reference to the FileReaderImpl is dropped by a future callback on a CPU-pool worker, even with use_threads=False, after read_table has returned. Py_IsInitialized() is still true that early in finalization, so the guard doesn't stop ~PyBuffer from calling PyGILState_Ensure. CPython 3.12 then ends the worker with pthread_exit, and the forced unwind through the noexcept destructor calls std::terminate. A check on Py_IsFinalizing() (3.13+) or _Py_IsFinalizing() (3.12) would catch it. Releasing the reader on the calling thread before read_table returns would avoid it altogether.

  10. masatakashiwagi commented on Nov 23, 2026

    @masatakashiwagi

    Thanks, this matches what I see on macOS: the same code path, ending in a hang instead of an abort.

    Same repro and environment as my earlier comment (pyarrow 26.0.1, CPython 3.12.9, macOS 15.7 arm64), use_threads=True. Under lldb with breakpoints on PyThread_exit_thread and pthread_exit, a CPU-pool worker stops in PyThread_exit_thread while the main thread is in the GC during finalization, then in pthread_exit. After continue, the process doesn't abort. It hangs in exit → __cxa_finalize_ranges → ThreadPool::~ThreadPool() → Shutdown.

    To check that this is the cause of every hang and not just one of them, I also interposed pthread_exit (DYLD_INSERT_LIBRARIES) to log a backtrace on each call. 15 runs each:

    source hung pthread_exit called both
    pa.BufferReader(bytes) 7/15 7/15 7
    io.BytesIO(bytes) 4/15 4/15 4

    Every hung run had exactly one pthread_exit. No run that exited normally had any.

    Where the last reference is dropped depends on the source. Here read_table goes through the dataset scanner:

    # pa.BufferReader(bytes)
    PyThread_exit_thread
    take_gil
    PyEval_RestoreThread
    PyGILState_Ensure
    arrow::py::PyBuffer::~PyBuffer()
    arrow::io::BufferReader::~BufferReader()
    arrow::dataset::FileSource::FileSource(...)::$_0   (destructor)
    arrow::dataset::FileFragment::~FileFragment()
    ...
    arrow::internal::ThreadPool::SpawnReal(...)   (CPU pool worker)
    
    # io.BytesIO(bytes): a PyBuffer held in the pre-buffer cache
    ...
    PyGILState_Ensure
    arrow::py::PyBuffer::~PyBuffer()
    arrow::ConcreteFutureImpl::~ConcreteFutureImpl()
    arrow::io::internal::ReadRangeCache::~ReadRangeCache()
    parquet::SerializedFile::~SerializedFile()
    parquet::arrow::FileReaderImpl::~FileReaderImpl()
    ...
    arrow::internal::ThreadPool::SpawnReal(...)   (CPU pool worker)
    

    (With io.BytesIO, I also saw it dropped in PyReadableFile::~PyReadableFile() → OwnedRefNoGIL::~OwnedRefNoGIL().)

    My reading is that Darwin's pthread_exit doesn't unwind C++ frames, so the worker disappears without the pool noticing, and Shutdown waits for it forever. On glibc, the forced unwind through the noexcept destructor calls std::terminate instead. Either way, it's the same bug.

    This also explains the idle worker I mentioned for io.BytesIO. It seems to belong to the IO pool: in a run that didn't hang, the IO pool launched one worker (from RandomAccessFile::ReadAsync), and the CPU pool, which launched four, was shut down first at exit. So it is just waiting for a Shutdown that never starts, because the main thread is stuck in the CPU pool's Shutdown. I haven't tied that thread to the IO pool directly; this is from the counts and the shutdown order.

    On the fix: a Py_IsFinalizing() / _Py_IsFinalizing() check before PyGILState_Ensure would catch the cases above. I think it can still race, though, because finalization can begin between the check and take_gil. Releasing the reader on the calling thread before read_table returns avoids touching Python from a worker at all, so that seems the more robust option to me.

    A side note for anyone trying to reproduce: the timing is sensitive to stdout. With stdout redirected to a regular file, pa.BufferReader(bytes) didn't hang in 15 runs. With stdout sent to /dev/null, it hung in 6–10 of 15.

  11. aclerc commented on Nov 23, 2026

    @aclerc

    A data point from the most common route into this: pandas.read_parquet(local_path) on pandas 2.x. pandas 2.x opens a local path with Python's open() and passes the handle to pyarrow, so every pandas 2 user reading a local file goes through the Python-file-object path in the original report. We found it as an intermittent hang in a CI job on Python 3.13: a child process that read a parquet cache with pandas never exited.

    Results from the reproducer below. Each run is a fresh process that calls pd.read_parquet(path) on a small local file and exits; a run counts as hung if it's still alive after 20 s. Linux x86_64 (Ubuntu 22.04, glibc 2.35), 32 CPUs, Python 3.13.18 (python-build-standalone), fresh venvs with only pandas and pyarrow from PyPI, 12 processes at a time:

    pandas pyarrow read_parquet(path) read_parquet(path, filesystem=pyarrow.fs.LocalFileSystem())
    2.3.3 20.0.0 14 / 2000 hung 0 / 2000
    2.3.3 26.0.1 123 / 2000 hung not run
    3.1.1 20.0.0 0 / 2000 not run
    3.1.1 26.0.1 0 / 2000 not run

    So on this route the hang is about 9x more frequent on pyarrow 26.0.1 than on 20.0.0, which fits the earlier comments' observation that newer wheels lose the race more often.

    pandas 3.1.1 no longer opens a Python handle for a local path (pandas.io.parquet.get_handle isn't called on a read), so it doesn't reach this bug. On pandas 2.x, passing filesystem=pyarrow.fs.LocalFileSystem() avoids it the same way.

    In our application (more native threads loaded: OpenBLAS, numexpr), the same read hung about 1% of the time on both Python 3.13.18 (19 / 2000) and 3.13.16 (40 / 2000), and 0 / 2000 with LocalFileSystem.

    gdb on a hung process (pandas 2.3.3, pyarrow 20.0.0) shows the same deadlock as the earlier comments. The main thread:

    arrow::internal::ThreadPool::Shutdown(bool)
    std::_Sp_counted_ptr<arrow::internal::ThreadPool*, ...>::_M_dispose()
    __run_exit_handlers
    exit
    __libc_start_call_main
    

    The CPU-pool worker, dropping the last reference to the dataset scan's reader after read_parquet had returned:

    __libc_pause
    PyThread_hang_thread
    take_gil
    _PyThreadState_Attach
    PyGILState_Ensure
    arrow::py::PyBuffer::~PyBuffer()
    arrow::Future<std::shared_ptr<arrow::Buffer>>::SetResult(...)::{lambda(void*)#1}
    arrow::ConcreteFutureImpl::~ConcreteFutureImpl()
    arrow::io::internal::ReadRangeCache::LazyImpl::~LazyImpl()
    parquet::ParquetFileReader::~ParquetFileReader()
    parquet::arrow::(anonymous namespace)::FileReaderImpl::~FileReaderImpl()
    ... MergedGenerator / SlicingGenerator / SerialReadaheadGenerator state destructors
    
    repro.py
    """Hang at interpreter exit after pandas.read_parquet(local_path), Python 3.13+.
    
    Each run is a fresh child process that reads a small local parquet file with
    pandas.read_parquet(path) and exits. pandas 2.x opens the path as a Python file handle,
    so pyarrow's reads are held in arrow::py::PyBuffer.
    
        python repro.py                # pandas default: some runs hang at exit
        python repro.py --native-fs    # control: filesystem=pyarrow.fs.LocalFileSystem()
    """
    
    import argparse
    import subprocess
    import sys
    import tempfile
    from pathlib import Path
    
    import numpy as np
    import pandas as pd
    import pyarrow as pa
    
    
    def child(path: str, *, native_fs: bool) -> None:
        kwargs = {}
        if native_fs:
            import pyarrow.fs
    
            kwargs["filesystem"] = pyarrow.fs.LocalFileSystem()
        print(len(pd.read_parquet(path, **kwargs)), flush=True)
    
    
    def main() -> None:
        parser = argparse.ArgumentParser()
        parser.add_argument("--runs", type=int, default=200)
        parser.add_argument("--parallel", type=int, default=8)
        parser.add_argument("--timeout", type=float, default=20)
        parser.add_argument("--native-fs", action="store_true")
        parser.add_argument("--child", help=argparse.SUPPRESS)
        args = parser.parse_args()
        if args.child:
            child(args.child, native_fs=args.native_fs)
            return
    
        print(
            f"Python {sys.version.split()[0]}, pandas {pd.__version__}, pyarrow {pa.__version__}, "
            f"{pa.cpu_count()} CPU threads; {'LocalFileSystem' if args.native_fs else 'pandas default'}"
        )
        with tempfile.TemporaryDirectory() as tmp:
            path = str(Path(tmp) / "data.parquet")
            idx = pd.date_range("2024-03-01", periods=1440, freq="60s", tz="UTC")
            pd.DataFrame({f"c{i}": np.random.default_rng(i).random(len(idx)) for i in range(8)}, index=idx).to_parquet(path)
            cmd = [sys.executable, __file__, "--child", path, *(["--native-fs"] if args.native_fs else [])]
            hung = 0
            for start in range(0, args.runs, args.parallel):
                procs = [
                    subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                    for _ in range(min(args.parallel, args.runs - start))
                ]
                for p in procs:
                    try:
                        p.wait(timeout=args.timeout)
                    except subprocess.TimeoutExpired:
                        hung += 1
                        p.kill()
                        p.wait()
        print(f"{hung} of {args.runs} runs hung at exit")
    
    
    if __name__ == "__main__":
        main()

    Run with python repro.py --runs 2000 --parallel 12.

    I haven't tested #54467.

  12. added
    Status: confirmed
    on Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Component: PythonStatus: confirmedType: bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions