Repository navigation
GH-55904: [Python][C++][Numba] Read and build Arrow arrays in Numba-compiled code - #55951
Draft
Alex-PLACET wants to merge 1 commit into
Draft
Alex-PLACET wants to merge 1 commit into
Alex-PLACET wants to merge 1 commit into
Conversation
- @njit reads of pa.Array and Arrow C data producers, and scalar builders - benchmark suite (python/benchmarks/numba*.py) shared by the whole PR stack
Alex-PLACET
force-pushed
the
numba-pr1-core
branch
from
December 3, 2026 15:42
93f68dd to
81bedcc
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Rationale for this change
Custom per-element logic on Arrow data has no good path from Python today:
pyarrow.computeonly offers the existing kernels,to_numpy()+ Numba copies nullable arrays, drops the validity bitmap and does not handle strings, and plain Python loops are orders of magnitude slower.This PR lets
@numba.njitfunctions read Arrow arrays without copying and build new Arrow arrays, returned to Python aspa.Array.What changes are included in this PR?
@njitfunctions acceptpa.Arrayand Arrow PyCapsule producers (__arrow_c_array__, single-chunk__arrow_c_stream__), viaregister_producer(cls)orfrom_any(obj).append,reserve,finish.Reading
ArrowArraystruct, by value, no pyarrow object is touched in compiled code._capsule.take_array_into) moves the producer's struct in, the unbox cleanup calls itsreleasewhen the call returns.a[i]isOptional[T]for fixed width, a non-allocatingStringViewfor string/binary, an exact(high, low)pair for decimal128.TypeErrorat typing time. Returning an argument array raises at compile time, since its buffers are released on return.Building
PoolBuffers allocated in C++. Appends are inlined LLVM that call into C++ only to grow.finish()hands the buffers toPyArrow_MakeAndExportArray, which validates them against type and length and exports anArrowArray; the builder is then spent (RuntimeErroron further use).pa.Array._import_from_c, without a copy. A built array can be returned to Python once, a second return raisesRuntimeError.C++
libarrow: anExportArray(std::shared_ptr<ArrayData>, ...)overload inarrow/c/bridge.h, to export a builtArrayDatawithout wrapping it in anArray.libarrow_python:arrow/python/numba.{h,cc}, a smallextern "C"API (pool buffer alloc/reserve/resize/destroy, make-and-export, release) called from compiled code.Packaging and benchmarks
numba_extensionsentry point;import pyarrownever imports Numba.New files:
__init__.py: the public API and user documentation_capsule.py: Arrow C data interface in ctypes, run in Python before each call_utils.py: shared piecesarray.py: reading arraysbuilder_types.py: builder classes and typing, no code generationbuilder.py: builder code generationpoolbuffer.py: growable buffers on Arrow's memory poolAre these changes tested?
New test files:
test_numba.pytest_numba_builder.pytest_numba_capsule.pytest_numba_helpers.pypython/benchmarks/numba*.py: asv suites (per-type reads and builds, per-primitive costs, call overhead).Some numbers
Input data
pa.array(values(type)), with every third element null.i % 100;b"abcdefgh"[: i % 8 + 1];i % 2 == 0;(i % 10000) / 100.nullable_ints(): int640..N, with every third element null.dense_ints(): int640..N, with no validity bitmap.strings():b"abcdefgh", with every third element null.Reads
Numba: a compiled loop reads every element. The numeric case looks like this:
The other loops follow the same pattern:
pc.sum(a),a.null_countpc.sum(a.view(storage type))total += decimal_to_float(a[i], 2)pc.sum(a)(exact decimal)if v.valid: n += string_len(v)pc.sum(pc.binary_length(a))pc.sum(a)is_validif is_valid(a, i): acc += a[i]pc.sum(a)dense_ints()pc.sum(a)Builds
Numba: a compiled loop appends every value to a builder, then calls
finish(). The fixed-width case looks like this:append(i)/append(None)pa.array([v if i % 3 else None ...], type)append(i % 2 == 0)/append(None)pa.array([...], pa.bool_())append(b"abcdefgh")/append(None)pa.array([...], type)append(i % 100), reservedpa.array([i % 100 ...])append(None)pa.array([None] * N, pa.int64())append(i % 3 == 0)pa.array([...])append(b"abcdefgh")pa.array([B] * N, pa.string())b.append(source[i])pa.array(src.to_pylist())####€ Cold and warm calls
The per-type read and build loops are timed three ways, each case in a fresh process:
@njitfunction: typing, LLVM compilation, one run@njit(cache=True), the code loaded from Numba's disk cacheResults
Setup: N = 1,048,576 values; median of 15 runs; pinned to a single core of an i7-13700H; Python 3.13.16, numba 0.68.1, numpy 2.5.4; Arrow C++ built from the same
main(SSE4.2 baseline, AVX2 chosen at runtime).Reads: PyArrow compute kernel vs Numba
Builds: PyArrow vs Numba builder
PyArrow builds the same array from a Python list: a Python loop computes the values, then
pa.array(list, type)converts them.Are there any user-facing changes?
A new optional module,
pyarrow.numba, available when Numba is installed. No change to existing APIs.Was AI used for this PR?
In accordance to the AI generation guidelines, please disclose below whether and how AI was used in this PR.
PR code and description written by:
Reviewed before submission by: