← Back to Pull requests

feat(python): declare the package as compatible with free-threaded CPython and fix thread-safety issues #1035

Open
edgarrmondragon opened this pull request with 474 lines diff across 13 files
View on GitHub
edgarrmondragon edgarrmondragon commented on Nov 25, 2026 21:44 UTC
Author

As discussed in https://github.com/apache/arrow-nanoarrow/pull/1030#discussion_r4690053076.

I found and fixed three data races in the free-threaded build, and one bug that was present in GIL builds too.

Common patterns and their thread-safety status are documented.

Developed with AI assitance (Claude Code Opus 5.5)

Diff: 474 lines (+405 / -69) across 13 files Reviewer: paleolimbot Review duration: 10685m
All Vouch review confidence checks passed
Residual risk 0.05 = Change Risk (0.62) × (1 − Review Confidence (0.93)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.62 · 474 lines diff across 13 files
0.62
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.94 · 5 substantive comment(s)
0.94
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
92%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.369
Ai Authored ai_authored
0.050
Real PR Conversation Timeline
9 items
paleolimbot paleolimbot commented on Nov 26, 2026 02:48 UTC
Reviewer

While I don't mind this per se, I would also like to make sure we run realistic scenarios that exercise realistic things people need to do in parallel. One obvious thing I can think of is one Array being read concurrently by many threads. The lazily computed null_count and the refcounting of the shallow clones I am wondering if it might be a problem but it has been a while since I have touched those internals.

edgarrmondragon edgarrmondragon commented on Nov 26, 2026 16:03 UTC
Author

[...] one Array being read concurrently by many threads. The lazily computed null_count and the refcounting of the shallow clones I am wondering if it might be a problem

I just added a test specifically for the lazy null_counts, i.e. a shared array is read concurrently (via slices and per-chuck views) and the null counts are checked for each chunk.

I'll see about testing the refcounts. An existing test already kinda checks them:

https://github.com/apache/arrow-nanoarrow/blob/b5511b28e9ce2aa2970617131377e209072842b6/python/tests/test_c_array.py#L149-L189

paleolimbot paleolimbot commented on code on Nov 27, 2026 20:21 UTC
Code Review
.github/workflows/python.yaml:1
@@ -29,6 +29,9 @@ on:
       - 'src/nanoarrow/**'
       - 'python/**'
 
+env:
+  FORCE_COLOR: 1
+

Do we need to force color here?

paleolimbot paleolimbot commented on Nov 27, 2026 20:37 UTC
Reviewer

I reviewed this more closely and read up on how Cython extensions are supposed to handle free threading.

First, I think we should not use pytest-parallel here...that style of testing is really only useful in the presence of mutable module globals, and that is not a current concern. In other words, I don't think it is testing anything we care about. The threading test you added is more appropriate...it deliberately exercises shared state that we have thought about and decided to support.

Second, while the test you added does exercise some degree of making sure this works under free threading, it doesn't update the Cython module to actually be free threaded safe. Notably, the sections where we currently have with gil are where we mess with reference counts and I think we may need cython.critical_section(self) or cython.pymutex. Note that we also added in this release native C support for shared buffers and shared arrays, so we may want to migrate to that (although it seems easier to start with the cython utilities and move to a lighter solution if that impacts performance).

If I'm off base with that, feel free to add an explanation in a comment next to the -Xfreethreading_compatible=True and update the PR.

I think it would also be good to add to the readme patterns that are specifically supported and tested.

edgarrmondragon edgarrmondragon commented on code on Dec 01, 2026 17:17 UTC
Code Review
.github/workflows/python.yaml:1
@@ -29,6 +29,9 @@ on:
       - 'src/nanoarrow/**'
       - 'python/**'
 
+env:
+  FORCE_COLOR: 1
+

No, this was just so pytest output was colored but not really needed

edgarrmondragon edgarrmondragon commented on Dec 01, 2026 17:30 UTC
Author

First, I think we should not use pytest-parallel here...that style of testing is really only useful in the presence of mutable module globals, and that is not a current concern. In other words, I don't think it is testing anything we care about.

Ok, that makes sense. I'll drop pytest-parallel.

Second, while the test you added does exercise some degree of making sure this works under free threading, it doesn't update the Cython module to actually be free threaded safe. Notably, the sections where we currently have with gil are where we mess with reference counts and I think we may need cython.critical_section(self) or cython.pymutex. . Note that we also added in this release native C support for shared buffers and shared arrays, so we may want to migrate to that (although it seems easier to start with the cython utilities and move to a lighter solution if that impacts performance).

Gotcha. In my limited understanding, refcounting should itself be thread-safe, so the with gil blocks are probably OK. Other shared mutable state (global or not) could still be a problem, so I'll look for that kind of thing (e.g. moving/releasing arrays and streams) and try running the threading tests under TSan on a 3.15t build.

If I'm off base with that, feel free to add an explanation in a comment next to the -Xfreethreading_compatible=True and update the PR.

I'll work on this and then either push some fixes or add the comment next to -Xfreethreading_compatible=True. This becomes a draft in the meantime.

Thanks for reviewing!

edgarrmondragon edgarrmondragon commented on Dec 03, 2026 02:17 UTC
Author

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, 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]:

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

   uv run -p 3.15t --script https://gist.githubusercontent.com/edgarrmondragon/9869a790e5e5124ed99fb2b3ff4e7b77/raw/nanoft.py
   

2. re-enables the GIL

   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)

   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

   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>

# 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

paleolimbot paleolimbot approved these changes on Dec 03, 2026 03:48 UTC
Approved Reviewer

Thank you!

Reviewers
Assignees
edgarrmondragon edgarrmondragon
Labels
risk: low confidence: 92.8% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 62.5% (MEDIUM) · Higher = larger blast radius
62.5%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 92.8% · Lower = rushed or shallow review
92.8%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 4.5% · Safe to merge
4.5%