edgarrmondragon commented on PR #1035: URL: https://github.com/apache/arrow-nanoarrow/pull/1035#issuecomment-7365291187
Hey @paleolimbot, this is ready for another pass. A lot of text ahead, but the TL;DR is that this PR now fixes four thread-safety issues. Two of them were also bugs in the GIL build. I dropped pytest-run-parallel since it didn't find the races, while the dedicated tests do. There's one gap for IPC-backed streams that I'd like your input on. --- _Disclaimer: this was assisted by Claude Code (Opus 5.5). I checked at every step and verified that the races were real._ To check for data races I asked Claude to review the code and I also ran the tests using a TSan build of free-threaded CPython[^1]. ## `pyobject_buffer_count` TSan reported a data race on `pyobject_buffer_count` (from the `+= 1` and `-= 1` in `_utils.pyx`) on the initial `test_shared_array_read_concurrently` test. The number of warnings TSan produced changes from run to run, but it ranged between 18 and 34 warnings in a few runs. `test_shared_array_read_concurrently` triggers it even though pytest reports the test as passing. No other tests trigger it. The fix guards the counter with a `cython.pymutex`, which requires Cython 3.1 or later, so I bumped the build requirement (`cython.critical_section` also requires Cython 3.1+). We could run tests under TSan in CI (using NumPy's approach as inspiration[^2]) but that would require a TSan build of CPython. --- Beyond that, I had Claude look for other races using these criteria: 1. Look for module-level cdef variables and global statements in the `.pyx` files. That found only `pyobject_buffer_count`. 2. Look for methods that change C state or cached attributes on self, including ones that look read-only. For example, advancing a stream. 3. Check whether two threads could reasonably call that method on the same object at once. For example, reading an array, schema or buffer. 4. For each candidate, write a test where one object is shared across threads, and run it three ways: under TSan, on a normal free-threaded build, and with `-X gil=1` as a control. Something counts as a race if TSan reports it, or if the free-threaded build gives wrong results or crashes while the `-X gil=1` run is fine. ## `CArrayStream.get_next()` Each call to a stream's `get_next()` moves its position forward. In `_array_stream.pyx`, `CArrayStream.get_next()` called `ArrowArrayStreamGetNext(self._ptr, ...)` directly, with no lock. Until now the calling thread held the GIL for the whole call (except where a callback releases it, see the IPC question below), so calls happened one at a time. TSan confirmed this race in `ArrowBasicArrayStreamGetNext` via the new `test_shared_stream_consumed_concurrently` test; and the test also fails (or crashes) on a regular free-threaded build. Fixed it with `cython.critical_section(self)` around the `CArrayStream` methods that use or move the stream. Now, streams nanoarrow builds from in-memory arrays are safe, and taking arrays is serialized. There's a note in the README that tells the user to do the work on each array in the thread that receives it. Reading from an IPC file detaches the thread because of the `readinto` I/O, so the stream is not protected and another thread can enter `get_next()` on the same stream while the first is still inside the nanoarrow IPC reader. FWIW the GIL builds have the same race (confirmed [in CI](https://github.com/apache/arrow-nanoarrow/actions/runs/46976265665/job/143804482166?pr=1035), see the XFAIL), since file I/O releases the GIL: https://github.com/apache/arrow-nanoarrow/blob/c1fdc8e6a4765799d56852995a0a9481467ea042/python/src/nanoarrow/_ipc_lib.pyx#L131-L138 **Q: Should `CArrayStream` hold a `cython.pymutex` around its calls into the C stream, instead of a critical section? That would protect IPC-backed streams, but the tradeoff is a risk of hangs and Ctrl+C not reaching waiting threads.** ## `SchemaMetadata` This actually had a bug in the GIL build too. Every method used to reset and advance the same `self._reader`, so two iterations over one metadata object broke each other. For example, `[(k, md[k]) for k in md]` returned only the first pair. Each method now uses its own reader, so no lock is needed. ## `CBuffer` `CBuffer.__getbuffer__` let its internal `CBufferView` fill in the `Py_buffer`, which set `buffer.obj` to the view. Releasing a `memoryview` therefore called the view's no-op `__releasebuffer__` instead of the `CBuffer`'s, so the count of open exports never went down. After a single `memoryview(buf)`, `view()`, `_set_format()` and `_set_data_type()` failed permanently, and the error message referred to a nonexistent `_writable_get_buffer_count` attribute, so they raised `AttributeError` instead of `RuntimeError`. `CBuffer.__getbuffer__` now sets `buffer.obj` to the `CBuffer`, so `memoryview(buf).obj` is the `CBuffer` rather than the internal `CBufferView`. The export count and the operations that depend on it are guarded with `cython.critical_section` so concurrent exports of a shared `CBuffer` on free-threaded builds don't lose updates. This is the usual behavior: `memoryview(b"abc").obj` is the bytes object itself. From the CPython docs[^3]: ```python >>> b = bytearray(b'xyz') >>> m = memoryview(b) >>> m.obj is b True ``` ## Results With all four fixes, the whole suite runs with no TSan warnings. Tests that need optional dependencies (pyarrow, numpy, cupy or CUDA) were skipped because those weren't installed in the TSan environment, so those code paths weren't checked. I added a "Thread safety" section to the Python README that lists which objects can be shared between threads. It documents the builders (`CArrayBuilder`, `CBufferBuilder` and `CSchemaBuilder`) as not thread-safe: they exist to be modified step by step, and none of their methods are locked. I think this is the right choice, but please let me know if you disagree. RE `null_count`: reading through `Array` or `CArray` creates a fresh `CArrayView` each time, so the lazily cached `null_count` is never shared. A single `CArrayView` shared directly between threads would race on that cache, though every thread writes the same value. I created a gist with a simple script that exercises consuming a stream from multiple threads: https://gist.githubusercontent.com/edgarrmondragon/9869a790e5e5124ed99fb2b3ff4e7b77 A few ways to run it: 1. shows that free-threaded CPython is working, and the performance of spreading the work across threads: ```shell uv run -p 3.15t --script https://gist.githubusercontent.com/edgarrmondragon/9869a790e5e5124ed99fb2b3ff4e7b77/raw/nanoft.py ``` 2. re-enables the GIL ```console PYTHON_GIL=1 uv run -p 3.15t --script ... ``` Now switch the dependency ref from `refs/pull/1035/head` to `main` in the script's header: 3. Disables the GIL (crashes) ```console PYTHON_GIL=0 uv run -p 3.15t --script ... ``` 4. The GIL is re-enabled by default at import time on `main`, so the script runs fine ```console uv run -p 3.15t --script ... ``` On my laptop (4 performance + 4 efficiency cores), 8 threads ran about 4x faster than 1. A plain-Python version of the same work, without nanoarrow, levels off at the same point, so the limit comes from the machine or the interpreter, not from nanoarrow. <details><summary>How to run tests with TSan</summary> ```sh # 1. Build free-threaded CPython with TSan (about 10 minutes) git clone --depth 1 -b v3.15.2 https://github.com/python/cpython.git cd cpython CC=clang CXX=clang++ ./configure --disable-gil --with-thread-sanitizer --prefix="$HOME/.local/cpython-tsan" make -j8 && make install # 2. Build nanoarrow with TSan instrumentation (from arrow-nanoarrow/python) uv venv -p "$HOME/.local/cpython-tsan/bin/python3.15t" .venv-tsan export VIRTUAL_ENV="$PWD/.venv-tsan" uv pip install meson meson-python Cython ninja pytest uv pip install --no-build-isolation \ -Csetup-args=-Db_sanitize=thread -Csetup-args=-Db_lundef=false -Csetup-args=-Ddebug=true \ -Cbuild-dir=build-tsan . # 3. Run the tests. -s keeps pytest from swallowing TSan's output on stderr. # TSan makes the process exit non-zero when it finds a race, even if pytest says the tests passed. TSAN_OPTIONS="halt_on_error=0" .venv-tsan/bin/python -m pytest -s tests/test_threading.py ``` </details> [^1]: https://py-free-threading.github.io/thread_sanitizer/ [^2]: https://github.com/numpy/numpy/blob/main/.github/workflows/compiler_sanitizers.yml [^3]: https://docs.python.org/3/library/stdtypes.html#memoryview.obj -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
