From 81bedcccaa14bd901d25e0ac27cc352a265aa803 Mon Sep 17 00:00:00 2001 From: Alexis Placet <2400067+Alex-PLACET@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:08:12 +0100 Subject: [PATCH] feat(python): run Numba code on Arrow arrays and build arrays in it - @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 --- cpp/src/arrow/c/bridge.cc | 11 +- cpp/src/arrow/c/bridge.h | 7 + python/CMakeLists.txt | 1 + python/benchmarks/numba.py | 209 +++++++ python/benchmarks/numba_common.py | 105 ++++ python/benchmarks/numba_primitives.py | 632 ++++++++++++++++++++ python/pyarrow/conftest.py | 7 + python/pyarrow/numba/__init__.py | 160 +++++ python/pyarrow/numba/_capsule.py | 421 +++++++++++++ python/pyarrow/numba/_utils.py | 231 ++++++++ python/pyarrow/numba/array.py | 649 +++++++++++++++++++++ python/pyarrow/numba/builder.py | 304 ++++++++++ python/pyarrow/numba/builder_types.py | 151 +++++ python/pyarrow/numba/poolbuffer.py | 428 ++++++++++++++ python/pyarrow/src/arrow/python/numba.cc | 125 ++++ python/pyarrow/src/arrow/python/numba.h | 65 +++ python/pyarrow/tests/numba_util.py | 101 ++++ python/pyarrow/tests/test_numba.py | 381 ++++++++++++ python/pyarrow/tests/test_numba_builder.py | 524 +++++++++++++++++ python/pyarrow/tests/test_numba_capsule.py | 397 +++++++++++++ python/pyarrow/tests/test_numba_helpers.py | 153 +++++ python/pyproject.toml | 3 + 22 files changed, 5062 insertions(+), 3 deletions(-) create mode 100644 python/benchmarks/numba.py create mode 100644 python/benchmarks/numba_common.py create mode 100644 python/benchmarks/numba_primitives.py create mode 100644 python/pyarrow/numba/__init__.py create mode 100644 python/pyarrow/numba/_capsule.py create mode 100644 python/pyarrow/numba/_utils.py create mode 100644 python/pyarrow/numba/array.py create mode 100644 python/pyarrow/numba/builder.py create mode 100644 python/pyarrow/numba/builder_types.py create mode 100644 python/pyarrow/numba/poolbuffer.py create mode 100644 python/pyarrow/src/arrow/python/numba.cc create mode 100644 python/pyarrow/src/arrow/python/numba.h create mode 100644 python/pyarrow/tests/numba_util.py create mode 100644 python/pyarrow/tests/test_numba.py create mode 100644 python/pyarrow/tests/test_numba_builder.py create mode 100644 python/pyarrow/tests/test_numba_capsule.py create mode 100644 python/pyarrow/tests/test_numba_helpers.py diff --git a/cpp/src/arrow/c/bridge.cc b/cpp/src/arrow/c/bridge.cc index 184be3ab8eb9..78a19c054e61 100644 --- a/cpp/src/arrow/c/bridge.cc +++ b/cpp/src/arrow/c/bridge.cc @@ -689,19 +689,24 @@ struct ArrayExporter { } // namespace -Status ExportArray(const Array& array, struct ArrowArray* out, +Status ExportArray(std::shared_ptr array, struct ArrowArray* out, struct ArrowSchema* out_schema) { SchemaExportGuard guard(out_schema); if (out_schema != nullptr) { - RETURN_NOT_OK(ExportType(*array.type(), out_schema)); + RETURN_NOT_OK(ExportType(*array->type, out_schema)); } ArrayExporter exporter; - RETURN_NOT_OK(exporter.Export(array.data())); + RETURN_NOT_OK(exporter.Export(std::move(array))); exporter.Finish(out); guard.Detach(); return Status::OK(); } +Status ExportArray(const Array& array, struct ArrowArray* out, + struct ArrowSchema* out_schema) { + return ExportArray(array.data(), out, out_schema); +} + Status ExportRecordBatch(const RecordBatch& batch, struct ArrowArray* out, struct ArrowSchema* out_schema) { // XXX perhaps bypass ToStructArray() for speed? diff --git a/cpp/src/arrow/c/bridge.h b/cpp/src/arrow/c/bridge.h index 78860e0650e7..f30850d7100c 100644 --- a/cpp/src/arrow/c/bridge.h +++ b/cpp/src/arrow/c/bridge.h @@ -73,6 +73,13 @@ ARROW_EXPORT Status ExportArray(const Array& array, struct ArrowArray* out, struct ArrowSchema* out_schema = NULLPTR); +/// \brief Export C++ ArrayData using the C data interface format. +/// +/// Same as the Array overload, without needing an Array wrapper. +ARROW_EXPORT +Status ExportArray(std::shared_ptr array, struct ArrowArray* out, + struct ArrowSchema* out_schema = NULLPTR); + /// \brief Export C++ RecordBatch using the C data interface format. /// /// The record batch is exported as if it were a struct array. diff --git a/python/CMakeLists.txt b/python/CMakeLists.txt index f38abce98a41..09231603b1f9 100644 --- a/python/CMakeLists.txt +++ b/python/CMakeLists.txt @@ -399,6 +399,7 @@ set(PYARROW_CPP_SRCS ${PYARROW_CPP_SOURCE_DIR}/inference.cc ${PYARROW_CPP_SOURCE_DIR}/io.cc ${PYARROW_CPP_SOURCE_DIR}/ipc.cc + ${PYARROW_CPP_SOURCE_DIR}/numba.cc ${PYARROW_CPP_SOURCE_DIR}/numpy_convert.cc ${PYARROW_CPP_SOURCE_DIR}/numpy_init.cc ${PYARROW_CPP_SOURCE_DIR}/numpy_to_arrow.cc diff --git a/python/benchmarks/numba.py b/python/benchmarks/numba.py new file mode 100644 index 000000000000..adfdb3911017 --- /dev/null +++ b/python/benchmarks/numba.py @@ -0,0 +1,209 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Compiled (Numba) code reading and building Arrow arrays, per type.""" + +from typing import ClassVar + +import pyarrow as pa +from benchmarks.numba_common import N, dense_values, numba_module, require, values + +READ_TYPES = { + "int8": pa.int8(), "int16": pa.int16(), + "int32": pa.int32(), "int64": pa.int64(), + "uint8": pa.uint8(), "uint16": pa.uint16(), + "uint32": pa.uint32(), "uint64": pa.uint64(), + "float32": pa.float32(), "float64": pa.float64(), + "date32": pa.date32(), "date64": pa.date64(), + "time32_s": pa.time32("s"), "time64_us": pa.time64("us"), + "timestamp_us": pa.timestamp("us"), "duration_s": pa.duration("s"), + "bool": pa.bool_(), + "decimal128": pa.decimal128(20, 2), + "string": pa.string(), "large_string": pa.large_string(), + "binary": pa.binary(), "large_binary": pa.large_binary(), + "fixed_size_binary": pa.binary(8), +} + +BUILD_TYPES = { + "int8": "Int8Builder", "int16": "Int16Builder", + "int32": "Int32Builder", "int64": "Int64Builder", + "uint8": "UInt8Builder", "uint16": "UInt16Builder", + "uint32": "UInt32Builder", "uint64": "UInt64Builder", + "float32": "Float32Builder", "float64": "Float64Builder", + "bool": "BoolBuilder", + "string": "StringBuilder", "large_string": "LargeStringBuilder", + "binary": "BinaryBuilder", "large_binary": "LargeBinaryBuilder", +} + +BYTES_BUILDERS = ("string", "binary", "large_string", "large_binary") + + +class NumbaRead: + """Read one array of every supported type, element by element.""" + + param_names: ClassVar[list[str]] = ["arrow_type"] + params: ClassVar[list[list[str]]] = [sorted(READ_TYPES)] + + def setup(self, arrow_type): + nb = numba_module() + from pyarrow.numba import decimal_to_float, string_len + from pyarrow.numba._utils import _is_var_width + + self.array = pa.array(values(arrow_type), type=READ_TYPES[arrow_type]) + + if arrow_type == "bool": + @nb.njit + def scan(a): + n = 0 + for i in range(len(a)): + if a[i] is not None and a[i]: + n += 1 + return n + elif pa.types.is_decimal(READ_TYPES[arrow_type]): + @nb.njit + def scan(a): + total = 0.0 + for i in range(len(a)): + if a[i] is not None: + total += decimal_to_float(a[i], 2) + return total + elif _is_var_width(READ_TYPES[arrow_type]): + @nb.njit + def scan(a): + n = 0 + for i in range(len(a)): + v = a[i] + if v.valid: + n += string_len(v) + return n + else: + @nb.njit + def scan(a): + total = 0 + nulls = 0 + for i in range(len(a)): + if a[i] is None: + nulls += 1 + else: + total += a[i] + return total, nulls + + self.func = scan + self.func(self.array) # compile outside the measured region + + def time_read(self, arrow_type): + self.func(self.array) + + +class NumbaBuild: + """Append one million values of every builder type, then finish.""" + + param_names: ClassVar[list[str]] = ["arrow_type"] + params: ClassVar[list[list[str]]] = [sorted(BUILD_TYPES)] + + def setup(self, arrow_type): + nb = numba_module() + import pyarrow.numba as apn + + builder_cls = getattr(apn, BUILD_TYPES[arrow_type]) + + if arrow_type in BYTES_BUILDERS: + @nb.njit + def build(n): + b = builder_cls() + b.reserve(n) + for i in range(n): + if i % 3: + b.append(b"abcdefgh") + else: + b.append(None) + return b.finish() + elif arrow_type == "bool": + @nb.njit + def build(n): + b = builder_cls() + b.reserve(n) + for i in range(n): + if i % 3: + b.append(i % 2 == 0) + else: + b.append(None) + return b.finish() + else: + # one append per element, no arithmetic in the loop: the append + # (reserve check, cast, store) is what is being measured + @nb.njit + def build(n): + b = builder_cls() + b.reserve(n) + for i in range(n): + if i % 3: + b.append(i) + else: + b.append(None) + return b.finish() + + self.func = build + self.func(16) # compile outside the measured region + + def time_build(self, arrow_type): + self.func(N) + + +class NumbaBuildBulk: + """Append one million values of every fixed-width type in one batch. + + Bytes types are absent because a bulk append needs one length per + element, not a flat array. + """ + + param_names: ClassVar[list[str]] = ["arrow_type"] + params: ClassVar[list[list[str]]] = [ + sorted(t for t in BUILD_TYPES if t not in BYTES_BUILDERS) + ] + + def setup(self, arrow_type): + require("bulk_builders") + nb = numba_module() + import pyarrow.numba as apn + + builder_cls = getattr(apn, BUILD_TYPES[arrow_type]) + self.values = dense_values() + + if arrow_type == "bool": + @nb.njit + def build(values): + b = builder_cls() + b.append_many(values) + return b.finish() + + self.func = build + self.arg = self.values % 3 == 0 + else: + @nb.njit + def build(values): + b = builder_cls() + b.append_many(values) + return b.finish() + + self.func = build + self.arg = self.values.astype(arrow_type) + + self.func(self.arg[:16]) # compile outside the measured region + + def time_build(self, arrow_type): + self.func(self.arg) diff --git a/python/benchmarks/numba_common.py b/python/benchmarks/numba_common.py new file mode 100644 index 000000000000..39f527ff255c --- /dev/null +++ b/python/benchmarks/numba_common.py @@ -0,0 +1,105 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Shared sizes and data for the Numba benchmarks.""" + +from decimal import Decimal + +import numpy as np + +import pyarrow as pa + +N = 1 << 20 + +# The optional features this revision implements; ``require`` skips the +# benchmarks of the others. +FEATURES = frozenset() + + +class Unavailable(NotImplementedError): + """A benchmark skipped on purpose (asv skips a setup raising it).""" + + +def require(feature): + if feature is not None and feature not in FEATURES: + raise Unavailable(f"{feature} is not in this revision") + + +def numba_module(): + """``numba``, after importing ``pyarrow.numba`` to register its types.""" + try: + import numba + except ImportError: + raise Unavailable("numba is not installed") + import pyarrow.numba # noqa: F401 (registers the array and builder types) + return numba + + +def nullable_ints(n=N): + """Every third element null.""" + data = np.arange(n, dtype=np.int64) + return pa.array(np.where(np.arange(n) % 3, data, 0), + mask=np.arange(n) % 3 == 0) + + +def dense_ints(n=N): + """No null bitmap at all.""" + return pa.array(np.arange(n, dtype=np.int64)) + + +def dense_values(n=N): + """A raw ``int64`` array: what a bulk append consumes.""" + return np.arange(n, dtype=np.int64) + + +def null_mask(n=N): + """One ``bool_`` per element: False marks a null, every third one.""" + return (np.arange(n) % 3) != 0 + + +def strings(n=N): + return pa.array([b"abcdefgh" if i % 3 else None for i in range(n)], + type=pa.string()) + + +def chunked_strings(n=N): + source = strings(n) + return pa.chunked_array([source[: n // 2], source[n // 2:]]) + + +def chunked_ints(n=N): + data = np.arange(n, dtype=np.int64) + return pa.chunked_array([pa.array(data[: n // 2]), pa.array(data[n // 2:])], + type=pa.int64()) + + +def batch(n=N): + return pa.record_batch({"x": pa.array(np.arange(n, dtype=np.int64))}) + + +def values(arrow_type, n=N): + """One million values of *arrow_type*, null every third.""" + if arrow_type == "bool": + return [(i % 2 == 0) if i % 3 else None for i in range(n)] + if arrow_type == "decimal128": + return [Decimal(i % 10000) / 100 if i % 3 else None for i in range(n)] + if arrow_type == "fixed_size_binary": + return [b"abcdefgh" if i % 3 else None for i in range(n)] + if arrow_type in ("string", "large_string", "binary", "large_binary"): + return [b"abcdefgh"[: (i % 8) + 1] if i % 3 else None + for i in range(n)] + return [i % 100 if i % 3 else None for i in range(n)] diff --git a/python/benchmarks/numba_primitives.py b/python/benchmarks/numba_primitives.py new file mode 100644 index 000000000000..60dc11168d5e --- /dev/null +++ b/python/benchmarks/numba_primitives.py @@ -0,0 +1,632 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""One loop per primitive: where the per-element time actually goes.""" + +from __future__ import annotations + +import functools +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, ClassVar + +import numpy as np +from numpy.typing import NDArray + +import pyarrow as pa +import pyarrow.compute as pc +from benchmarks.numba_common import ( + N, + Unavailable, + batch, + chunked_ints, + chunked_strings, + dense_ints, + dense_values, + null_mask, + nullable_ints, + numba_module, + require, + strings, +) + +if TYPE_CHECKING: + from polars import Series + + from pyarrow.tests.numba_util import ArrayProducer, StreamProducer + +READ_OPS = ( + "getitem_optional", + "getitem_dense", + "getitem_producer", + "is_valid", + "string_len", + "chunked", + "chunked_string", + "batch_column", +) +BUILD_OPS = ( + "append_int", + "append_null", + "append_bool", + "append_bytes", + "append_view", + "reserve", + "append_no_reserve", + "append_many", + "append_many_masked", + "append_many_nulls", + "append_many_strings", + "append_many_equivalent", +) +CALL_PRODUCERS = ( + "pyarrow_dense", + "pyarrow_nullable", + "chunked_array", + "table", + "record_batch", + "array_capsule", + "stream_capsule", + "batch_stream", + "polars_series", + "from_any", + "build_tiny", +) + + +# The feature each gated parameter needs. +READ_FEATURES = { + "chunked": "columns", + "chunked_string": "columns", + "batch_column": "columns", +} +BUILD_FEATURES = { + "append_many": "bulk_builders", + "append_many_masked": "bulk_builders", + "append_many_nulls": "bulk_builders", + "append_many_strings": "bulk_builders", +} +CALL_FEATURES = { + "chunked_array": "columns", + "table": "columns", + "record_batch": "columns", +} + + +@functools.cache +def _kernels() -> dict[str, Callable[..., Any]]: + """The compiled loops, compiled once for the whole run.""" + nb = numba_module() + import pyarrow.numba as apn + from pyarrow.numba import is_valid, string_len + from pyarrow.tests.numba_util import total + + @nb.njit + def loop_getitem_optional(a: pa.Array | ArrayProducer) -> tuple[int, int]: + acc = 0 + nulls = 0 + for i in range(len(a)): + v = a[i] + if v is None: + nulls += 1 + else: + acc += v + return acc, nulls + + @nb.njit + def loop_is_valid(a: pa.Array) -> int: + acc = 0 + for i in range(len(a)): + if is_valid(a, i): + acc += a[i] + return acc + + @nb.njit + def loop_string_len(a: pa.Array | pa.ChunkedArray) -> int: + acc = 0 + for i in range(len(a)): + v = a[i] + if v.valid: + acc += string_len(v) + return acc + + @nb.njit + def loop_chunked(a: pa.ChunkedArray) -> int: + acc = 0 + for i in range(len(a)): + acc += a[i] + return acc + + @nb.njit + def loop_batch_column(b: pa.RecordBatch) -> int: + column = b.column(0) + acc = 0 + for i in range(len(b)): + acc += column[i] + return acc + + @nb.njit + def loop_built(n: int) -> int: + b = apn.Int64Builder() + b.reserve(n) + for i in range(n): + b.append(i % 100) + a = b.finish() + acc = 0 + for i in range(len(a)): + acc += a[i] + return acc + + return { + "loop_getitem_optional": loop_getitem_optional, + "loop_is_valid": loop_is_valid, + "loop_string_len": loop_string_len, + "loop_chunked": loop_chunked, + "loop_batch_column": loop_batch_column, + "loop_built": loop_built, + "total": total, + } + + +@functools.cache +def _read_loops() -> dict[str, tuple[Callable[..., Any], Callable[[], object]]]: + """op -> (jitted function, argument factory)""" + kernels = _kernels() + + def producer() -> ArrayProducer: + from pyarrow.tests.numba_util import ArrayProducer + + return ArrayProducer(dense_ints()) + + return { + "getitem_optional": (kernels["loop_getitem_optional"], nullable_ints), + "getitem_dense": (kernels["loop_getitem_optional"], dense_ints), + # a foreign typed nullable array without a bitmap: the guarded load + "getitem_producer": (kernels["loop_getitem_optional"], producer), + "is_valid": (kernels["loop_is_valid"], nullable_ints), + "string_len": (kernels["loop_string_len"], strings), + "chunked": (kernels["loop_chunked"], chunked_ints), + "chunked_string": (kernels["loop_string_len"], chunked_strings), + "batch_column": (kernels["loop_batch_column"], batch), + } + + +class ReadPrimitives: + """Per-element cost of each read accessor, ns per element.""" + + param_names: ClassVar[list[str]] = ["op"] + params: ClassVar[list[list[str]]] = [list(READ_OPS)] + + def setup(self, op: str) -> None: + require(READ_FEATURES.get(op)) + self.func, factory = _read_loops()[op] + self.arg_factory = factory + self.arg = factory() + self.func(self.arg) # compile outside the timed region + + def time_read(self, op: str) -> None: + self.func(self.arg) + + +@functools.cache +def _build_loops() -> dict[str, tuple[Callable[..., Any], Callable[[], object]]]: + """op -> (jitted function, argument factory)""" + nb = numba_module() + import pyarrow.numba as apn + + @nb.njit + def append_int(n: int) -> pa.Array: + b = apn.Int64Builder() + b.reserve(n) + for i in range(n): + b.append(i % 100) + return b.finish() + + @nb.njit + def append_null(n: int) -> pa.Array: + b = apn.Int64Builder() + b.reserve(n) + for i in range(n): + b.append(None) + return b.finish() + + @nb.njit + def append_bool(n: int) -> pa.Array: + b = apn.BoolBuilder() + b.reserve(n) + for i in range(n): + b.append(i % 3 == 0) + return b.finish() + + @nb.njit + def append_bytes(n: int) -> pa.Array: + b = apn.StringBuilder() + b.reserve(n) + for _ in range(n): + b.append(b"abcdefgh") + return b.finish() + + @nb.njit + def append_view(source: pa.Array) -> pa.Array: + b = apn.StringBuilder() + b.reserve(len(source)) + for i in range(len(source)): + b.append(source[i]) + return b.finish() + + @nb.njit + def reserve(n: int) -> pa.Array: + b = apn.Int64Builder() + b.reserve(n) + return b.finish() + + @nb.njit + def no_reserve(n: int) -> pa.Array: + b = apn.Int64Builder() + for i in range(n): + b.append(i % 100) + return b.finish() + + @nb.njit + def append_many(values: NDArray[np.int64]) -> pa.Array: + b = apn.Int64Builder() + b.append_many(values) + return b.finish() + + @nb.njit + def append_many_masked( + values: NDArray[np.int64], mask: NDArray[np.bool_] + ) -> pa.Array: + b = apn.Int64Builder() + b.append_many(values, mask) + return b.finish() + + @nb.njit + def append_many_nulls(n: int) -> pa.Array: + b = apn.Int64Builder() + b.append_many_nulls(n) + return b.finish() + + @nb.njit + def append_many_strings(a: pa.Array) -> pa.Array: + b = apn.StringBuilder() + b.append_many(a) + return b.finish() + + @nb.njit + def append_many_equivalent(values: NDArray[np.int64]) -> pa.Array: + """The per-element work append_many replaces, for the same result.""" + b = apn.Int64Builder() + b.reserve(len(values)) + for i in range(len(values)): + if i % 3: + b.append(values[i]) + else: + b.append(None) + return b.finish() + + return { + "append_int": (append_int, lambda: N), + "append_null": (append_null, lambda: N), + "append_bool": (append_bool, lambda: N), + "append_bytes": (append_bytes, lambda: N), + "append_view": (append_view, strings), + "reserve": (reserve, lambda: N), + "append_no_reserve": (no_reserve, lambda: N), + "append_many": (append_many, dense_values), + "append_many_strings": (append_many_strings, strings), + "append_many_masked": ( + append_many_masked, + lambda: (dense_values(), null_mask()), + ), + "append_many_nulls": (append_many_nulls, lambda: N), + "append_many_equivalent": (append_many_equivalent, dense_values), + } + + +class BuildPrimitives: + """Per-element cost of each builder method, ns per element.""" + + param_names: ClassVar[list[str]] = ["op"] + params: ClassVar[list[list[str]]] = [list(BUILD_OPS)] + + def setup(self, op: str) -> None: + require(BUILD_FEATURES.get(op)) + self.func, factory = _build_loops()[op] + self.arg_factory = factory + self.arg = factory() + self.func(*self._call_args()) # compile, and time the growth path once + + def _call_args(self) -> tuple[object, ...]: + return self.arg if isinstance(self.arg, tuple) else (self.arg,) + + def time_build(self, op: str) -> None: + self.func(*self._call_args()) + + +class DerivedBuild: + """Same conditional square, including output allocation and mask packing.""" + + param_names: ClassVar[list[str]] = ["method"] + params: ClassVar[list[list[str]]] = [ + ["branching", "flagged", "generated", "numpy_bulk", "arrow"] + ] + + def setup(self, method: str) -> None: + require( + "bulk_builders" + if method in ("flagged", "generated", "numpy_bulk") + else None + ) + nb = numba_module() + import pyarrow.numba as apn + + @nb.njit + def square_at( + i: int, values: NDArray[np.int64], limit: int + ) -> tuple[int, bool]: + v = values[i] + return v * v, v <= limit + + @nb.njit + def branching(values: NDArray[np.int64]) -> pa.Array: + b = apn.Int64Builder() + b.reserve(len(values)) + for v in values: + if v <= 500: + b.append(v * v) + else: + b.append(None) + return b.finish() + + @nb.njit + def flagged(values: NDArray[np.int64]) -> pa.Array: + b = apn.Int64Builder() + b.reserve(len(values)) + for v in values: + b.append(v * v, v <= 500) + return b.finish() + + @nb.njit + def generated(values: NDArray[np.int64]) -> pa.Array: + b = apn.Int64Builder() + b.append_generated(len(values), square_at, (values, 500)) + return b.finish() + + @nb.njit + def bulk(values: NDArray[np.int64], valid: NDArray[np.bool_]) -> pa.Array: + b = apn.Int64Builder() + b.append_many(values, valid) + return b.finish() + + def numpy_bulk(values: NDArray[np.int64]) -> pa.Array: + return bulk(values * values, values <= 500) + + def arrow(values: pa.Array) -> pa.Array: + return pc.if_else( + pc.less_equal(values, 500), pc.multiply(values, values), None + ) + + values = np.random.default_rng(0).integers(0, 1000, N) + self.values = pa.array(values) if method == "arrow" else values + self.func = { + "branching": branching, + "flagged": flagged, + "generated": generated, + "numpy_bulk": numpy_bulk, + "arrow": arrow, + }[method] + # Compile outside the timed region and verify equal consumer results. + result = self.func(self.values[:17]) + expected = [int(v * v) if v <= 500 else None for v in values[:17]] + assert result.to_pylist() == expected + + def time_build(self, method: str) -> None: + self.func(self.values) + + def peakmem_build(self, method: str) -> None: + self.func(self.values) + + +@functools.cache +def _call_cases() -> dict[str, tuple[Callable[..., Any], Callable[[], object]]]: + """producer -> (callable, argument factory); imports the producer libs.""" + import importlib.util + + nb = numba_module() + import pyarrow.numba as apn + from pyarrow.numba import from_any + + kernels = _kernels() + total = kernels["total"] + + def polars_series() -> Series: + if importlib.util.find_spec("polars") is None: + raise Unavailable("polars is not installed") + import polars as pl + + from pyarrow.numba import register_producer + + register_producer(pl.Series) + return pl.Series("x", [1, 2, 3]) + + def array_producer() -> ArrayProducer: + from pyarrow.tests.numba_util import ArrayProducer + + return ArrayProducer(dense_ints(3)) + + def stream_producer() -> StreamProducer: + from pyarrow.tests.numba_util import StreamProducer + + return StreamProducer(pa.chunked_array([[1, 2, 3]])) + + def batch_stream() -> StreamProducer: + from pyarrow.tests.numba_util import StreamProducer + + return StreamProducer(pa.table({"x": [1, 2, 3]})) + + @nb.njit + def batch_total(b: pa.RecordBatch) -> int: + return total(b.column(0)) + + @nb.njit + def build_tiny(n: int) -> pa.Array: + b = apn.Int64Builder() + for i in range(n): + b.append(i + 1) + return b.finish() + + return { + "pyarrow_dense": (total, lambda: pa.array([1, 2, 3])), + "pyarrow_nullable": (total, lambda: pa.array([1, None, 3], type=pa.int64())), + "chunked_array": ( + total, + lambda: pa.chunked_array([[1], [2, 3]], type=pa.int64()), + ), + "table": (total, lambda: pa.table({"x": [1, 2, 3]})), + "record_batch": ( + batch_total, + lambda: pa.record_batch( + { + "x": pa.array([1, 2, 3]), + "y": pa.array([1.5, 2.5, 3.5]), + "z": pa.array(["a", "b", "c"]), + } + ), + ), + "array_capsule": (total, array_producer), + "stream_capsule": (total, stream_producer), + "batch_stream": (total, batch_stream), + "polars_series": (total, polars_series), + "from_any": (from_any, polars_series), + # ctor + finish + box of a three-element array + "build_tiny": (build_tiny, lambda: 3), + } + + +class CallOverhead: + """Python glue per call: typeof + unbox + box, microseconds.""" + + param_names: ClassVar[list[str]] = ["producer"] + params: ClassVar[list[list[str]]] = [list(CALL_PRODUCERS)] + + def setup(self, producer: str) -> None: + require(CALL_FEATURES.get(producer)) + self.func, factory = _call_cases()[producer] + self.arg = factory() + self.func(self.arg) # compile outside the measured region + + def time_call(self, producer: str) -> None: + self.func(self.arg) + + +@functools.cache +def _boolean_loops() -> dict[str, Callable[..., Any]]: + nb = numba_module() + + @nb.njit + def sum_values(a: pa.Array | pa.ChunkedArray) -> int | None: + return a.sum() + + @nb.njit + def count_values(a: pa.Array | pa.ChunkedArray) -> int: + return a.count() + + @nb.njit + def any_value(a: pa.Array | pa.ChunkedArray) -> bool | None: + return a.any() + + @nb.njit + def all_values(a: pa.Array | pa.ChunkedArray) -> bool | None: + return a.all() + + @nb.njit + def sum_nulls(a: pa.Array | pa.ChunkedArray) -> tuple[int, int]: + total = a.sum() + return (0 if total is None else total), len(a) - a.count() + + return { + "sum": sum_values, + "count": count_values, + "any": any_value, + "all": all_values, + "sum_nulls": sum_nulls, + } + + +def _boolean_input(dataset: str) -> pa.Array | pa.ChunkedArray: + n = N + 7 if dataset == "slice" else N + indices = np.arange(n) + values = indices % 2 == 0 + mask = None + if dataset in ("nullable", "slice", "chunked"): + mask = indices % 3 == 0 + elif dataset == "all_true": + values[:] = True + elif dataset == "all_false": + values[:] = False + elif dataset == "all_null": + mask = np.ones(n, dtype=np.bool_) + arg = pa.array(values, mask=mask) + if dataset == "slice": + arg = arg.slice(7, N) + elif dataset == "chunked": + arg = pa.chunked_array( + [arg[i * N // 8:(i + 1) * N // 8] for i in range(8)] + ) + return arg + + +_ARROW_BOOLEAN: dict[str, Callable[[Any], object]] = { + "sum": lambda a: pc.sum(a).as_py(), + "count": lambda a: pc.count(a).as_py(), + "any": lambda a: pc.any(a).as_py(), + "all": lambda a: pc.all(a).as_py(), + "sum_nulls": lambda a: (pc.sum(a, min_count=0).as_py(), a.null_count), +} + + +class BooleanReductions: + """Word-at-a-time reductions, including the Python/native boundary.""" + + param_names: ClassVar[list[str]] = ["operation", "dataset"] + params: ClassVar[list[list[str]]] = [ + ["sum", "count", "any", "all", "sum_nulls"], + ["dense", "nullable", "slice", "chunked", "all_true", "all_false", "all_null"], + ] + + def setup(self, operation: str, dataset: str) -> None: + require("boolean_reductions") + self.arg = _boolean_input(dataset) + self.func = _boolean_loops()[operation] + assert self.func(self.arg) == _ARROW_BOOLEAN[operation](self.arg) + + def time_reduce(self, operation: str, dataset: str) -> None: + self.func(self.arg) + + +class ArrowBooleanReductions: + """The pyarrow.compute reference for ``BooleanReductions``.""" + + param_names: ClassVar[list[str]] = BooleanReductions.param_names + params: ClassVar[list[list[str]]] = BooleanReductions.params + + def setup(self, operation: str, dataset: str) -> None: + self.arg = _boolean_input(dataset) + self.func = _ARROW_BOOLEAN[operation] + + def time_reduce(self, operation: str, dataset: str) -> None: + self.func(self.arg) diff --git a/python/pyarrow/conftest.py b/python/pyarrow/conftest.py index e2595dc2d9b0..b83927c95f8a 100644 --- a/python/pyarrow/conftest.py +++ b/python/pyarrow/conftest.py @@ -243,6 +243,13 @@ def _cuda_is_available(): if 'pyarrow/cuda' in str(collection_path): return not _cuda_is_available() + if 'pyarrow/numba' in str(collection_path): + try: + import pyarrow.numba # noqa + return False + except ImportError: + return True + if 'pyarrow/fs' in str(collection_path): try: from pyarrow.fs import S3FileSystem # noqa diff --git a/python/pyarrow/numba/__init__.py b/python/pyarrow/numba/__init__.py new file mode 100644 index 000000000000..843e7c4e1ba3 --- /dev/null +++ b/python/pyarrow/numba/__init__.py @@ -0,0 +1,160 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Run Numba compiled code on Arrow arrays, and build Arrow arrays in it. + +Reading is zero-copy: the producer's buffers are passed to the compiled code, +never copied. Building appends into pool-backed buffers and hands them to +Arrow on ``finish()``. The null test is emitted only for arrays that have +nulls. + +>>> import numba as nb +>>> import pyarrow as pa +>>> @nb.njit +... def sum_and_nulls(a): +... total = 0 +... nulls = 0 +... for i in range(len(a)): +... if a[i] is None: +... nulls += 1 +... else: +... total += a[i] +... return total, nulls +>>> sum_and_nulls(pa.array([2, 3, None] * 50)) +(250, 50) + +Element types +------------- +===================== ================================================= +Arrow type ``a[i]`` in ``@njit`` +===================== ================================================= +int8 .. int64 ``Optional[int]`` +uint8 .. uint64 ``Optional[int]`` +float32, float64 ``Optional[float]`` +date32/64, time32/64 storage integer (days, ms, s, us) +timestamp, duration storage integer +string, binary, ``StringView``: ``string_len(v)``, ``v.valid``, +fixed_size_binary boxes to bytes +decimal128 ``(high, low)``, exact; see ``decimal_to_float`` +bool ``Optional[bool]``, read from the bit-packed buffer +===================== ================================================= + +Any other type (nested, dictionary, decimal256) raises ``TypeError`` when it +is first seen, rather than reading the wrong buffer. + +Producers +--------- +pyarrow arrays are accepted as they are. Anything else implementing +``__arrow_c_array__`` or ``__arrow_c_stream__`` is accepted once its class is +registered, or per call through ``from_any()`` which needs no registration:: + + >>> from pyarrow.numba import register_producer + >>> register_producer(polars.Series) # doctest: +SKIP + +Limits +------ +* A ``StringView`` carries its own validity as ``v.valid``: a null element + still yields a view, so nothing silently reads a null's offsets. +* A stream yielding more than one chunk raises; ``from_any()`` concatenates, + which copies. +* ``decimal128`` has no 128-bit arithmetic in ``@njit``: the two words are + exact, ``decimal_to_float()`` is a double. ``+`` on two ``(high, low)`` + pairs concatenates the tuples, it does not add the values. +* Returning an array *argument* raises + ``NotImplementedError`` at compile time: its buffers are released when the + call returns. Return a built array instead. +* An array argument, and every ``StringView`` read from + one, borrows the caller's buffers for the duration of the + call only. Keeping one past the call, in a ``numba.typed.List``, a typed + ``Dict`` or a jitclass, leaves it pointing at released memory: a later read + returns garbage or crashes. Keep the values themselves, or build an array. + +Building +-------- +One builder per supported type: the eleven scalar builders plus +``StringBuilder``/``LargeStringBuilder``/``BinaryBuilder``/``LargeBinaryBuilder``. +A var-width builder keeps ``[validity, offsets, data]`` and copies each value +with one memcpy. + +Builders and built arrays are reference-counted by Numba's runtime: an +unfinished builder, or a built array that is not returned, is freed with its +last reference, and a builder may be passed to or returned from other compiled +functions. ``finish()`` hands the buffers to the array and leaves the builder +spent: any later ``append``, ``reserve`` or ``finish`` raises ``RuntimeError``. +A built array can be returned to Python once. + +>>> from pyarrow.numba import Float64Builder +>>> @nb.njit +... def build(): +... b = Float64Builder() +... b.reserve(3) +... b.append(1.5) +... b.append(None) +... return b.finish() +>>> build().to_pylist() +[1.5, None] +""" + +from __future__ import annotations + +from ._utils import array_from as from_any +from .array import decimal_to_float, is_valid, register_producer, string_len +from .builder import ( + BinaryBuilder, + BoolBuilder, + Float32Builder, + Float64Builder, + Int8Builder, + Int16Builder, + Int32Builder, + Int64Builder, + LargeBinaryBuilder, + LargeStringBuilder, + StringBuilder, + UInt8Builder, + UInt16Builder, + UInt32Builder, + UInt64Builder, +) + +__all__ = [ + "BinaryBuilder", + "BoolBuilder", + "Float32Builder", + "Float64Builder", + "Int8Builder", + "Int16Builder", + "Int32Builder", + "Int64Builder", + "LargeBinaryBuilder", + "LargeStringBuilder", + "StringBuilder", + "UInt8Builder", + "UInt16Builder", + "UInt32Builder", + "UInt64Builder", + "decimal_to_float", + "from_any", + "is_valid", + "register_producer", + "string_len", +] + + +def _register() -> bool: + """Entry point: importing this module is what registers the extension.""" + return True diff --git a/python/pyarrow/numba/_capsule.py b/python/pyarrow/numba/_capsule.py new file mode 100644 index 000000000000..c04e98f46af5 --- /dev/null +++ b/python/pyarrow/numba/_capsule.py @@ -0,0 +1,421 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + + +"""Arrow C data interface: structs, capsules, and ownership. + +Everything here is ctypes on purpose: the compiled code must read a producer's +buffers without pyarrow building an object per call. +""" + +from __future__ import annotations + +import ctypes +from collections.abc import Hashable +from functools import cache +from typing import TypeVar + +import pyarrow as pa + +_StructT = TypeVar("_StructT", bound=ctypes.Structure) + + +class ArrowSchema(ctypes.Structure): + """``ArrowSchema``: the C data interface's type descriptor.""" + + _fields_ = [ + ("format", ctypes.c_char_p), + ("name", ctypes.c_char_p), + ("metadata", ctypes.c_char_p), + ("flags", ctypes.c_int64), + ("n_children", ctypes.c_int64), + ("children", ctypes.c_void_p), + ("dictionary", ctypes.c_void_p), + ("release", ctypes.c_void_p), + ("private_data", ctypes.c_void_p), + ] + + +class ArrowArray(ctypes.Structure): + """``ArrowArray``: the C data interface's buffer descriptor. + + Field order and widths must match the Numba struct model in ``array.py``: + ten word-sized fields, 80 bytes on a 64-bit platform. + """ + + _fields_ = [ + ("length", ctypes.c_int64), + ("null_count", ctypes.c_int64), + ("offset", ctypes.c_int64), + ("n_buffers", ctypes.c_int64), + ("n_children", ctypes.c_int64), + ("buffers", ctypes.POINTER(ctypes.c_void_p)), + ("children", ctypes.c_void_p), + ("dictionary", ctypes.c_void_p), + ("release", ctypes.c_void_p), + ("private_data", ctypes.c_void_p), + ] + + +class ArrowArrayStream(ctypes.Structure): + """``ArrowArrayStream``: the C stream interface's vtable.""" + + _fields_ = [ + ("get_schema", ctypes.c_void_p), + ("get_next", ctypes.c_void_p), + ("get_last_error", ctypes.c_void_p), + ("release", ctypes.c_void_p), + ("private_data", ctypes.c_void_p), + ] + + +# every C struct's release callback takes a pointer to that struct +Release = ctypes.CFUNCTYPE(None, ctypes.c_void_p) +StreamGetSchema = ctypes.CFUNCTYPE( + ctypes.c_int, ctypes.POINTER(ArrowArrayStream), ctypes.POINTER(ArrowSchema)) +StreamGetNext = ctypes.CFUNCTYPE( + ctypes.c_int, ctypes.POINTER(ArrowArrayStream), ctypes.POINTER(ArrowArray)) +StreamGetError = ctypes.CFUNCTYPE( + ctypes.c_char_p, ctypes.POINTER(ArrowArrayStream)) + +_PyCapsule_GetPointer = ctypes.pythonapi.PyCapsule_GetPointer +_PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p] +_PyCapsule_GetPointer.restype = ctypes.c_void_p + + +def no_protocol(obj: object) -> TypeError: + """``TypeError`` for an object that is not an Arrow producer. + + Parameters + ---------- + obj : object + The object that was refused. + """ + return TypeError(f"{type(obj).__name__} implements neither " + "__arrow_c_array__ nor __arrow_c_stream__") + + +def capsule_pointer(capsule: object, name: bytes) -> int: + """Address of the struct inside *capsule*, or ``TypeError`` if misnamed. + + Parameters + ---------- + capsule : object + PyCapsule holding an Arrow C struct. + name : bytes + Expected capsule name. + """ + try: + return _PyCapsule_GetPointer(capsule, name) + except ValueError: + raise TypeError( + f"expected a PyCapsule named {name.decode()!r}, " + f"got {type(capsule).__name__}") from None + + +def take(struct_type: type[_StructT], capsule: object, + name: bytes) -> _StructT: + """Copy the struct out of *capsule* and take over its release callback. + + The copy owns the buffers from here on: the producer's ``release`` is + cleared so its capsule destructor cannot free them a second time. + + Parameters + ---------- + struct_type : type[_StructT] + ctypes structure type of the struct. + capsule : object + PyCapsule holding the struct. + name : bytes + Expected capsule name. + """ + addr = capsule_pointer(capsule, name) + struct = struct_type.from_buffer_copy( + ctypes.string_at(addr, ctypes.sizeof(struct_type))) + struct_type.from_address(addr).release = None + return struct + + +def release_struct(struct: ctypes.Structure) -> None: + """Run the struct's release callback once, then clear it. + + Parameters + ---------- + struct : ctypes.Structure + Arrow C struct to release. + """ + if struct.release: + Release(struct.release)(ctypes.addressof(struct)) + struct.release = None + + +def store_array(array: ArrowArray, addr: int) -> None: + """Copy *array* into the struct at *addr* (a Numba view's address). + + Parameters + ---------- + array : ArrowArray + Struct to copy. + addr : int + Address of the destination struct. + """ + ctypes.memmove(addr, ctypes.addressof(array), ctypes.sizeof(ArrowArray)) + + +def stream_error(stream: ArrowArrayStream) -> str: + """The producer's message for a failed stream call. + + Parameters + ---------- + stream : ArrowArrayStream + The stream whose call failed. + """ + message = (StreamGetError(stream.get_last_error)(ctypes.byref(stream)) + if stream.get_last_error else None) + return message.decode() if message else "Arrow stream failed" + + +def from_stream(capsule: object, dtype: pa.DataType) -> ArrowArray: + """The single chunk a stream capsule yields, as an ``ArrowArray``. + + The caller owns the returned struct. An empty stream yields an empty array + of *dtype*; a record-batch stream (duckdb, ibis) yields its first column. + ``TypeError`` for more than one chunk, ``ValueError`` when the stream + reports an error. + + Parameters + ---------- + capsule : object + PyCapsule holding an ``ArrowArrayStream``. + dtype : pa.DataType + Expected type of the chunk. + """ + stream = take(ArrowArrayStream, capsule, b"arrow_array_stream") + get_schema = StreamGetSchema(stream.get_schema) + get_next = StreamGetNext(stream.get_next) + + schema = ArrowSchema() + array = ArrowArray() + status = get_schema(ctypes.byref(stream), ctypes.byref(schema)) + if not status: + status = get_next(ctypes.byref(stream), ctypes.byref(array)) + error = stream_error(stream) if status else None + empty = error is None and not array.release + + has_more = False + if error is None and not empty: + extra = ArrowArray() + probe = get_next(ctypes.byref(stream), ctypes.byref(extra)) + has_more = probe == 0 and bool(extra.release) + if has_more: + release_struct(extra) + elif probe != 0: + error = stream_error(stream) + + release_struct(stream) + + if error is not None or has_more: + release_struct(array) + release_struct(schema) + if has_more: + raise TypeError( + "Arrow stream yields more than one chunk; call from_any() " + "on it to concatenate them (which copies)") + raise ValueError(error) + + if empty: + release_struct(schema) + return _exported(pa.array([], type=dtype)) + if array.n_children: + # a record-batch stream: the batch is the struct array, the column is + # what the compiled code reads. The import moves both structs. + imported_schema = pa.Schema._import_from_c(ctypes.addressof(schema)) + batch = pa.RecordBatch._import_from_c( + ctypes.addressof(array), imported_schema) + return _exported(batch.column(0)) + release_struct(schema) # the type is known at compile time + return array + + +def _exported(obj: pa.Array | pa.ChunkedArray) -> ArrowArray: + """A fresh ``ArrowArray`` owning *obj*'s buffers.""" + array = ArrowArray() + obj._export_to_c(ctypes.addressof(array)) + return array + + +@cache +def num_buffers(dtype: pa.DataType) -> int: + """How many buffers a struct of *dtype* must carry: validity, offsets, data. + + Parameters + ---------- + dtype : pa.DataType + Arrow type of the array. + """ + if (pa.types.is_string(dtype) or pa.types.is_large_string(dtype) + or pa.types.is_binary(dtype) or pa.types.is_large_binary(dtype)): + return 3 + return 2 + + +def _check_buffers(array: ArrowArray, dtype: pa.DataType) -> None: + """Refuse a struct with fewer buffers than its type needs. + + The compiled code reads the validity, offsets and data pointers by index; + a producer that exports too few would make it read past the end of the + buffer array and then dereference whatever it found. The struct is + released before raising: the caller never gets to release it. + """ + expected = num_buffers(dtype) + if array.n_buffers < expected: + release_struct(array) + raise ValueError( + f"producer exported {array.n_buffers} buffers for {dtype}, " + f"which needs {expected}") + + +def take_array_into(obj: object, addr: int, dtype: pa.DataType) -> None: + """Move *obj*'s ArrowArray into the Numba struct at *addr*. + + A ``pa.Array`` writes its struct straight out; everything else goes + through ``__arrow_c_array__`` or a single-chunk ``__arrow_c_stream__``. + Nothing is copied: the struct is moved, and the compiled code's cleanup + calls its release callback. + + Parameters + ---------- + obj : object + ``pa.Array`` or Arrow PyCapsule producer. + addr : int + Address of the destination struct. + dtype : pa.DataType + Arrow type the compiled code was typed for. + """ + if isinstance(obj, pa.Table): + obj = obj.column(0) # a Table is read as its first column + if isinstance(obj, pa.ChunkedArray): + obj = (obj.chunk(0) if obj.num_chunks + else pa.array([], type=dtype)) + if isinstance(obj, pa.Array): + # its struct is the typed one: no buffer check needed + obj._export_to_c(addr) + return + + protocol = _protocol_of(obj) + if protocol == "__arrow_c_array__": + _, array_capsule = getattr(obj, protocol)() + array = take(ArrowArray, array_capsule, b"arrow_array") + elif protocol is not None: + array = from_stream(getattr(obj, protocol)(), dtype) + else: + raise no_protocol(obj) + _check_buffers(array, dtype) + store_array(array, addr) + + +_DTYPE_CACHE: dict[tuple[type, Hashable], pa.DataType] = {} +_DTYPE_CACHE_LIMIT = 256 +_PROTOCOLS: dict[type, str | None] = {} +_PROTOCOL_NAMES = ("__arrow_c_array__", "__arrow_c_stream__") + + +def _protocol_of(obj: object) -> str | None: + """The PyCapsule protocol *obj* exports, decided once per class. + """ + kind = type(obj) + if kind not in _PROTOCOLS: + # class array, class stream, instance array, instance stream: a + # class-level miss can still be a per-instance wrapper, so ask once + _PROTOCOLS[kind] = next( + (name for source in (kind, obj) for name in _PROTOCOL_NAMES + if getattr(source, name, None) is not None), None) + return _PROTOCOLS[kind] + + +def _dtype_hint(obj: object) -> tuple[type, Hashable] | None: + """A cheap, hashable stand-in for *obj*'s Arrow type, or ``None``. + + Numba re-types every argument on every call, so reading a schema per call + would open a stream (and, for duckdb, run the query) twice per call. + + ``None`` means "cannot be cached": no ``dtype``/``types`` attribute, a + numpy object column (which says nothing about the Arrow type: two object + columns can be a string and a struct), or an unhashable hint. + """ + kind = type(obj) + if not (hasattr(kind, "dtype") or hasattr(kind, "types")): + return None + hint = getattr(obj, "dtype", None) + if hint is None: + types_ = getattr(obj, "types", None) + if types_ is None: + return None + hint = tuple(types_) + if getattr(hint, "kind", "") == "O": + return None + return (kind, hint) + + +def dtype_of(obj: object) -> pa.DataType: + """*obj*'s pyarrow DataType, read from its schema and nothing else. + + Streaming producers hand out record batches, so a one-field struct schema + means the compiled code will read that field. + + Parameters + ---------- + obj : object + Arrow PyCapsule producer. + """ + hint = _dtype_hint(obj) + if hint is not None: + try: + return _DTYPE_CACHE[hint] # TypeError for an unhashable hint + except KeyError: + pass + except TypeError: + hint = None + dtype = _dtype_of_uncached(obj) + if hint is not None: + if len(_DTYPE_CACHE) >= _DTYPE_CACHE_LIMIT: + _DTYPE_CACHE.clear() + _DTYPE_CACHE[hint] = dtype + return dtype + + +def _dtype_of_uncached(obj: object) -> pa.DataType: + # pyarrow classes have their own typeof: only registered producers get here + protocol = _protocol_of(obj) + if protocol == "__arrow_c_array__": + schema_capsule, _ = getattr(obj, protocol)() # the array is dropped + return pa.DataType._import_from_c_capsule(schema_capsule) + if protocol is None: + raise no_protocol(obj) + + handle = take(ArrowArrayStream, getattr(obj, protocol)(), + b"arrow_array_stream") + schema = ArrowSchema() + try: + status = StreamGetSchema(handle.get_schema)( + ctypes.byref(handle), ctypes.byref(schema)) + if status: + raise ValueError(stream_error(handle)) + dtype = pa.DataType._import_from_c(ctypes.addressof(schema)) + finally: + release_struct(handle) + return dtype.field(0).type if pa.types.is_struct(dtype) else dtype diff --git a/python/pyarrow/numba/_utils.py b/python/pyarrow/numba/_utils.py new file mode 100644 index 000000000000..014f7408bf99 --- /dev/null +++ b/python/pyarrow/numba/_utils.py @@ -0,0 +1,231 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +import ctypes +import functools +from collections.abc import Callable + +import llvmlite.binding +from llvmlite import ir +from numba import types as nbt +from numba.core import cgutils +from numba.core.base import BaseContext + +import pyarrow as pa + +from ._capsule import _protocol_of +from ._capsule import no_protocol as _no_protocol + + +def array_from(obj: object) -> pa.Array: + """A ``pa.Array`` for *obj*, through the Arrow PyCapsule interface. + + Zero copy: the capsules hand over the producer's buffers. Producers that + only implement ``__arrow_c_stream__`` (polars, duckdb) are read as a + one-column table; a single-chunk column keeps the buffers. + + Parameters + ---------- + obj : object + Arrow PyCapsule producer. + """ + if isinstance(obj, pa.Array): + return obj + protocol = _protocol_of(obj) + if protocol == "__arrow_c_array__": + return pa.Array._import_from_c_capsule(*getattr(obj, protocol)()) + if protocol is not None: + # a stream of record batches (duckdb) or of arrays (polars); both + # import zero copy, but combine_chunks() copies even for one chunk + chunked = pa.chunked_array(obj) + array = (chunked.chunk(0) if chunked.num_chunks == 1 + else chunked.combine_chunks()) + if pa.types.is_struct(array.type): + # a record-batch stream: one struct array, one column + array = array.field(0) + return array + raise _no_protocol(obj) + + +def _is_var_width(ty: pa.DataType) -> bool: + """True for string/binary types: elements are views, not scalars.""" + return (pa.types.is_string(ty) or pa.types.is_large_string(ty) + or pa.types.is_binary(ty) or pa.types.is_large_binary(ty) + or pa.types.is_fixed_size_binary(ty)) + + +def _arrow_type_to_nb_type(ty: pa.DataType) -> nbt.Type: + if pa.types.is_integer(ty): + return nbt.Integer(str(ty), bitwidth=ty.bit_width, + signed=pa.types.is_signed_integer(ty)) + if pa.types.is_float32(ty): + return nbt.float32 + if pa.types.is_float64(ty): + return nbt.float64 + if _is_var_width(ty): + # element reads go through StringViewType, there is no scalar type + return nbt.uint8 + if pa.types.is_decimal(ty) and ty.bit_width == 128: + # (high, low) of the 128-bit two's complement integer, exact; + # use decimal_to_float() when a double is what you want + return nbt.Tuple((nbt.int64, nbt.uint64)) + # temporal types are their storage integers: no unit conversion here + if pa.types.is_date32(ty) or pa.types.is_time32(ty): + return nbt.int32 + if (pa.types.is_date64(ty) or pa.types.is_time64(ty) + or pa.types.is_timestamp(ty) or pa.types.is_duration(ty)): + return nbt.int64 + if pa.types.is_boolean(ty): + # bit-packed values: readable as validity, not as elements + return nbt.boolean + raise TypeError(f'Unsupported PyArrow type {ty}') + + +class ArrowValueType(nbt.Type): + """A Numba type carrying an Arrow type and the Numba type of one value. + + Parameters + ---------- + arrow_type : pa.DataType + Arrow type of the values. + name : str + Numba type name. + """ + + def __init__(self, arrow_type: pa.DataType, name: str) -> None: + self.arrow_type = arrow_type + self.numba_type = _arrow_type_to_nb_type(arrow_type) + super().__init__(name=name) + + +# a MemInfoPointer of void: the payload's layout is read by the codegen +MEMINFO = nbt.MemInfoPointer(nbt.voidptr) + + +def nrt_dtor(module: ir.Module, name: str, emit: Callable[..., None]) -> ir.Function: + """Define ``name`` once per module: the destructor of this package's payloads. + + *emit* writes the body, given the builder and the payload pointer. The + signature is the one NRT calls a destructor with; the last two arguments + are the size and the MemInfo, which nothing here needs. + + Parameters + ---------- + module : ir.Module + LLVM module to define the destructor in. + name : str + Symbol name of the destructor. + emit : Callable[..., None] + Emits the destructor body, given an IR builder and the payload pointer. + """ + fnty = ir.FunctionType(ir.VoidType(), + [cgutils.voidptr_t, cgutils.intp_t, + cgutils.voidptr_t]) + fn = cgutils.get_or_insert_function(module, fnty, name) + if fn.is_declaration: + fn.linkage = "linkonce_odr" + builder = ir.IRBuilder(fn.append_basic_block()) + emit(builder, fn.args[0]) + builder.ret_void() + return fn + + +def nrt_alloc_ll(context: BaseContext, builder: ir.IRBuilder, + payload_type: ir.Type, + dtor: ir.Function) -> tuple[ir.Value, ir.Value]: + """Allocate a zero-filled NRT payload; returns ``(meminfo, payload_ptr)``. + + Parameters + ---------- + context : BaseContext + Numba target context. + builder : ir.IRBuilder + LLVM IR builder at the insertion point. + payload_type : ir.Type + LLVM type of the payload. + dtor : ir.Function + Destructor called on the payload when it is freed. + """ + size = context.get_constant(nbt.uintp, context.get_abi_sizeof(payload_type)) + meminfo = context.nrt.meminfo_alloc_dtor_unchecked( + builder, size, builder.bitcast(dtor, cgutils.voidptr_t)) + with builder.if_then(cgutils.is_null(builder, meminfo), likely=False): + context.call_conv.return_user_exc( + builder, MemoryError, ("pyarrow.numba: out of memory",)) + payload = builder.bitcast(context.nrt.meminfo_data(builder, meminfo), + payload_type.as_pointer()) + builder.store(ir.Constant(payload_type, None), payload) + return meminfo, payload + + +def _return_arrow_error_ll(context: BaseContext, + builder: ir.IRBuilder) -> None: + """Propagate a C++-set Python error, marking its exit for NRT pruning.""" + # RETCODE_EXC preserves the pending Python exception and ignores excinfo; + # the marker is what tells Numba's refcount optimizer this block raises. + excptr = context.call_conv._get_excinfo_argument(builder.function) + store = builder.store(ir.Constant(excptr.type.pointee, None), excptr) + store.set_metadata( + "numba_exception_output", + builder.module.add_metadata([ir.IntType(1)(1)]), + ) + context.call_conv.return_exc(builder) + + +int64_t = ir.IntType(64) + +pyarrow_cpp_funcs = { + 'PyArrow_AllocatePoolBuffer': ir.FunctionType(cgutils.voidptr_t, [int64_t]), + 'PyArrow_PoolBufferReserve': ir.FunctionType( + cgutils.int32_t, [cgutils.voidptr_t, int64_t]), + 'PyArrow_PoolBufferResizeExactly': ir.FunctionType( + cgutils.int32_t, [cgutils.voidptr_t, int64_t]), + 'PyArrow_PoolBufferDestroy': ir.FunctionType( + ir.VoidType(), [cgutils.voidptr_t]), + 'PyArrow_MakeAndExportArray': ir.FunctionType( + cgutils.int32_t, [cgutils.int32_t, int64_t, int64_t, cgutils.int32_t, + cgutils.voidptr_t.as_pointer(), cgutils.voidptr_t]), + 'PyArrow_ReleaseArray': ir.FunctionType(ir.VoidType(), [cgutils.voidptr_t]), +} + + +@functools.cache +def get_pyarrow_dll() -> ctypes.CDLL: + """The handle every ``PyArrow_*`` symbol resolves through. + + ``pyarrow.lib`` itself, not a fresh ``CDLL`` of ``libarrow_python.so``: a + wheel ships that file and a versioned copy next to it, and ``pyarrow.lib`` + is linked against the versioned one. Opening it by name would map a second + copy and give out pointers from the wrong one. + """ + dll = ctypes.CDLL(pa.lib.__file__) + # symbols must be registered before the first compilation in this process + for func_name in pyarrow_cpp_funcs: + llvmlite.binding.add_symbol( + func_name, ctypes.cast(dll[func_name], ctypes.c_void_p).value) + return dll + + +get_pyarrow_dll() # registers the symbols before the first compilation + + +def get_pyarrow_cpp_func(builder: ir.IRBuilder, + func_name: str) -> ir.Function: + return cgutils.get_or_insert_function( + builder.module, pyarrow_cpp_funcs[func_name], func_name) diff --git a/python/pyarrow/numba/array.py b/python/pyarrow/numba/array.py new file mode 100644 index 000000000000..e0f0124fe14c --- /dev/null +++ b/python/pyarrow/numba/array.py @@ -0,0 +1,649 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Arrow ``Array`` support: typing, data model, and the read accessors. + +An array is unboxed as the C ``ArrowArray`` struct itself (by value), so the +compiled code reads a producer's buffers without pyarrow building anything. +The struct carries the producer's release callback; the unbox cleanup calls it +when the call returns. +""" + +from __future__ import annotations + +import functools +import operator +from collections.abc import Callable + +import numpy as np +from llvmlite import ir +from numba import extending as nbext +from numba import types as nbt +from numba.core import cgutils +from numba.core.base import BaseContext +from numba.core.datamodel.manager import DataModelManager +from numba.core.pythonapi import PythonAPI +from numba.core.typing.context import BaseContext as TypingContext +from numba.core.typing.templates import Signature, signature + +import pyarrow as pa + +from ._capsule import dtype_of, num_buffers, take_array_into +from ._utils import ( + MEMINFO, + ArrowValueType, + _is_var_width, + get_pyarrow_cpp_func, + int64_t, + nrt_dtor, +) + + +class PyArrowArrayType(ArrowValueType): + def __init__(self, type: pa.DataType, nullable: bool = True, + owned: bool = False) -> None: + name = f"PyArrowArray({type}{', built' if owned else ''})" + super().__init__(type, name) + # decides whether the null test is emitted at all, so it is part of the + # type; producers that cannot say cheaply leave it True and pay the test + self.nullable = nullable + # a built array: its C struct lives in an NRT payload, NRT releases it, + # and boxing hands the struct to pyarrow + self.owned = owned + + @property + def key(self) -> tuple: + return (self.name, self.nullable) + + +@functools.cache +def _array_type(arrow_type: pa.DataType, nullable: bool = True, + owned: bool = False) -> PyArrowArrayType: + """One Numba type per (Arrow type, nullability, ownership).""" + return PyArrowArrayType(arrow_type, nullable, owned) + + +@nbext.typeof_impl.register(pa.Array) +def typeof_array(val: object, c: TypingContext) -> PyArrowArrayType: + return _array_type(val.type, val.null_count != 0) + + +def register_producer(cls: type) -> type: + """Let ``@njit`` accept arrays of *cls* via the Arrow PyCapsule interface. + + Call once per producer class before compiling:: + + register_producer(polars.Series) + + The type is derived from the producer's own dtype, so a producer of a + supported Arrow type needs no further setup. + """ + + @nbext.typeof_impl.register(cls) + def typeof_producer(val, c): + return _array_type(dtype_of(val)) + + return cls + + +for _field in ("length", "null_count", "offset"): + nbext.make_attribute_wrapper(PyArrowArrayType, _field, _field) + + +class StringViewType(nbt.Type): + """A non-owning view of one string or binary element.""" + + def __init__(self) -> None: + super().__init__(name="ArrowStringView") + + +# The C ABI's ten fields; _capsule.ArrowArray is the authority. Everything is +# word-sized, so a mismatch only shows up as wrong data, not a crash. +_ARRAY_FIELDS = ( + ("length", nbt.int64), + ("null_count", nbt.int64), + ("offset", nbt.int64), + ("n_buffers", nbt.int64), + ("n_children", nbt.int64), + ("buffers", nbt.CPointer(nbt.CPointer(nbt.uint8))), + ("children", nbt.CPointer(nbt.CPointer(nbt.uint8))), + ("dictionary", nbt.CPointer(nbt.uint8)), + ("release_cb", nbt.CPointer(nbt.uint8)), + ("private_data", nbt.CPointer(nbt.uint8)), +) +_RELEASE_FIELD = [name for name, _ in _ARRAY_FIELDS].index("release_cb") + + +@nbext.register_model(PyArrowArrayType) +class ArrayModel(nbext.models.StructModel): + def __init__(self, dmm: DataModelManager, fe_type: PyArrowArrayType) -> None: + # The struct is by value: unboxing writes the producer's struct in + # place and its cleanup releases the buffers. A *built* array owns a + # struct too, and that one lives in an NRT payload, so it is not a + # read-only copy: it is where finish() wrote it. + members = list(_ARRAY_FIELDS) + if fe_type.owned: + # the C struct a built array owns lives in this NRT payload; its + # destructor releases it. The fields above are a read-only copy. + members.append(("meminfo", MEMINFO)) + super().__init__(dmm, fe_type, members) + + +@nbext.register_model(StringViewType) +class StringViewModel(nbext.models.StructModel): + """chars/start/end: a byte range inside the array's data buffer. + + Parameters + ---------- + dmm : DataModelManager + Numba data model manager. + fe_type : nbt.Type + Numba type this model describes. + """ + + def __init__(self, dmm: DataModelManager, fe_type: nbt.Type) -> None: + super().__init__(dmm, fe_type, [ + ("chars", nbt.CPointer(nbt.uint8)), ("start", nbt.int64), + ("end", nbt.int64), ("valid", nbt.boolean)]) + + +for _field in ("chars", "start", "end", "valid"): + nbext.make_attribute_wrapper(StringViewType, _field, _field) + + +def _release_ll(builder: ir.IRBuilder, struct_ptr: ir.Value) -> None: + """Release the buffers a struct at *struct_ptr* owns, if any.""" + fn = get_pyarrow_cpp_func(builder, "PyArrow_ReleaseArray") + builder.call(fn, [builder.bitcast(struct_ptr, cgutils.voidptr_t)]) + + +def _array_dtor(module: ir.Module) -> ir.Function: + """The destructor of a built array's payload: release, unless boxed.""" + return nrt_dtor(module, "_pyarrow_numba_array_dtor", _release_ll) + + +def _call_ll(c: PythonAPI, func: object, addr: ir.Value, dtype: pa.DataType, + *objs: ir.Value) -> ir.Value: + """Call ``func(*objs, addr, dtype)``; returns the result (NULL on error).""" + addr_obj = c.pyapi.long_from_unsigned_int( + c.builder.ptrtoint(addr, cgutils.intp_t)) + fn_obj = c.pyapi.unserialize(c.pyapi.serialize_object(func)) + dtype_obj = c.pyapi.unserialize(c.pyapi.serialize_object(dtype)) + ret = c.pyapi.call_function_objargs(fn_obj, (*objs, addr_obj, dtype_obj)) + c.pyapi.decref(fn_obj) + c.pyapi.decref(dtype_obj) + c.pyapi.decref(addr_obj) + return ret + + +def _safe_buffers_ll( + context: BaseContext, builder: ir.IRBuilder, array: type, n_buffers: int, + copy: ir.Value | None = None, +) -> None: + """Copy the buffer pointers, putting a zero word where Arrow has none. + + A dense array leaves ``buffers[0]`` null. Pointing our copy at zeroed + memory makes the per-element bitmap load unconditional; ``null_count`` + then decides if the bit counts. + No validity buffer means no nulls, so ``null_count`` is set to 0 there: + a producer may leave it -1 ("not computed"), and the null test would then + read bits past the single zero word. + + *copy* is where the pointers go: by default a stack slot, which exists + once per call site, so a caller exporting in a loop passes one per array. + """ + ptr_t = context.get_value_type(nbt.uint8).as_pointer() + source = array.buffers + if copy is None: + copy = cgutils.alloca_once(builder, ptr_t, size=n_buffers) + zero_word = cgutils.alloca_once(builder, ir.IntType(64), zfill=True) + zero_ptr = builder.bitcast(zero_word, ptr_t) + + has_source = cgutils.is_not_null(builder, source) + with builder.if_then(has_source): + for i in range(n_buffers): + pointer = builder.load(cgutils.gep(builder, source, i)) + builder.store(builder.select(cgutils.is_not_null(builder, pointer), + pointer, zero_ptr), + cgutils.gep(builder, copy, i)) + bitmap = builder.load(cgutils.gep(builder, source, 0)) + array.null_count = builder.select(cgutils.is_null(builder, bitmap), + array.null_count.type(0), + array.null_count) + + # a failed export leaves no buffers: keep the null pointer, the caller is + # raising anyway + array.buffers = builder.select(has_source, copy, source) + + +def _export_into_ll(c: PythonAPI, obj: ir.Value, addr: ir.Value, + array_type: PyArrowArrayType, is_error_ptr: ir.Value, + copy: ir.Value | None = None) -> None: + """Emit ``take_array_into(obj, addr, dtype)``; flag a NULL result. + + *copy* is passed to ``_safe_buffers_ll``. + """ + dtype = array_type.arrow_type + ret = _call_ll(c, take_array_into, addr, dtype, obj) + with c.builder.if_then(cgutils.is_null(c.builder, ret)): + c.builder.store(cgutils.true_bit, is_error_ptr) + c.pyapi.decref(ret) # Py_DecRef ignores NULL + + # the slot now holds the producer's struct: make its null buffer slots safe + proxy = c.context.make_helper(c.builder, array_type, ref=addr) + _safe_buffers_ll(c.context, c.builder, proxy, num_buffers(dtype), copy) + + +@nbext.unbox(PyArrowArrayType) +def unbox_array( + typ: PyArrowArrayType, obj: ir.Value, c: PythonAPI +) -> nbext.NativeValue: + """ + Unbox a pa.Array object as a ArrowArray struct wrapper. + + Parameters + ---------- + typ : PyArrowArrayType + Numba type of the argument. + obj : ir.Value + The Python object to unbox. + c : PythonAPI + Numba's boxing and unboxing helpers. + """ + is_error_ptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit) + c_array = cgutils.create_struct_proxy(typ)(c.context, c.builder) + # _capsule.take_array_into moves the producer's ArrowArray into this + # struct + _export_into_ll(c, obj, c_array._getpointer(), typ, is_error_ptr) + + def cleanup(): + _release_ll(c.builder, c_array._getpointer()) + + return nbext.NativeValue( + c_array._getvalue(), cleanup=cleanup, is_error=c.builder.load(is_error_ptr) + ) + + +@nbext.box(PyArrowArrayType) +def box_array(typ: PyArrowArrayType, val: ir.Value, c: PythonAPI) -> ir.Value: + """Box a built array: hand its owned struct to pyarrow. + + Only structs created inside compiled code (a builder's ``finish()``) may be + boxed. An array that came from an *argument* has no owned struct: pyarrow's + import would keep pointing at the argument, and unboxing's cleanup releases + the buffers the returned array still reads. + + Parameters + ---------- + typ : PyArrowArrayType + Numba type of the value. + val : ir.Value + LLVM value to box. + c : PythonAPI + Numba's boxing and unboxing helpers. + """ + if not typ.owned: + raise NotImplementedError( + "cannot return an Arrow array argument from compiled code: its " + "buffers are released when the call returns; build a new array " + "instead") + c_array = c.context.make_helper(c.builder, typ, value=val) + payload = c.context.nrt.meminfo_data(c.builder, c_array.meminfo) + ret_ptr = cgutils.alloca_once_value(c.builder, c.pyapi.get_null_object()) + # the first boxing moves the struct to pyarrow, which clears its release + release = c.builder.load(c.builder.gep( + c.builder.bitcast(payload, cgutils.voidptr_t.as_pointer()), + [int64_t(_RELEASE_FIELD)])) + with c.builder.if_else(cgutils.is_null(c.builder, release), + likely=False) as (moved, owned): + with moved: + c.pyapi.err_set_string( + "PyExc_RuntimeError", + "a built Arrow array can be returned to Python only once") + with owned: + c.builder.store( + _call_ll(c, pa.Array._import_from_c, payload, typ.arrow_type), + ret_ptr) + ret = c.builder.load(ret_ptr) + # the struct now belongs to pyarrow: drop this array's native reference + c.context.nrt.decref(c.builder, typ, val) + return ret + + +@nbext.intrinsic +def ll_array_is_null( + typingctx: TypingContext, arr_type: nbt.Type, index_type: nbt.Type +) -> tuple[Signature, Callable[..., ir.Value]] | None: + if not isinstance(arr_type, PyArrowArrayType): + return None + + def codegen(context, builder, signature, args): + array = context.make_helper(builder, arr_type, value=args[0]) + return _array_is_null_ll(context, builder, arr_type, array, args[1]) + + return nbt.bool_(arr_type, nbt.int64), codegen + + +def _bit_ll(builder: ir.IRBuilder, buffer: ir.Value, bit_index: ir.Value, + word_t: ir.Type, guard: ir.Value | None = None) -> ir.Value: + """True when bit *bit_index* of *buffer* is set. + + *guard* selects word 0 when false: it keeps the load inside the single + zero word a missing bitmap was replaced with. + """ + shift = word_t.width.bit_length() - 1 # 6 for u64, 3 for i8 + within = word_t.width - 1 + word_index = builder.lshr(bit_index, bit_index.type(shift)) + if guard is not None: + word_index = builder.select(guard, word_index, word_index.type(0)) + word = builder.load( + cgutils.gep(builder, builder.bitcast(buffer, word_t.as_pointer()), + word_index)) + mask = builder.shl( + ir.Constant(word_t, 1), + builder.trunc(builder.and_(bit_index, bit_index.type(within)), word_t), + ) + return builder.icmp_unsigned( + "!=", builder.and_(word, mask), ir.Constant(word_t, 0)) + + +def _array_is_null_ll(context, builder, arr_type, array, index): + """True when element *index* is null; straight-line, no branch. + + The validity pointer is never null here (unbox substitutes a zero word for + the slot a dense array leaves empty), so the bit load is unconditional and + the ``null_count`` gate is a plain ``and``. *array* is the + struct proxy. + """ + if not arr_type.nullable: + # no nulls: no load, no test, no branch + return cgutils.false_bit + + has_nulls = builder.icmp_unsigned("!=", array.null_count, + array.null_count.type(0)) + bitmap = builder.load(cgutils.gep(builder, array.buffers, 0, inbounds=True)) + + numeric = isinstance(arr_type.numba_type, nbt.Number) + word_t = ir.IntType(64) if numeric else cgutils.int8_t + + bit_index = builder.add(array.offset, index) + valid = _bit_ll(builder, bitmap, bit_index, word_t, guard=has_nulls) + return builder.and_(has_nulls, builder.xor(valid, cgutils.true_bit)) + + +def _load_value_ll(context: BaseContext, builder: ir.IRBuilder, + arr_type: PyArrowArrayType, array: type, + i: ir.Value) -> ir.Value: + """The value at element *i* (offset already applied), read unconditionally.""" + data_buffer = builder.load(cgutils.gep(builder, array.buffers, 1, inbounds=True)) + numba_type = arr_type.numba_type + + if arr_type.arrow_type == pa.bool_(): + # bit-packed values: one bit per element, no byte per value + return _bit_ll(builder, data_buffer, i, cgutils.int8_t) + + if pa.types.is_decimal(arr_type.arrow_type): + # 128-bit little-endian two's complement, returned as (high, low): + # exact, and tuple order compares like the value + words = builder.bitcast(data_buffer, ir.IntType(64).as_pointer()) + pair = builder.mul(i, ir.Constant(i.type, 2)) + low = builder.load(cgutils.gep(builder, words, pair)) + high = builder.load( + cgutils.gep(builder, words, builder.add(pair, ir.Constant(i.type, 1)))) + return context.make_tuple(builder, numba_type, [high, low]) + + data_buffer = builder.bitcast( + data_buffer, context.get_data_type(numba_type).as_pointer()) + return builder.load(cgutils.gep(builder, data_buffer, i)) + + +def _string_range_ll(builder: ir.IRBuilder, arr_type: PyArrowArrayType, + array: type, i: ir.Value) -> tuple[ir.Value, ...]: + """``(chars, start, end)`` of element *i*; offsets width from the type.""" + arrow_type = arr_type.arrow_type + fixed_width = (arrow_type.byte_width + if pa.types.is_fixed_size_binary(arrow_type) else 0) + if fixed_width: + # fixed-size binary has no offsets buffer: [validity, data] + chars = builder.load(cgutils.gep(builder, array.buffers, 1, inbounds=True)) + start = builder.mul(i, ir.Constant(i.type, fixed_width)) + return chars, start, builder.add(start, ir.Constant(i.type, fixed_width)) + + # string/binary: [validity, offsets, data] + wide = (pa.types.is_large_string(arrow_type) + or pa.types.is_large_binary(arrow_type)) + off_t = ir.IntType(64 if wide else 32) + offsets = builder.load(cgutils.gep(builder, array.buffers, 1, inbounds=True)) + chars = builder.load(cgutils.gep(builder, array.buffers, 2, inbounds=True)) + offsets = builder.bitcast(offsets, off_t.as_pointer()) + start = builder.load(cgutils.gep(builder, offsets, i)) + end = builder.load(cgutils.gep(builder, offsets, builder.add(i, i.type(1)))) + return chars, builder.sext(start, int64_t), builder.sext(end, int64_t) + + +@nbext.intrinsic +def ll_array_get(typingctx: TypingContext, arr_type: nbt.Type, + index_type: nbt.Type + ) -> tuple[Signature, Callable[..., ir.Value]] | None: + """Element *index*: an ``Optional`` value, or a ``StringView`` for strings. + + A fixed-width data buffer has a slot per element whether or not that + element is null, so the load can sit outside the null test. + + Parameters + ---------- + typingctx : TypingContext + Numba typing context. + arr_type : nbt.Type + Numba type of the array. + index_type : nbt.Type + Numba type of the index. + """ + if not isinstance(arr_type, PyArrowArrayType): + return None + var_width = _is_var_width(arr_type.arrow_type) + result_type = (StringViewType() if var_width + else nbt.Optional(arr_type.numba_type)) + sig = result_type(arr_type, nbt.int64) + + def codegen(context, builder, signature, args): + arr_val, index = args + array = context.make_helper(builder, arr_type, value=arr_val) + i = builder.add(array.offset, index) + is_null = _array_is_null_ll(context, builder, arr_type, array, index) + + out = context.make_helper(builder, signature.return_type) + out.valid = builder.xor(is_null, cgutils.true_bit) + if var_width: + out.chars, out.start, out.end = _string_range_ll( + builder, arr_type, array, i) + else: + out.data = _load_value_ll(context, builder, arr_type, array, i) + return out._getvalue() + + return sig, codegen + + +@nbext.intrinsic +def string_view_data(typingctx: TypingContext, view_type: nbt.Type) -> object: + """The first byte of a view, so a builder can copy the range in one call. + + Parameters + ---------- + typingctx : TypingContext + Numba typing context. + view_type : nbt.Type + Numba type of the view. + """ + + def codegen(context, builder, signature, args): + view = context.make_helper(builder, view_type, value=args[0]) + return builder.gep(view.chars, [view.start]) + + return signature(nbt.voidptr, view_type), codegen + + +@nbext.box(StringViewType) +def box_string_view(typ: StringViewType, val: ir.Value, c: PythonAPI) -> ir.Value: + """Box a view as ``bytes``, one copy of the element, or ``None`` if null. + + Parameters + ---------- + typ : StringViewType + Numba type of the value. + val : ir.Value + LLVM value to box. + c : PythonAPI + Numba's boxing and unboxing helpers. + """ + view = c.context.make_helper(c.builder, typ, value=val) + out = cgutils.alloca_once(c.builder, c.pyapi.pyobj) + with c.builder.if_else(view.valid) as (valid, null): + with valid: + c.builder.store(c.pyapi.bytes_from_string_and_size( + c.builder.gep(view.chars, [view.start]), + c.builder.sub(view.end, view.start)), out) + with null: + c.builder.store(c.pyapi.make_none(), out) + return c.builder.load(out) + + +def decimal_to_float(words: tuple[int, int], scale: int) -> float: + """A double for a ``(high, low)`` decimal128 value. + + Exact only to 53 bits, which is all a double holds; ``words`` itself is + the exact value: ``high * 2**64 + low``, unscaled by ``scale``. + + Parameters + ---------- + words : tuple[int, int] + ``(high, low)`` words of the unscaled value, as ``a[i]`` returns them. + scale : int + Scale of the decimal type. + """ + raise NotImplementedError("only callable from nopython code") + + +@nbext.overload(decimal_to_float) +def decimal_to_float_impl(words, scale): + if not isinstance(words, nbt.BaseTuple) or len(words) != 2: + return + if not isinstance(scale, nbt.Integer): + return + + def impl(words, scale): + high, low = words + # the halves separately would cancel to 0 for a value like -1, so the + # 64-bit cases are converted from the low word alone + if high == 0: + unscaled = np.float64(low) + elif high == -1 and low >= 9223372036854775808: + unscaled = np.float64(np.int64(low)) + else: + unscaled = np.float64(high) * 2.0**64 + np.float64(low) + return unscaled * 10.0 ** (-scale) + + return impl + + +def string_len(view: object) -> int: + """Byte length of a string view. Implemented in compiled code. + + Parameters + ---------- + view : object + Element of a string or binary array. + """ + raise NotImplementedError("only callable from nopython code") + + +@nbext.overload(string_len) +def string_len_impl(view): + if not isinstance(view, StringViewType): + return + + def impl(view): + return view.end - view.start + + return impl + + +def _checked_index(index: int, length: int) -> int: + """*index*, normalised and range-checked. Implemented in compiled code.""" + raise NotImplementedError("only callable from nopython code") + + +@nbext.overload(_checked_index, inline="always") +def _checked_index_impl(index, length): + if not isinstance(index, nbt.Integer) and index not in nbt.integer_domain: + raise nbt.TypingError("array indices must be integers") + if not isinstance(length, nbt.Integer): + return + + def impl(index, length): + i = index if index >= 0 else index + length + if i < 0 or i >= length: + raise IndexError("Arrow array index out of range") + return i + + return impl + + +@nbext.overload(operator.getitem, inline="always") +def array_getitem(arr, index): + if not isinstance(arr, PyArrowArrayType): + return + + def impl(arr, index): + return ll_array_get(arr, _checked_index(index, arr.length)) + + return impl + + +def is_valid(arr: object, index: int) -> bool: + """True when element *index* is not null. Implemented in compiled code. + + Parameters + ---------- + arr : object + Arrow array. + index : int + Element index. + """ + raise NotImplementedError("only callable from nopython code") + + +@nbext.overload(is_valid, inline="always") +def is_valid_impl(arr, index): + if not isinstance(arr, PyArrowArrayType): + return + + def impl(arr, index): + return not ll_array_is_null(arr, _checked_index(index, arr.length)) + + return impl + + +@nbext.overload(len, inline="always") +def array_len(arr): + if not isinstance(arr, PyArrowArrayType): + return + + def impl(arr): + return arr.length + + return impl diff --git a/python/pyarrow/numba/builder.py b/python/pyarrow/numba/builder.py new file mode 100644 index 000000000000..f785ff19d16c --- /dev/null +++ b/python/pyarrow/numba/builder.py @@ -0,0 +1,304 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Array builders: per-element code generation. + +The type and typing rules are in ``builder_types``. Here: construction, the +NRT destructor, ``append``, ``reserve`` and ``finish``. +""" + +from __future__ import annotations + +from collections.abc import Callable + +from llvmlite import ir +from numba import extending as nbext +from numba import types as nbt +from numba.core import cgutils +from numba.core.base import BaseContext +from numba.core.typing.context import BaseContext as TypingContext +from numba.core.typing.templates import Signature, signature + +from ._utils import ( + MEMINFO, + _is_var_width, + _return_arrow_error_ll, + get_pyarrow_cpp_func, + int64_t, + nrt_alloc_ll, + nrt_dtor, +) +from .array import ( + _ARRAY_FIELDS, + StringViewType, + _array_dtor, + _array_type, + string_view_data, +) +from .builder_types import ( # noqa: F401 (the package's public builder face) + BUILDER_STATE, + ArrayBuilder, + ArrayBuilderAttribute, + ArrayBuilderModel, + ArrayBuilderType, + BinaryBuilder, + BoolBuilder, + Float32Builder, + Float64Builder, + Int8Builder, + Int16Builder, + Int32Builder, + Int64Builder, + LargeBinaryBuilder, + LargeStringBuilder, + StringBuilder, + UInt8Builder, + UInt16Builder, + UInt32Builder, + UInt64Builder, + _builder_typer, + _data_buffer_type, + _offsets_buffer_type, + _offsets_type, +) +from .poolbuffer import ( + FINISHED, + POOL, + SIZE, + append_ll, + finish_ll, + init_ll, + release_ll, + state_ptr, +) + + +def _builder_dtor(module: ir.Module) -> ir.Function: + """Free every pool the builder still owns.""" + def emit(builder: ir.IRBuilder, payload: ir.Value) -> None: + state = builder.bitcast(payload, BUILDER_STATE.as_pointer()) + for k in range(3): + slot = cgutils.gep(builder, state, 0, 1, k) + pool = builder.load(cgutils.gep(builder, slot, 0, POOL)) + with builder.if_then(cgutils.is_not_null(builder, pool)): + builder.call(get_pyarrow_cpp_func( + builder, 'PyArrow_PoolBufferDestroy'), [pool]) + + return nrt_dtor(module, '_pyarrow_numba_builder_dtor', emit) + + +# a plain lowering, not an @intrinsic: the model embeds pointers, which the +# intrinsic path cannot handle +def builder_ctor(context: BaseContext, builder: ir.IRBuilder, + sig: Signature, args: tuple[ir.Value, ...]) -> ir.Value: + typ = sig.return_type + meminfo, payload = nrt_alloc_ll(context, builder, BUILDER_STATE, + _builder_dtor(builder.module)) + state = builder.bitcast(payload, BUILDER_STATE.as_pointer()) + out = cgutils.create_struct_proxy(typ)(context, builder) + out.meminfo = meminfo + out.null_count_ptr = cgutils.gep(builder, state, 0, 0) + + for name, buffer_type, k in typ.buffers: + slot = cgutils.gep(builder, state, 0, 1, k) + arrow_type = buffer_type.arrow_type + # room for the leading zero offset, so seeding it cannot fail + initial = arrow_type.byte_width if name == 'offsets_builder' else 0 + fn = get_pyarrow_cpp_func(builder, 'PyArrow_AllocatePoolBuffer') + pool = builder.call(fn, [int64_t(initial)]) + with builder.if_then(cgutils.is_null(builder, pool)): + # destroys the pools made so far + context.nrt.decref(builder, MEMINFO, meminfo) + _return_arrow_error_ll(context, builder) + setattr(out, name, init_ll(context, builder, arrow_type, slot, pool)) + + if _is_var_width(typ.arrow_type): + # the leading offset, seeded once: every later entry follows the size + offsets = _offsets_buffer_type(typ) + append_ll(context, builder, offsets.arrow_type, + state_ptr(context, builder, offsets, out.offsets_builder), + ir.Constant(context.get_value_type(offsets.numba_type), 0)) + + return out._getvalue() + + +for _builder_cls in ArrayBuilder.__subclasses__(): + nbext.type_callable(_builder_cls)(_builder_typer(_builder_cls.arrow_type)) + nbext.lower_builtin(_builder_cls)(builder_ctor) + + +@nbext.intrinsic +def builder_increment_null_count(typingctx: TypingContext, + array_builder: nbt.Type, is_null: nbt.Type + ) -> tuple[Signature, Callable[..., None]]: + """Add *is_null* (a boolean, 0 or 1) to the null count, without a branch. + + Parameters + ---------- + typingctx : TypingContext + Numba typing context. + array_builder : nbt.Type + Numba type of the builder. + is_null : nbt.Type + Numba type of the null flag. + """ + assert isinstance(array_builder, ArrayBuilderType) + sig = nbt.none(array_builder, nbt.boolean) + + def codegen(context, builder, sig, args): + array_builder = context.make_helper(builder, sig.args[0], value=args[0]) + null_count = builder.load(array_builder.null_count_ptr) + builder.store(builder.add(null_count, + builder.zext(args[1], null_count.type)), + array_builder.null_count_ptr) + + return sig, codegen + + +@nbext.intrinsic +def bytes_data(typingctx: TypingContext, value_type: nbt.Type) -> object: + """The first byte of a ``bytes`` value, for the bulk builder copy. + + Parameters + ---------- + typingctx : TypingContext + Numba typing context. + value_type : nbt.Type + Numba type of the value. + """ + + def codegen(context, builder, signature, args): + value = context.make_helper(builder, value_type, value=args[0]) + return builder.bitcast(value.data, ir.IntType(8).as_pointer()) + + return signature(nbt.voidptr, value_type), codegen + + +@nbext.overload_method(ArrayBuilderType, 'append', inline="always") +def builder_append(builder, value): + if _is_var_width(builder.arrow_type): + if value == nbt.none: + def append_null(builder, value): + builder.null_bitmap_builder.append(False) + builder.offsets_builder.append(builder.data_builder.size) + builder_increment_null_count(builder, True) + return append_null + + if isinstance(value, nbt.Bytes): + def append_bytes(builder, value): + builder.data_builder.append_bytes(bytes_data(value), len(value)) + builder.null_bitmap_builder.append(True) + builder.offsets_builder.append(builder.data_builder.size) + return append_bytes + + if isinstance(value, StringViewType): + def append_view(builder, value): + if value.valid: + builder.data_builder.append_bytes( + string_view_data(value), value.end - value.start) + else: + builder_increment_null_count(builder, True) + builder.null_bitmap_builder.append(value.valid) + builder.offsets_builder.append(builder.data_builder.size) + return append_view + + return + + if value == nbt.none: + # the data buffer still needs a placeholder of its own type + element = builder.numba_type + zero = (0.0 if isinstance(element, nbt.Float) + else False if element == nbt.boolean else 0) + + def append_impl(builder, value): + builder.null_bitmap_builder.append(False) + builder.data_builder.append(zero) + builder_increment_null_count(builder, True) + return append_impl + else: + def append_impl(builder, value): + builder.null_bitmap_builder.append(True) + builder.data_builder.append(value) + return append_impl + + +@nbext.overload_method(ArrayBuilderType, 'reserve', inline="always") +def builder_reserve(builder, capacity): + if _is_var_width(builder.arrow_type): + def impl_var_width(builder, capacity): + builder.null_bitmap_builder.reserve(capacity) + builder.data_builder.reserve(capacity) + builder.offsets_builder.reserve(capacity) + return impl_var_width + + def impl(builder, capacity): + builder.null_bitmap_builder.reserve(capacity) + builder.data_builder.reserve(capacity) + return impl + + +@nbext.lower_builtin('ArrayBuilder.finish', ArrayBuilderType) +def builder_finish(context: BaseContext, builder: ir.IRBuilder, + sig: Signature, args: tuple[ir.Value, ...]) -> ir.Value: + typ = sig.args[0] + array_builder = context.make_helper(builder, typ, value=args[0]) + states = {k: state_ptr(context, builder, buffer_type, + getattr(array_builder, name)) + for name, buffer_type, k in typ.buffers} + null_state = states[0] + + pool = builder.load(cgutils.gep(builder, null_state, 0, POOL)) + with builder.if_then(cgutils.is_null(builder, pool)): + context.call_conv.return_user_exc(builder, RuntimeError, (FINISHED,)) + + length = builder.load(cgutils.gep(builder, null_state, 0, SIZE)) + null_count = builder.load(array_builder.null_count_ptr) + # exactly the buffers the type has, in Arrow order + pools = [finish_ll(context, builder, buffer_type.arrow_type, states[k]) + for _, buffer_type, k in typ.buffers] + + # the array owns a struct of its own, in its own NRT payload + array_type = _array_type(typ.arrow_type) + meminfo, c_array = nrt_alloc_ll( + context, builder, context.get_data_type(array_type), + _array_dtor(builder.module)) + # the export owns the pools from here, even if it fails + for state in states.values(): + release_ll(builder, state) + + buffer_ptrs = cgutils.pack_array(builder, pools) + # LLVM doesn't implicitly cast `[n x x*]*` to `void**` + buffer_ptrs = builder.bitcast( + cgutils.alloca_once_value(builder, buffer_ptrs), + cgutils.voidptr_t.as_pointer()) + fn = get_pyarrow_cpp_func(builder, 'PyArrow_MakeAndExportArray') + status = builder.call( + fn, [cgutils.int32_t(typ.arrow_type.id), length, null_count, + cgutils.int32_t(len(pools)), buffer_ptrs, + builder.bitcast(c_array, cgutils.voidptr_t)]) + with builder.if_then(builder.icmp_signed('<', status, status.type(0))): + # the C++ already set the Python exception: do not overwrite it + context.nrt.decref(builder, MEMINFO, meminfo) + _return_arrow_error_ll(context, builder) + + exported = cgutils.create_struct_proxy(array_type)( + context, builder, ref=c_array) + out = cgutils.create_struct_proxy(sig.return_type)(context, builder) + for name, _ in _ARRAY_FIELDS: + setattr(out, name, getattr(exported, name)) + out.meminfo = meminfo + return out._getvalue() diff --git a/python/pyarrow/numba/builder_types.py b/python/pyarrow/numba/builder_types.py new file mode 100644 index 000000000000..621e0470284d --- /dev/null +++ b/python/pyarrow/numba/builder_types.py @@ -0,0 +1,151 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Array builders: the Python classes, the Numba type, and the typing rules. + +Separate from the code generation so the type layer can be read without the +LLVM. A builder owns its buffers through an NRT payload; the layout and the +code that reads it are in ``builder``. +""" + +from __future__ import annotations + +from collections.abc import Callable + +from llvmlite import ir +from numba import extending as nbext +from numba import types as nbt +from numba.core.typing.context import BaseContext as TypingContext +from numba.core.typing.templates import ( + AttributeTemplate, + bound_function, + infer_getattr, + signature, +) + +import pyarrow as pa + +from ._utils import MEMINFO, ArrowValueType, _is_var_width, int64_t +from .array import _array_type +from .poolbuffer import BUFFER_STATE, TypedBufferBuilderType + + +def _data_buffer_type(arrow_type: pa.DataType) -> pa.DataType: + """What a builder appends into: raw bytes for var-width types. + + ``pa.string().byte_width`` raises ``ValueError``, so the payload buffer of + a var-width builder is typed ``uint8``. + """ + return pa.uint8() if _is_var_width(arrow_type) else arrow_type + + +def _offsets_type(arrow_type: pa.DataType) -> pa.DataType: + """``int64`` offsets for the ``large_*`` types, ``int32`` otherwise.""" + return (pa.int64() + if arrow_type in (pa.large_string(), pa.large_binary()) + else pa.int32()) + + +class ArrayBuilder: + """A builder's Python face: a typing stand-in, usable only inside @njit.""" + + arrow_type: pa.DataType + + +def _builder_class(name: str, arrow_type: pa.DataType) -> type[ArrayBuilder]: + return type(name, (ArrayBuilder,), {"arrow_type": arrow_type}) + + +Int8Builder = _builder_class("Int8Builder", pa.int8()) +Int16Builder = _builder_class("Int16Builder", pa.int16()) +Int32Builder = _builder_class("Int32Builder", pa.int32()) +Int64Builder = _builder_class("Int64Builder", pa.int64()) +UInt8Builder = _builder_class("UInt8Builder", pa.uint8()) +UInt16Builder = _builder_class("UInt16Builder", pa.uint16()) +UInt32Builder = _builder_class("UInt32Builder", pa.uint32()) +UInt64Builder = _builder_class("UInt64Builder", pa.uint64()) +Float32Builder = _builder_class("Float32Builder", pa.float32()) +Float64Builder = _builder_class("Float64Builder", pa.float64()) +BoolBuilder = _builder_class("BoolBuilder", pa.bool_()) +StringBuilder = _builder_class("StringBuilder", pa.string()) +LargeStringBuilder = _builder_class("LargeStringBuilder", pa.large_string()) +BinaryBuilder = _builder_class("BinaryBuilder", pa.binary()) +LargeBinaryBuilder = _builder_class("LargeBinaryBuilder", pa.large_binary()) + + +class ArrayBuilderType(ArrowValueType): + + def __init__(self, value_type: pa.DataType): + super().__init__(value_type, f'ArrayBuilderType({value_type})') + # Arrow buffer order, one slot per buffer the type actually has: a + # fixed-width builder has no offsets buffer. The third element is the + # buffer's slot in BUILDER_STATE, which is always three slots wide, so + # the payload layout does not depend on the type. + buffers = [('null_bitmap_builder', TypedBufferBuilderType(pa.bool_()), 0)] + if _is_var_width(value_type): + buffers.append(('offsets_builder', + TypedBufferBuilderType(_offsets_type(value_type)), 1)) + buffers.append(('data_builder', + TypedBufferBuilderType(_data_buffer_type(value_type)), + 2)) + self.buffers = tuple(buffers) + self.array_type = _array_type(value_type, True, owned=True) + + +# one typer per class: the Arrow type is baked in, since PyArrow's own types +# are not Numba types +def _builder_typer(arrow_type: pa.DataType + ) -> Callable[[TypingContext], Callable[[], nbt.Type]]: + def type_callable(context): + return lambda: ArrayBuilderType(arrow_type) + return type_callable + + +@infer_getattr +class ArrayBuilderAttribute(AttributeTemplate): + key = ArrayBuilderType + + @bound_function("ArrayBuilder.finish") + def resolve_finish(self, buffer_builder, args, kws): + if args or kws: + return + return signature(buffer_builder.array_type) + + +for _name in ('null_bitmap_builder', 'offsets_builder', 'data_builder'): + nbext.make_attribute_wrapper(ArrayBuilderType, _name, _name) + + +# {null_count, [validity, offsets, data]}: the payload of an ArrayBuilder +BUILDER_STATE = ir.LiteralStructType( + [int64_t, ir.ArrayType(BUFFER_STATE, 3)]) + + +def _offsets_buffer_type(typ: ArrayBuilderType) -> TypedBufferBuilderType: + return next(buffer_type for name, buffer_type, _ in typ.buffers + if name == 'offsets_builder') + + +@nbext.register_model(ArrayBuilderType) +class ArrayBuilderModel(nbext.models.StructModel): + + def __init__(self, dmm, fe_type): + members = [('meminfo', MEMINFO)] + members += [(name, buffer_type) + for name, buffer_type, _ in fe_type.buffers] + members.append(('null_count_ptr', nbt.CPointer(nbt.int64))) + super().__init__(dmm, fe_type, members) diff --git a/python/pyarrow/numba/poolbuffer.py b/python/pyarrow/numba/poolbuffer.py new file mode 100644 index 000000000000..a0641f6cac89 --- /dev/null +++ b/python/pyarrow/numba/poolbuffer.py @@ -0,0 +1,428 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Growable Arrow buffers backed by the C++ pool. + +``TypedBufferBuilder`` appends values (or bits, for booleans) one at a time +into a ``pa.Buffer`` owned by the Arrow memory pool. Growth doubles the +capacity. + +A buffer builder is a *handle*: its state (pool, size, capacity, data pointer) +lives in the payload of whichever builder owns it, and the owning builder's NRT +destructor frees the pool. + +Only the pieces the array builders need are exposed: ``reserve``, ``append``, +``size`` and the code-generation helpers the builder lowering calls. +""" + +from __future__ import annotations + +import ctypes + +from llvmlite import ir +from numba import extending as nbext +from numba import types as nbt +from numba.core import cgutils +from numba.core.base import BaseContext +from numba.core.typing.templates import ( + AttributeTemplate, + bound_function, + infer_getattr, + signature, +) + +import pyarrow as pa + +from ._utils import ( + ArrowValueType, + _return_arrow_error_ll, + get_pyarrow_cpp_func, + get_pyarrow_dll, + int64_t, +) + + +class TypedBufferBuilderType(ArrowValueType): + + def __init__(self, value_type: pa.DataType): + super().__init__(value_type, f'TypedBufferBuilder({value_type})') + + +@infer_getattr +class TypedBufferBuilderAttribute(AttributeTemplate): + key = TypedBufferBuilderType + + @bound_function("TypedBufferBuilder.reserve") + def resolve_reserve(self, buffer_builder, args, kws): + if kws or len(args) != 1: + return + return signature(nbt.none, nbt.int64) + + @bound_function("TypedBufferBuilder.append") + def resolve_append(self, buffer_builder, args, kws): + if kws or len(args) != 1: + return + return signature(nbt.none, buffer_builder.numba_type) + + @bound_function("TypedBufferBuilder.append_bytes") + def resolve_append_bytes(self, buffer_builder, args, kws): + if kws or len(args) != 2: + return + return signature(nbt.none, nbt.voidptr, nbt.int64) + + +@nbext.register_model(TypedBufferBuilderType) +class TypedBufferBuilderModel(nbext.models.StructModel): + def __init__(self, dmm, fe_type): + # a pointer into the owning builder's NRT payload, which keeps it alive + super().__init__(dmm, fe_type, [('state', nbt.voidptr)]) + + +# {pool, size (items), capacity (items), data}: the buffer builder's state, +# inside the payload of the builder that owns it +BUFFER_STATE = ir.LiteralStructType( + [cgutils.voidptr_t, int64_t, int64_t, cgutils.voidptr_t]) +POOL, SIZE, CAPACITY, DATA = range(4) + +FINISHED = "cannot use an Arrow builder after finish()" + + +class _PoolBufferMeta(ctypes.Structure): + """The C++ pool buffer's field offsets, in the order numba.cc fills them.""" + + _fields_ = [ + ("offset_of_data", ctypes.c_int32), + ("offset_of_size", ctypes.c_int32), + ("offset_of_capacity", ctypes.c_int32), + ] + + +def _pool_buffer_offsets() -> tuple[int, int, int]: + """``(data, size, capacity)`` byte offsets, read from the C++ layout.""" + meta = _PoolBufferMeta() + get_pyarrow_dll().PyArrow_GetPoolBufferMeta(ctypes.byref(meta)) + return (meta.offset_of_data, meta.offset_of_size, meta.offset_of_capacity) + + +(_pool_buffer_offsetof_data, _pool_buffer_offsetof_size, + _pool_buffer_offsetof_capacity) = _offsets = _pool_buffer_offsets() +if len(set(_offsets)) != 3 or not all(0 < o < 64 for o in _offsets): + raise RuntimeError( + f"unexpected PoolBuffer layout (data, size, capacity): {_offsets}") + + +def state_ptr(context: BaseContext, builder: ir.IRBuilder, + buffer_builder_type: TypedBufferBuilderType, + value: ir.Value) -> ir.Value: + """The owning builder's ``BUFFER_STATE*`` for this buffer builder. + + Parameters + ---------- + context : BaseContext + Numba target context. + builder : ir.IRBuilder + LLVM IR builder at the insertion point. + buffer_builder_type : TypedBufferBuilderType + Numba type of the buffer builder. + value : ir.Value + LLVM value of the buffer builder. + """ + handle = context.make_helper(builder, buffer_builder_type, value=value) + return builder.bitcast(handle.state, BUFFER_STATE.as_pointer()) + + +def _refresh_ll(builder: ir.IRBuilder, value_type: pa.DataType, + state: ir.Value) -> None: + """Publish the pool's byte capacity and data pointer into *state*.""" + def field_ptr(offset: int, ty: ir.Type) -> ir.Value: + pool = builder.load(cgutils.gep(builder, state, 0, POOL)) + return builder.inttoptr( + builder.add(builder.ptrtoint(pool, int64_t), int64_t(offset)), + ty.as_pointer()) + + capacity = builder.load(field_ptr(_pool_buffer_offsetof_capacity, int64_t)) + data = builder.load(field_ptr(_pool_buffer_offsetof_data, cgutils.voidptr_t)) + builder.store(get_item_capacity(builder, value_type, capacity), + cgutils.gep(builder, state, 0, CAPACITY)) + builder.store(data, cgutils.gep(builder, state, 0, DATA)) + + +def init_ll(context: BaseContext, builder: ir.IRBuilder, + value_type: pa.DataType, slot: ir.Value, + pool: ir.Value) -> ir.Value: + """A buffer-builder handle whose state is *slot* in the builder's payload. + + Parameters + ---------- + context : BaseContext + Numba target context. + builder : ir.IRBuilder + LLVM IR builder at the insertion point. + value_type : pa.DataType + Arrow type of the buffer's items. + slot : ir.Value + Pointer to the state slot in the owning builder's payload. + pool : ir.Value + Pool buffer the handle wraps. + """ + builder.store(pool, cgutils.gep(builder, slot, 0, POOL)) + builder.store(ir.Constant(int64_t, 0), cgutils.gep(builder, slot, 0, SIZE)) + _refresh_ll(builder, value_type, slot) + + handle = cgutils.create_struct_proxy( + TypedBufferBuilderType(value_type))(context, builder) + handle.state = builder.bitcast(slot, cgutils.voidptr_t) + return handle._getvalue() + + +def _checked_call_ll(context: BaseContext, builder: ir.IRBuilder, + func_name: str, args: list[ir.Value]) -> None: + """Call a ``PyArrow_*`` helper whose negative status is an error.""" + fn = get_pyarrow_cpp_func(builder, func_name) + status = builder.call(fn, args) + # the helper returns the Arrow status as a signed int: negative is an error + # and leaves a Python exception set + with builder.if_then(builder.icmp_signed('<', status, status.type(0))): + _return_arrow_error_ll(context, builder) + + +def grow_ll(context: BaseContext, builder: ir.IRBuilder, + value_type: pa.DataType, state: ir.Value, + new_capacity: ir.Value) -> None: + """Reserve *new_capacity* items and publish the pool buffer's new state. + + Parameters + ---------- + context : BaseContext + Numba target context. + builder : ir.IRBuilder + LLVM IR builder at the insertion point. + value_type : pa.DataType + Arrow type of the buffer's items. + state : ir.Value + Pointer to the buffer state. + new_capacity : ir.Value + Capacity to reserve, in items. + """ + pool = builder.load(cgutils.gep(builder, state, 0, POOL)) + with builder.if_then(cgutils.is_null(builder, pool)): + context.call_conv.return_user_exc(builder, RuntimeError, (FINISHED,)) + # a negative request would wrap to a huge byte capacity and leave a + # capacity the pool never had + with builder.if_then(builder.icmp_signed('<', new_capacity, + new_capacity.type(0))): + context.call_conv.return_user_exc( + builder, ValueError, ("cannot reserve a negative capacity",)) + _checked_call_ll( + context, builder, 'PyArrow_PoolBufferReserve', + [pool, get_byte_capacity(builder, value_type, new_capacity)]) + _refresh_ll(builder, value_type, state) + + +def _make_room_ll(context: BaseContext, builder: ir.IRBuilder, + value_type: pa.DataType, state: ir.Value, + needed: ir.Value) -> None: + """Grow the pool once when *needed* items do not fit; both appends share it.""" + capacity = builder.load(cgutils.gep(builder, state, 0, CAPACITY)) + with builder.if_then(builder.icmp_signed('<', capacity, needed), + likely=False): + grow_ll(context, builder, value_type, state, + builder.mul(needed, capacity.type(2))) + + +def append_bit_ll(builder: ir.IRBuilder, data: ir.Value, index: ir.Value, + value: ir.Value) -> None: + """Write bit *index* of the bitmap at *data* to the ``i1`` *value*. + + Clear the target bit, then OR in its value. Constant values fold to + one AND or OR; variable values need no branch or select. + + Parameters + ---------- + builder : ir.IRBuilder + LLVM IR builder at the insertion point. + data : ir.Value + Start of the bitmap. + index : ir.Value + Bit position. + value : ir.Value + Bit to write. + """ + byte_ptr = builder.gep(data, [builder.udiv(index, index.type(8))]) + shift = builder.trunc(builder.urem(index, index.type(8)), cgutils.int8_t) + mask = builder.shl(cgutils.int8_t(1), shift) + bit = builder.shl(builder.zext(value, cgutils.int8_t), shift) + builder.store(builder.or_(builder.and_(builder.load(byte_ptr), + builder.not_(mask)), bit), + byte_ptr) + + +def append_ll(context: BaseContext, builder: ir.IRBuilder, + value_type: pa.DataType, state: ir.Value, + data_value: ir.Value) -> None: + """Append *data_value* to the pool-backed buffer at *state*. + + Parameters + ---------- + context : BaseContext + Numba target context. + builder : ir.IRBuilder + LLVM IR builder at the insertion point. + value_type : pa.DataType + Arrow type of the buffer's items. + state : ir.Value + Pointer to the buffer state. + data_value : ir.Value + Value to append. + """ + index = builder.load(cgutils.gep(builder, state, 0, SIZE)) + index_plus_one = builder.add(index, index.type(1)) + _make_room_ll(context, builder, value_type, state, index_plus_one) + + data = builder.load(cgutils.gep(builder, state, 0, DATA)) + if pa.types.is_boolean(value_type): + append_bit_ll(builder, data, index, data_value) + else: + data = builder.bitcast(data, data_value.type.as_pointer()) + builder.store(data_value, builder.gep(data, [index])) + builder.store(index_plus_one, cgutils.gep(builder, state, 0, SIZE)) + + +def finish_ll(context: BaseContext, builder: ir.IRBuilder, + value_type: pa.DataType, state: ir.Value) -> ir.Value: + """Shrink the pool to the appended size; returns the pool pointer. + + May raise: the caller still owns the builder and everything in it, so a + failed ``finish()`` leaves a consistent builder behind. + + Parameters + ---------- + context : BaseContext + Numba target context. + builder : ir.IRBuilder + LLVM IR builder at the insertion point. + value_type : pa.DataType + Arrow type of the buffer's items. + state : ir.Value + Pointer to the buffer state. + """ + size = builder.load(cgutils.gep(builder, state, 0, SIZE)) + _checked_call_ll( + context, builder, 'PyArrow_PoolBufferResizeExactly', + [builder.load(cgutils.gep(builder, state, 0, POOL)), + get_byte_capacity(builder, value_type, size)]) + _refresh_ll(builder, value_type, state) + return builder.load(cgutils.gep(builder, state, 0, POOL)) + + +def release_ll(builder: ir.IRBuilder, state: ir.Value) -> None: + """Give up the pool: the array owns it from here. + + Parameters + ---------- + builder : ir.IRBuilder + LLVM IR builder at the insertion point. + state : ir.Value + Pointer to the buffer state. + """ + builder.store(ir.Constant(cgutils.voidptr_t, None), + cgutils.gep(builder, state, 0, POOL)) + builder.store(ir.Constant(int64_t, -1), cgutils.gep(builder, state, 0, CAPACITY)) + + +def get_item_capacity(builder: ir.IRBuilder, item_type: pa.DataType, + byte_capacity: ir.Value) -> ir.Value: + if pa.types.is_boolean(item_type): + return builder.mul(byte_capacity, byte_capacity.type(8)) + return builder.udiv(byte_capacity, byte_capacity.type(item_type.byte_width)) + + +def get_byte_capacity(builder: ir.IRBuilder, item_type: pa.DataType, + item_capacity: ir.Value) -> ir.Value: + if pa.types.is_boolean(item_type): + return builder.udiv(builder.add(item_capacity, item_capacity.type(7)), + item_capacity.type(8)) + return builder.mul(item_capacity, item_capacity.type(item_type.byte_width)) + + +@nbext.overload_attribute(TypedBufferBuilderType, 'size', inline="always") +def typed_buffer_builder_size(buffer_builder): + def get(buffer_builder): + return typed_buffer_builder_size_ll(buffer_builder) + + return get + + +@nbext.intrinsic +def typed_buffer_builder_size_ll(typingctx, buffer_builder_type): + assert isinstance(buffer_builder_type, TypedBufferBuilderType) + sig = nbt.int64(buffer_builder_type) + + def codegen(context, builder, signature, args): + state = state_ptr(context, builder, signature.args[0], args[0]) + return builder.load(cgutils.gep(builder, state, 0, SIZE)) + + return sig, codegen + + +@nbext.lower_builtin('TypedBufferBuilder.reserve', + TypedBufferBuilderType, nbt.int64) +def typed_buffer_builder_reserve(context, builder, sig, args): + state = state_ptr(context, builder, sig.args[0], args[0]) + size = builder.load(cgutils.gep(builder, state, 0, SIZE)) + grow_ll(context, builder, sig.args[0].arrow_type, state, + builder.add(size, args[1])) + return context.get_dummy_value() + + +@nbext.lower_builtin('TypedBufferBuilder.append', TypedBufferBuilderType, nbt.Any) +def typed_buffer_builder_append(context, builder, sig, args): + state = state_ptr(context, builder, sig.args[0], args[0]) + append_ll(context, builder, sig.args[0].arrow_type, state, args[1]) + return context.get_dummy_value() + + +@nbext.lower_builtin('TypedBufferBuilder.append_bytes', + TypedBufferBuilderType, nbt.voidptr, nbt.int64) +def typed_buffer_builder_append_bytes(context, builder, sig, args): + """Copy *nbytes* from *source* in one capacity check and one memcpy. + + Parameters + ---------- + context : BaseContext + Numba target context. + builder : ir.IRBuilder + LLVM IR builder at the insertion point. + sig : Signature + Signature of the lowered call. + args : tuple[ir.Value, ...] + LLVM values of the call's arguments. + """ + value_type = sig.args[0].arrow_type + state = state_ptr(context, builder, sig.args[0], args[0]) + source, nbytes = args[1], args[2] + + index = builder.load(cgutils.gep(builder, state, 0, SIZE)) + needed = builder.add(index, nbytes) + _make_room_ll(context, builder, value_type, state, needed) + + data = builder.load(cgutils.gep(builder, state, 0, DATA)) + destination = builder.gep(builder.bitcast(data, ir.IntType(8).as_pointer()), + [index]) + cgutils.raw_memcpy(builder, destination, source, nbytes, 1) + builder.store(needed, cgutils.gep(builder, state, 0, SIZE)) + return context.get_dummy_value() diff --git a/python/pyarrow/src/arrow/python/numba.cc b/python/pyarrow/src/arrow/python/numba.cc new file mode 100644 index 000000000000..c36c92a6a282 --- /dev/null +++ b/python/pyarrow/src/arrow/python/numba.cc @@ -0,0 +1,125 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "arrow/python/numba.h" + +#include "arrow/array/data.h" +#include "arrow/array/util.h" +#include "arrow/array/validate.h" +#include "arrow/buffer.h" +#include "arrow/c/bridge.h" +#include "arrow/c/helpers.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/macros.h" + +#include "arrow/python/common.h" +#include "arrow/python/pyarrow.h" + +namespace arrow::py::internal { +namespace { + +static_assert(sizeof(std::unique_ptr) == sizeof(ResizableBuffer*)); + +class DummyBuffer : public ResizableBuffer { + public: + DummyBuffer() : ResizableBuffer(nullptr, 0) {} + + Status Resize(const int64_t new_size, bool shrink_to_fit) override { + return Status::OK(); + } + + Status Reserve(const int64_t new_capacity) override { return Status::OK(); } + + PyArrow_PoolBufferMeta GetInstanceMeta() const { + // HACK because we are not able to call offsetof on a protected member field. +#define CUSTOM_OFFSETOF(_member) \ + static_cast(reinterpret_cast(&this->_member) - \ + reinterpret_cast(this)) + + return PyArrow_PoolBufferMeta{ + .offset_of_data = CUSTOM_OFFSETOF(data_), + .offset_of_size = CUSTOM_OFFSETOF(size_), + .offset_of_capacity = CUSTOM_OFFSETOF(capacity_), + }; + +#undef CUSTOM_OFFSETOF + } + + static PyArrow_PoolBufferMeta GetMeta() { + static const auto meta = DummyBuffer().GetInstanceMeta(); + return meta; + } +}; + +} // namespace +} // namespace arrow::py::internal + +void PyArrow_GetPoolBufferMeta(PyArrow_PoolBufferMeta* out) { + using namespace arrow; + *out = py::internal::DummyBuffer::GetMeta(); +} + +PyArrow_PoolBufferPtr PyArrow_AllocatePoolBuffer(int64_t size) { + using namespace arrow; + // Will raise an exception and returning a null unique_ptr on error + auto buffer = py::GetResultValue(AllocateResizableBuffer(size)); + return reinterpret_cast(buffer.release()); +} + +int32_t PyArrow_PoolBufferReserve(PyArrow_PoolBufferPtr buf_ptr, int64_t capacity) { + using namespace arrow; + auto buf = reinterpret_cast(buf_ptr); + return py::internal::check_status(buf->Reserve(capacity)); +} + +int32_t PyArrow_PoolBufferResizeExactly(PyArrow_PoolBufferPtr buf_ptr, int64_t size) { + using namespace arrow; + auto buf = reinterpret_cast(buf_ptr); + return py::internal::check_status(buf->Resize(size, /*shrink_to_fit=*/true)); +} + +void PyArrow_PoolBufferDestroy(PyArrow_PoolBufferPtr buf_ptr) { + using namespace arrow; + auto to_destroy = + std::unique_ptr(reinterpret_cast(buf_ptr)); + ARROW_UNUSED(to_destroy); +} + +int32_t PyArrow_MakeAndExportArray(int32_t type_id, int64_t length, int64_t null_count, + int32_t num_buffers, + PyArrow_PoolBufferPtr* buffer_ptrs, ArrowArray* out) { + using namespace arrow; + // owned from here: on any error below they are freed with the vector + BufferVector buffers(num_buffers); + for (int32_t i = 0; i < num_buffers; ++i) { + if (buffer_ptrs[i] != nullptr) { + auto buf = reinterpret_cast(buffer_ptrs[i]); + buffers[i] = std::shared_ptr(std::unique_ptr(buf)); + } + } + return py::internal::check_status([&]() -> Status { + ARROW_ASSIGN_OR_RAISE(auto type, type_singleton(static_cast(type_id))); + auto data = ArrayData::Make(std::move(type), length, std::move(buffers), null_count); + // buffer sizes against the length: catches a builder whose buffers + // disagree + RETURN_NOT_OK(internal::ValidateArray(*data)); + return ExportArray(std::move(data), out); + }()); +} + +void PyArrow_ReleaseArray(ArrowArray* array) { ArrowArrayRelease(array); } diff --git a/python/pyarrow/src/arrow/python/numba.h b/python/pyarrow/src/arrow/python/numba.h new file mode 100644 index 000000000000..d8dc0a473a44 --- /dev/null +++ b/python/pyarrow/src/arrow/python/numba.h @@ -0,0 +1,65 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/c/abi.h" +#include "arrow/python/platform.h" +#include "arrow/python/visibility.h" + +extern "C" { + +struct PyArrow_PoolBuffer; +typedef PyArrow_PoolBuffer* PyArrow_PoolBufferPtr; + +struct PyArrow_PoolBufferMeta { + int32_t offset_of_data; + int32_t offset_of_size; + int32_t offset_of_capacity; +}; + +ARROW_PYTHON_EXPORT +void PyArrow_GetPoolBufferMeta(PyArrow_PoolBufferMeta* out); + +// On error these set a Python exception and report it: a null pointer from +// PyArrow_AllocatePoolBuffer, a negative status from the others. The +// exceptions go through the C API that importing pyarrow.lib initializes. +ARROW_PYTHON_EXPORT +PyArrow_PoolBufferPtr PyArrow_AllocatePoolBuffer(int64_t size); + +ARROW_PYTHON_EXPORT +int32_t PyArrow_PoolBufferReserve(PyArrow_PoolBufferPtr buf, int64_t capacity); + +ARROW_PYTHON_EXPORT +int32_t PyArrow_PoolBufferResizeExactly(PyArrow_PoolBufferPtr buf, int64_t size); + +ARROW_PYTHON_EXPORT +void PyArrow_PoolBufferDestroy(PyArrow_PoolBufferPtr buf); + +// Takes the buffers in every case, error or not. Validates the array against +// its type and length (buffer sizes, not each value) before exporting it. +ARROW_PYTHON_EXPORT +int32_t PyArrow_MakeAndExportArray(int32_t type_id, int64_t length, int64_t null_count, + int32_t num_buffers, PyArrow_PoolBufferPtr* buffers, + ArrowArray* out); + +ARROW_PYTHON_EXPORT +void PyArrow_ReleaseArray(ArrowArray* array); + +} // extern "C" diff --git a/python/pyarrow/tests/numba_util.py b/python/pyarrow/tests/numba_util.py new file mode 100644 index 000000000000..921323883943 --- /dev/null +++ b/python/pyarrow/tests/numba_util.py @@ -0,0 +1,101 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Shared producers and compiled kernels for the numba tests and benchmarks. + +Test modules import this only after ``pytest.importorskip("numba")``: importing +it imports numba and ``pyarrow.numba``. +""" + +import numpy as np +from numba import njit + +from pyarrow.numba import is_valid, register_producer, string_len + + +@register_producer +class ArrayProducer: + """A foreign producer: hands out a real array's C array capsule.""" + + def __init__(self, array): + self._array = array + + def __arrow_c_array__(self, requested_schema=None): + return self._array.__arrow_c_array__(requested_schema) + + +@register_producer +class StreamProducer: + """A stream-only producer (the polars/duckdb shape).""" + + def __init__(self, source): + self._source = source + + def __arrow_c_stream__(self, requested_schema=None): + return self._source.__arrow_c_stream__(requested_schema) + + +@njit +def at(a, i): + return a[i] + + +@njit +def valid_at(a, i): + return is_valid(a, i) + + +@njit +def sum_and_nulls(a): + total = 0 + nulls = 0 + for i in range(len(a)): + if a[i] is None: + nulls += 1 + else: + total += a[i] + return total, nulls + + +@njit +def total(a): + acc = 0 + for i in range(len(a)): + if a[i] is not None: + acc += a[i] + return acc + + +@njit +def valid_flags(a): + out = np.zeros(len(a), np.bool_) + for i in range(len(a)): + out[i] = is_valid(a, i) + return out + + +@njit +def sizes(a): + """Byte length per element, -1 for a null (a string column).""" + out = np.zeros(len(a), np.int64) + for i in range(len(a)): + valid = is_valid(a, i) + if valid: + out[i] = string_len(a[i]) + else: + out[i] = -1 + return out diff --git a/python/pyarrow/tests/test_numba.py b/python/pyarrow/tests/test_numba.py new file mode 100644 index 000000000000..d92611c4cb53 --- /dev/null +++ b/python/pyarrow/tests/test_numba.py @@ -0,0 +1,381 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Reading Arrow arrays: element types, nulls, producers, layouts.""" + +from decimal import Decimal, localcontext + +import pytest + +import pyarrow as pa + +nb = pytest.importorskip("numba") +import numpy as np # noqa: E402 (numba requires numpy) + +from numba.core.errors import TypingError # noqa: E402 + +from pyarrow.numba import _register # noqa: E402 (registers the extension) +from pyarrow.numba import ( # noqa: E402 + decimal_to_float, + from_any, + is_valid, + string_len, +) +from pyarrow.tests.numba_util import ( # noqa: E402 + StreamProducer, + at, + sizes, + sum_and_nulls, + total, + valid_at, + valid_flags, +) + +_register() + + +def test_doc_example_reads_a_pyarrow_array(): + arr = pa.array([2, 3, None] * 50) + assert sum_and_nulls(arr) == (250, 50) + + +INDEX_TYPES = { + "int64": ([10, None, 30], [10, None, 30], pa.int64()), + "bool": ([True, None, False], [True, None, False], pa.bool_()), + "string": (["ab", None, "c"], [b"ab", None, b"c"], pa.string()), + "decimal128": ([Decimal("1.5"), None, Decimal("-2.5")], + [(0, 15), None, (-1, 2 ** 64 - 25)], + pa.decimal128(5, 1)), +} + + +@pytest.mark.parametrize("container", ["array"]) +@pytest.mark.parametrize("type_name", list(INDEX_TYPES)) +def test_index_forms_and_bounds(type_name, container): + """Positive, negative and out-of-range indexes on every element kind.""" + values, expected, pa_type = INDEX_TYPES[type_name] + array = pa.array(values, type=pa_type) + data = array + + assert [at(data, i) for i in range(3)] == expected + assert at(data, -1) == expected[-1] + for bad in (3, -4): + with pytest.raises(IndexError, match="out of range"): + at(data, bad) + with pytest.raises(IndexError, match="out of range"): + valid_at(data, bad) + + assert valid_flags(data).tolist() == [value is not None for value in values] + assert valid_at(data, -1) is (values[-1] is not None) + + +@pytest.mark.parametrize("container", ["array"]) +def test_non_integer_index_is_a_typing_error(container): + array = pa.array([1, 2, 3]) + + @nb.njit + def frac_index(a, i): + return a[i] + + for func in (frac_index, valid_at): + with pytest.raises(TypingError, match="array indices must be integers"): + func(array, 1.5) + + +def test_is_valid_matches_pyarrow(): + array = pa.array([1, None, 3, None]) + assert valid_flags(array).tolist() == array.is_valid().to_pylist() + + +SCALAR_TYPES = [ + pa.int8(), pa.int16(), pa.int32(), pa.int64(), + pa.uint8(), pa.uint16(), pa.uint32(), pa.uint64(), + pa.float32(), pa.float64(), + pa.date32(), pa.date64(), pa.time32("s"), pa.time64("us"), + pa.timestamp("us"), pa.duration("s"), +] + + +@pytest.mark.parametrize("pa_type", SCALAR_TYPES, ids=str) +@pytest.mark.parametrize("offset", [0, 1]) +def test_scalar_types_read_values_and_nulls(pa_type, offset): + values = [1, None, 3, 4] + view = pa.array(values, type=pa_type).slice(offset) + expected = values[offset:] + + @nb.njit + def read(a): + out = np.zeros(len(a), np.float64) + valid = np.zeros(len(a), np.bool_) + for i in range(len(a)): + valid[i] = is_valid(a, i) + v = a[i] + if v is not None: + out[i] = v + return out, valid + + out, valid = read(view) + assert valid.tolist() == [v is not None for v in expected] + assert out.tolist() == [0.0 if v is None else float(v) for v in expected] + + +def test_array_attributes(): + view = pa.array([1, None, 3, None]).slice(1) + + @nb.njit + def attributes(a): + return a.length, a.null_count, a.offset + + assert attributes(view) == (3, 2, 1) + + +@pytest.mark.parametrize("pa_type,payloads", [ + (pa.string(), [b"abc", None, b"", b"de"]), + (pa.large_string(), [b"abc", None, b"", b"de"]), + (pa.binary(), [b"abc", None, b"", b"de"]), + (pa.large_binary(), [b"abc", None, b"", b"de"]), + (pa.binary(3), [b"abc", None, b"xyz", b"def"]), +], ids=["string", "large_string", "binary", "large_binary", + "fixed_size_binary"]) +@pytest.mark.parametrize("offset", [0, 1]) +def test_string_types_read_views(pa_type, payloads, offset): + view = pa.array(payloads, type=pa_type).slice(offset) + expected = payloads[offset:] + + assert sizes(view).tolist() == [-1 if p is None else len(p) for p in expected] + assert valid_flags(view).tolist() == [p is not None for p in expected] + # a returned element boxes as bytes, and a null one as None + assert [at(view, i) for i in range(len(expected))] == expected + + +BOOLEANS = [True, False, True, True, False, False, True, False, + None, True, False, None, True, True, False, True, False] + + +@pytest.mark.parametrize("offset", range(8)) +def test_boolean_read_every_bit_offset(offset): + """Every bit position inside a byte, across the array's bytes.""" + view = pa.array(BOOLEANS, type=pa.bool_()).slice(offset) + expected = BOOLEANS[offset:] + + @nb.njit + def read(a): + values = np.zeros(len(a), np.bool_) + valid = np.zeros(len(a), np.bool_) + missing = np.zeros(len(a), np.bool_) + for i in range(len(a)): + valid[i] = is_valid(a, i) + missing[i] = a[i] is None + v = a[i] + if v is not None: + values[i] = v + return values, valid, missing + + values, valid, missing = read(view) + assert missing.tolist() == [v is None for v in expected] + assert valid.tolist() == [v is not None for v in expected] + assert values.tolist() == [bool(v) if v is not None else False + for v in expected] + + +def test_boolean_read_without_a_null_bitmap(): + view = pa.array([True, False, True], type=pa.bool_()) + assert view.null_count == 0 + + @nb.njit + def read(a): + out = np.zeros(len(a), np.int64) + for i in range(len(a)): + valid = 1 if is_valid(a, i) else 0 + present = 2 if a[i] is not None else 0 + out[i] = valid + present + return out + + assert read(view).tolist() == [3, 3, 3] + + +def test_boolean_read_all_null(): + view = pa.nulls(5, type=pa.bool_()) + assert valid_flags(view).tolist() == [False] * 5 + assert total(view) == 0 + + +def test_boolean_read_empty(): + view = pa.array([], type=pa.bool_()) + assert len(view) == 0 + assert sum_and_nulls(view) == (0, 0) + + +@pytest.mark.parametrize("pa_type", [pa.string(), pa.binary(), + pa.binary(3)], + ids=["string", "binary", "fixed_size_binary"]) +def test_string_view_carries_validity(pa_type): + payloads = ([b"abc", None, b"", b"de"] if not pa.types.is_fixed_size_binary( + pa_type) else [b"abc", None, b"xyz", b"def"]) + view = pa.array(payloads, type=pa_type).slice(1) + + @nb.njit + def flags(a): + out = np.zeros(len(a), np.bool_) + for i in range(len(a)): + out[i] = a[i].valid + return out + + assert flags(view).tolist() == [p is not None for p in payloads[1:]] + + +@pytest.mark.parametrize("null_count", [0, -1], ids=["known_dense", "unknown"]) +def test_validity_bitmap_with_no_nulls(null_count): + """A bitmap that marks nothing null must not change the values.""" + data = pa.py_buffer(np.array([10, 20, 30], dtype=np.int64)) + bitmap = pa.py_buffer(np.array([0b111], dtype=np.uint8)) # all valid + array = pa.Array.from_buffers(pa.int64(), 3, [bitmap, data], + null_count=null_count) + + assert total(array) == 60 + assert valid_flags(array).tolist() == [True, True, True] + + +def test_decimal128_reads_exactly(): + values = [Decimal("12345.67"), None, Decimal("-0.01")] + array = pa.array(values, type=pa.decimal128(20, 2)) + + @nb.njit + def as_float(a, i): + return decimal_to_float(a[i], 2) + + @nb.njit + def ordered(a, i, j): + return a[i] < a[j] + + def unscaled(i): + raw = at(array, i) + return None if raw is None else Decimal(raw[0] * 2 ** 64 + raw[1]) + + assert [unscaled(i) for i in range(3)] == [Decimal(1234567), None, Decimal(-1)] + assert as_float(array, 0) == float(values[0]) + assert as_float(array, 2) == float(values[2]) + assert ordered(array, 2, 0) # -0.01 < 12345.67 + + +@pytest.mark.parametrize("unscaled", [ + 1234567, 2 ** 63 + 5, -1, -(2 ** 80) + 7, 2 ** 100, +], ids=["small", "high_bit", "minus_one", "wide_negative", "wide_positive"]) +def test_decimal_words_and_float(unscaled): + """Every branch of decimal_to_float, and the exact two-word value.""" + array = pa.array([Decimal(unscaled)], type=pa.decimal128(38, 0)) + + @nb.njit + def words(a): + return a[0] + + @nb.njit + def as_float(a): + return decimal_to_float(a[0], 0) + + high, low = words(array) + assert Decimal(high * 2 ** 64 + low) == Decimal(unscaled) + assert as_float(array) == float(unscaled) + + with localcontext() as ctx: + ctx.prec = 60 + assert Decimal(high * 2 ** 64 + low).scaleb(0) == Decimal(unscaled) + + +PANDAS_PRODUCER = pytest.param( + lambda: pytest.importorskip("pandas").Series([2, 3, None, 5]), + id="pandas") +POLARS_PRODUCER = pytest.param( + lambda: pytest.importorskip("polars").Series("x", [2, 3, None, 5]), + id="polars") +IBIS_PRODUCER = pytest.param( + lambda: pytest.importorskip("ibis").memtable({"x": [2, 3, None, 5]}), + id="ibis") +DUCKDB_PRODUCER = pytest.param( + lambda: pytest.importorskip("duckdb").sql( + "select * from (values (2), (3), (null), (5)) t(x)"), + id="duckdb") + + +@pytest.mark.parametrize("make_producer", [ + POLARS_PRODUCER, PANDAS_PRODUCER, IBIS_PRODUCER, DUCKDB_PRODUCER, +]) +def test_reads_a_third_party_producer(make_producer): + from pyarrow.numba import register_producer + + producer = make_producer() + register_producer(type(producer)) + assert sum_and_nulls(producer) == (10, 1) + + +def test_polars_series_is_read_zero_copy(): + pl = pytest.importorskip("polars") + + series = pl.Series([2, 3, None, 5]) + # polars is stream-only: from_any() imports the stream's single chunk + assert (from_any(series).buffers()[1].address + == series.to_arrow().buffers()[1].address) + + +@pytest.mark.parametrize("unsupported,value", [ + (pa.list_(pa.int64()), [1]), + (pa.dictionary(pa.int32(), pa.string()), "a"), + (pa.decimal256(40, 2), Decimal(1)), +], ids=["list", "dictionary", "decimal256"]) +def test_unsupported_types_raise_at_typing(unsupported, value): + array = pa.array([value], type=unsupported) + + with pytest.raises((TypeError, TypingError), + match="Unsupported PyArrow type"): + at(array, 0) + + +def test_returning_a_borrowed_array_is_refused(): + @nb.njit + def ident(a): + return a + + with pytest.raises(NotImplementedError, + match="cannot return an Arrow array argument"): + ident(pa.array([1, 2])) + + +def test_helpers_reject_other_types(): + @nb.njit + def lengths(value): + return string_len(value) + + @nb.njit + def three_words(value): + return decimal_to_float((1, 2, 3), 0) + + @nb.njit + def float_scale(value): + return decimal_to_float((1, 2), 1.5) + + for kernel, argument in ((lengths, 1), (three_words, 1), + (float_scale, 1)): + with pytest.raises(TypingError): + kernel(argument) + + +def test_stream_producer_reads_one_chunk(): + stream = StreamProducer(pa.chunked_array([[1, 2, 3]], type=pa.int64())) + assert total(stream) == 6 + + with pytest.raises(TypeError, match="more than one chunk"): + total(StreamProducer(pa.chunked_array([[1, 2], [3]], type=pa.int64()))) diff --git a/python/pyarrow/tests/test_numba_builder.py b/python/pyarrow/tests/test_numba_builder.py new file mode 100644 index 000000000000..14dee1e89ed2 --- /dev/null +++ b/python/pyarrow/tests/test_numba_builder.py @@ -0,0 +1,524 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Building Arrow arrays in compiled code: values, ownership, failures.""" + +import gc + +import pytest + +import pyarrow as pa + +nb = pytest.importorskip("numba") + +from numba.core.errors import TypingError # noqa: E402 + +import pyarrow.numba as apn # noqa: E402 +from pyarrow.numba import is_valid, string_len # noqa: E402 + +# the most memory a thousand builder calls may retain +LEAK_LIMIT = 1 << 16 + + +def _grown(func, *args): + """Bytes the Arrow pool grew by over 1000 calls of *func*.""" + pool = pa.default_memory_pool() + before = pool.bytes_allocated() + for _ in range(1000): + try: + func(*args) + except Exception: + pass + gc.collect() + return pool.bytes_allocated() - before + + +def test_many_builds_do_not_leak_pool_memory(): + @nb.njit + def build(n): + b = apn.Float64Builder() + b.reserve(n) + for i in range(n): + b.append(i * 0.5) + return b.finish() + + assert build(4).to_pylist() == [0.0, 0.5, 1.0, 1.5] # warm up + assert _grown(build, 16) < LEAK_LIMIT + + +@pytest.mark.parametrize("builder_name,pa_type,expected", [ + ("StringBuilder", pa.string(), ["ab", None, "", "cde"]), + ("LargeStringBuilder", pa.large_string(), ["ab", None, "", "cde"]), + ("BinaryBuilder", pa.binary(), [b"ab", None, b"", b"cde"]), + ("LargeBinaryBuilder", pa.large_binary(), [b"ab", None, b"", b"cde"]), +]) +def test_var_width_builders(builder_name, pa_type, expected): + builder_cls = getattr(apn, builder_name) + + @nb.njit + def build(): + b = builder_cls() + b.append(b"ab") + b.append(None) + b.append(b"") + b.append(b"cde") + return b.finish() + + out = build() + assert out.type == pa_type + assert out.to_pylist() == expected # pyarrow decodes bytes to str + assert out.null_count == 1 + out.validate(full=True) + + +@pytest.mark.parametrize("builder_name,pa_type,values", [ + ("Int8Builder", pa.int8(), [1, None, 3]), + ("Int16Builder", pa.int16(), [1, None, 3]), + ("Int32Builder", pa.int32(), [1, None, 3]), + ("Int64Builder", pa.int64(), [1, None, 3]), + ("UInt8Builder", pa.uint8(), [1, None, 3]), + ("UInt16Builder", pa.uint16(), [1, None, 3]), + ("UInt32Builder", pa.uint32(), [1, None, 3]), + ("UInt64Builder", pa.uint64(), [1, None, 3]), + ("Float32Builder", pa.float32(), [0.5, None, 1.5]), + ("Float64Builder", pa.float64(), [0.5, None, 1.5]), + ("BoolBuilder", pa.bool_(), [True, None, False]), +]) +def test_every_builder_round_trips(builder_name, pa_type, values): + builder_cls = getattr(apn, builder_name) + + # literals inside the compiled function: freevar lists do not lower + if pa.types.is_boolean(pa_type): + @nb.njit + def build(): + b = builder_cls() + b.reserve(3) + b.append(True) + b.append(None) + b.append(False) + return b.finish() + elif pa.types.is_floating(pa_type): + @nb.njit + def build(): + b = builder_cls() + b.reserve(3) + b.append(0.5) + b.append(None) + b.append(1.5) + return b.finish() + else: + @nb.njit + def build(): + b = builder_cls() + b.reserve(3) + b.append(1) + b.append(None) + b.append(3) + return b.finish() + + out = build() + assert out.type == pa_type + assert out.to_pylist() == values + + +def test_bool_builder_crosses_a_byte(): + @nb.njit + def build(): + b = apn.BoolBuilder() + b.reserve(10) + for i in range(10): + if i % 3 == 1: + b.append(None) + else: + b.append(i % 2 == 0) + return b.finish() + + out = build() + assert out.type == pa.bool_() + # nulls every third (i % 3 == 1), value is i % 2 == 0 + assert out.to_pylist() == [True, None, True, False, None, False, True, + None, True, False] + + +def test_string_builder_appends_from_a_view(): + source = pa.array([b"abc", None, b"de"], type=pa.string()) + + @nb.njit + def copy_valid(a): + b = apn.StringBuilder() + for i in range(len(a)): + v = a[i] + if v.valid: + b.append(v) + else: + b.append(None) + return b.finish() + + out = copy_valid(source) + assert out.to_pylist() == ["abc", None, "de"] + out.validate(full=True) + + +def test_string_builder_copies_long_and_sliced_views(): + """One append can outgrow the buffer, and a slice starts mid-buffer.""" + source = pa.array([b"x" * 100, b"y", b"z" * 300], type=pa.string())[1:] + + @nb.njit + def copy(a): + b = apn.StringBuilder() + for i in range(len(a)): + b.append(a[i]) + return b.finish() + + out = copy(source) + assert out.to_pylist() == ["y", "z" * 300] + out.validate(full=True) + + +@pytest.mark.parametrize("builder_name,pa_type,expected", [ + ("StringBuilder", pa.string(), ["ab", None, "c"]), + ("BinaryBuilder", pa.binary(), [b"ab", None, b"c"]), +]) +def test_var_width_builder_appends_null_views_as_nulls(builder_name, pa_type, + expected): + """A null view is a null, not an empty value.""" + builder_cls = getattr(apn, builder_name) + source = pa.array([b"ab", None, b"c"], type=pa_type) + + @nb.njit + def copy(a): + b = builder_cls() + for i in range(len(a)): + b.append(a[i]) # no .valid check on purpose + return b.finish() + + out = copy(source) + assert out.null_count == 1 + assert out.to_pylist() == expected + out.validate(full=True) + + +def test_string_builder_reserve_then_append(): + @nb.njit + def build(n): + b = apn.StringBuilder() + b.reserve(n) + for _ in range(n): + b.append(b"xy") + return b.finish() + + assert build(5).to_pylist() == ["xy"] * 5 + + +@pytest.mark.parametrize("builder_name", ["StringBuilder", + "LargeStringBuilder", + "BinaryBuilder", + "LargeBinaryBuilder"]) +@pytest.mark.parametrize("n", [0, 4]) +def test_var_width_offsets(builder_name, n): + """One extra offset, seeded once: a second seed would shift them all.""" + builder_cls = getattr(apn, builder_name) + is_binary = builder_name.endswith("BinaryBuilder") + + @nb.njit + def build(count): + b = builder_cls() + for _ in range(count): + b.append(b"xy") + return b.finish() + + out = build(n) + offsets = out.buffers()[1] + width = 8 if "Large" in builder_name else 4 + assert len(offsets) == width * (n + 1) + assert offsets.to_pybytes()[:width] == b"\x00" * width + assert out.to_pylist() == ([b"xy"] * n if is_binary else ["xy"] * n) + out.validate(full=True) + + +def test_pool_buffer_offsets_come_from_the_cpp_layout(): + """The offsets are read from numba.cc, not hardcoded: three sane fields.""" + from pyarrow.numba import poolbuffer + + offsets = poolbuffer._pool_buffer_offsets() + assert len(set(offsets)) == 3, offsets + assert all(0 < offset < 64 for offset in offsets), offsets + assert offsets == (poolbuffer._pool_buffer_offsetof_data, + poolbuffer._pool_buffer_offsetof_size, + poolbuffer._pool_buffer_offsetof_capacity) + + +def test_unfinished_builder_frees_its_buffers(): + @nb.njit + def unfinished(n): + b = apn.Int64Builder() + b.reserve(n) + for i in range(n): + b.append(i) + return 0 # the builder is dropped, never finished + + assert unfinished(4) == 0 # warm up + assert _grown(unfinished, 1000) < LEAK_LIMIT + + +def test_built_array_not_returned_is_released(): + @nb.njit + def not_returned(n): + b = apn.Int64Builder() + for i in range(n): + b.append(i) + return len(b.finish()) # only the length escapes + + assert not_returned(4) == 4 + assert _grown(not_returned, 1000) < LEAK_LIMIT + + +def test_builder_freed_when_compiled_code_raises(): + @nb.njit + def raises(n): + b = apn.Int64Builder() + for i in range(n): + b.append(i) + if n: + raise ValueError("boom") + return 0 + + assert raises(0) == 0 # warm up + with pytest.raises(ValueError, match="boom"): + raises(100) + assert _grown(raises, 1000) < LEAK_LIMIT + + +def test_builder_refuses_use_after_finish_finish(): + """A spent builder must raise, not write through a freed pool.""" + @nb.njit + def finish_again(): + b = apn.Int64Builder() + b.append(1) + b.finish() + return b.finish() + + with pytest.raises(RuntimeError, match="after finish"): + finish_again() + + +def test_builder_refuses_use_after_finish_append(): + @nb.njit + def append_after(): + b = apn.Int64Builder() + b.append(1) + b.finish() + b.append(2) + return 0 + + with pytest.raises(RuntimeError, match="after finish"): + append_after() + + +def test_builder_refuses_use_after_finish_reserve(): + @nb.njit + def reserve_after(): + b = apn.Int64Builder() + b.append(1) + b.finish() + b.reserve(4) + return 0 + + with pytest.raises(RuntimeError, match="after finish"): + reserve_after() + + +def test_builder_refuses_append_bytes_after_finish(): + @nb.njit + def append_after(): + b = apn.StringBuilder() + b.append(b"x") + b.finish() + b.append(b"y") + return 0 + + with pytest.raises(RuntimeError, match="after finish"): + append_after() + + +def test_reserve_failure_is_an_arrow_error(): + @nb.njit + def huge(): + b = apn.Int64Builder() + b.reserve(1 << 58) + return 0 + + @nb.njit + def negative(): + b = apn.Int64Builder() + b.reserve(-5) + return 0 + + @nb.njit + def nested(): + return huge() + 1 + + with pytest.raises(pa.ArrowMemoryError): + huge() + # the pending Arrow error survives a compiled call frame in between + with pytest.raises(pa.ArrowMemoryError): + nested() + with pytest.raises(ValueError, match="negative capacity"): + negative() + assert _grown(negative) < LEAK_LIMIT + + +def test_builder_aliases_and_bound_methods_share_state(): + @nb.njit + def make(): + b = apn.Int64Builder() + b.append(1) + return b + + @nb.njit + def build(): + b = make() + append = b.append + alias = b + append(2) + alias.append(3) + return alias.finish() + + assert build().to_pylist() == [1, 2, 3] + assert _grown(build) < LEAK_LIMIT + + @nb.njit + def append_through_saved_method_after_finish(): + b = apn.Int64Builder() + b.append(1) + append = b.append + alias = b + alias.finish() + append(2) + return 0 + + with pytest.raises(RuntimeError, match="after finish"): + append_through_saved_method_after_finish() + + +def test_builder_can_leave_the_function_that_made_it(): + @nb.njit + def make(): + b = apn.Int64Builder() + b.append(1) + return b + + @nb.njit + def use(b): + b.append(2) + return b.finish() + + @nb.njit + def driver(): + return use(make()) + + assert driver().to_pylist() == [1, 2] + + +def test_builder_shared_with_a_helper(): + @nb.njit + def fill(b, n): + for i in range(n): + b.append(i) + + @nb.njit + def shared(): + b = apn.Int64Builder() + fill(b, 4) + return b.finish() + + assert shared().to_pylist() == [0, 1, 2, 3] + + +def test_built_array_is_readable_in_compiled_code(): + @nb.njit + def read_built(): + b = apn.Int64Builder() + b.append(1) + b.append(None) + b.append(3) + a = b.finish() + return len(a), a[0], a[1] is None, is_valid(a, 2) + + assert read_built() == (3, 1, True, True) + + @nb.njit + def string_len_of_built(): + b = apn.StringBuilder() + b.append(b"ab") + a = b.finish() + return string_len(a[0]) + + assert string_len_of_built() == 2 + + +def test_built_array_passes_through_compiled_calls(): + @nb.njit + def ident(a): + return a + + @nb.njit + def outer(): + b = apn.Int64Builder() + b.append(1) + b.append(2) + return ident(b.finish()) + + assert outer().to_pylist() == [1, 2] + + +def test_built_array_can_be_returned_once(): + @nb.njit + def twice(): + b = apn.Int64Builder() + b.append(7) + a = b.finish() + return a, a + + with pytest.raises((SystemError, pa.ArrowInvalid)): + twice() + + +def test_var_width_append_rejects_other_values(): + @nb.njit + def append_int(): + b = apn.StringBuilder() + b.append(1) + return b.finish() + + with pytest.raises(TypingError): + append_int() + + +def test_built_array_is_returned_once(): + @nb.njit + def twice(): + b = apn.Int64Builder() + b.append(1) + a = b.finish() + return a, a + + # Numba's tuple boxing reports a failed item as a SystemError + with pytest.raises(SystemError) as info: + twice() + assert isinstance(info.value.__cause__, RuntimeError) + assert "only once" in str(info.value.__cause__) diff --git a/python/pyarrow/tests/test_numba_capsule.py b/python/pyarrow/tests/test_numba_capsule.py new file mode 100644 index 000000000000..9f93dd516fcf --- /dev/null +++ b/python/pyarrow/tests/test_numba_capsule.py @@ -0,0 +1,397 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""The Arrow C data interface: structs, capsules and buffer ownership.""" + +import ctypes +import gc +import weakref + +import pytest + +import pyarrow as pa + +nb = pytest.importorskip("numba") +import numpy as np # noqa: E402 (numba requires numpy) + +from pyarrow.numba import _register, from_any, register_producer # noqa: E402 +from pyarrow.numba._capsule import ( # noqa: E402 + _DTYPE_CACHE, + _DTYPE_CACHE_LIMIT, + ArrowArray, + ArrowArrayStream, + ArrowSchema, + _protocol_of, + capsule_pointer, + dtype_of, + from_stream, + release_struct, + take, + take_array_into, +) +from pyarrow.tests.numba_util import ( # noqa: E402 + ArrayProducer, + StreamProducer, + sum_and_nulls, + total, + valid_flags, +) + +_register() + + +def _array_slot(): + """An ``ArrowArray`` the caller owns, released at the end of the test.""" + slot = ArrowArray() + + def release(): + release_struct(slot) + + return slot, release + + +def test_capsule_producer_is_read_without_materialising_it(): + """Unboxing fills the view from the capsule: no pa.Array per call.""" + array = pa.array([2, 3, None, 5]) + view = ArrowArray() + take_array_into(ArrayProducer(array), ctypes.addressof(view), pa.int64()) + try: + assert view.length == 4 + assert view.n_buffers == 2 + assert view.buffers[1] == array.buffers()[1].address # zero copy + assert view.release + finally: + release_struct(view) + + +def test_accepts_a_non_pyarrow_capsule_producer(): + array = pa.array([1, None, 3, 4]) + assert total(ArrayProducer(array)) == 8 + assert from_any(array) is array + with pytest.raises(TypeError, match="implements neither"): + from_any(object()) + + +def test_take_moves_the_release_callback(): + source = pa.array([1, 2, 3]) + _, array_capsule = source.__arrow_c_array__() + moved = take(ArrowArray, array_capsule, b"arrow_array") + + assert moved.length == 3 + assert moved.offset == 0 + assert moved.buffers[1] # data buffer, non-null + assert moved.release # we own it now + + # the capsule's own struct was neutralised: dropping it must not free + del array_capsule, source + gc.collect() + assert moved.length == 3 # still readable, no crash + release_struct(moved) + + +def test_multi_chunk_stream_raises_and_from_any_copies(): + table = pa.table({"x": pa.chunked_array([[1, 2], [3, 4]], + type=pa.int64())}) + stream = StreamProducer(table) + + with pytest.raises(TypeError, match="more than one chunk"): + total(stream) + + assert total(from_any(stream)) == 10 # the documented copying route + + +def test_empty_stream_reads_as_an_empty_array(): + empty = pa.table({"x": pa.chunked_array([], type=pa.int64())}) + producer = StreamProducer(empty) + + assert total(producer) == 0 + assert from_any(producer).equals(pa.array([], pa.int64())) + + +def test_record_batch_stream_reads_column_zero(): + table = pa.table({"x": pa.array([1, None, 3]), "y": pa.array(list("abc"))}) + assert total(StreamProducer(table)) == 4 + + +def test_stream_errors_surface_as_value_error(): + batches = pa.table({"x": pa.array([1, 2, 3])}).to_batches() + + def failing(after): + def generate(): + for batch in batches[:after]: + yield batch + raise RuntimeError("boom") + return pa.RecordBatchReader.from_batches(batches[0].schema, generate()) + + for after in (0, 1): + slot, release = _array_slot() + with pytest.raises(ValueError, match="boom"): + take_array_into(StreamProducer(failing(after)), + ctypes.addressof(slot), pa.int64()) + release() + + +def test_stream_failure_without_a_message(): + """A stream whose callbacks fail but report no message.""" + release_cb_type = ctypes.CFUNCTYPE(None, ctypes.POINTER(ArrowArrayStream)) + get_schema_type = ctypes.CFUNCTYPE( + ctypes.c_int, ctypes.POINTER(ArrowArrayStream), + ctypes.POINTER(ArrowSchema)) + get_next_type = ctypes.CFUNCTYPE( + ctypes.c_int, ctypes.POINTER(ArrowArrayStream), + ctypes.POINTER(ArrowArray)) + get_error_type = ctypes.CFUNCTYPE( + ctypes.c_char_p, ctypes.POINTER(ArrowArrayStream)) + new_capsule = ctypes.PYFUNCTYPE( + ctypes.py_object, ctypes.c_void_p, ctypes.c_char_p, + ctypes.c_void_p)(("PyCapsule_New", ctypes.pythonapi)) + + class SilentFailure: + """Every callback fails and ``get_last_error`` returns nothing.""" + + def __init__(self): + self._callbacks = [ + get_schema_type(lambda stream, schema: 5), + get_next_type(lambda stream, array: 5), + get_error_type(lambda stream: None), + release_cb_type(lambda stream: None), + ] + self._streams = [] + + def __arrow_c_stream__(self, requested_schema=None): + # a fresh struct per call: the capsule takes ownership of the one + # it wraps, so reusing it would hand out a freed pointer + stream = ArrowArrayStream() + for name, callback in zip( + ("get_schema", "get_next", "get_last_error", "release"), + self._callbacks): + setattr(stream, name, ctypes.cast(callback, ctypes.c_void_p)) + self._streams.append(stream) # the callbacks must outlive it + return new_capsule(ctypes.addressof(stream), + b"arrow_array_stream", None) + + producer = SilentFailure() + with pytest.raises(ValueError, match="Arrow stream failed"): + dtype_of(producer) + + slot, release = _array_slot() + with pytest.raises(ValueError, match="Arrow stream failed"): + take_array_into(producer, ctypes.addressof(slot), pa.int64()) + release() + + +def test_misnamed_capsule_is_a_type_error(): + class Swapped: + def __arrow_c_array__(self, requested_schema=None): + schema, array = pa.array([1]).__arrow_c_array__() + return array, schema # swapped on purpose + + slot, release = _array_slot() + with pytest.raises(TypeError, + match="expected a PyCapsule named 'arrow_array'"): + take_array_into(Swapped(), ctypes.addressof(slot), pa.int64()) + release() + + +def test_no_protocol_is_a_type_error(): + slot, release = _array_slot() + for call in (lambda: take_array_into(object(), ctypes.addressof(slot), + pa.int64()), + lambda: dtype_of(object()), + lambda: from_any(object())): + with pytest.raises(TypeError, match="implements neither"): + call() + release() + + +def test_protocol_found_on_the_instance(): + class Delegating: + """No class-level protocol: a per-instance wrapper answers instead.""" + + def __init__(self, array): + self._array = array + + def __getattr__(self, name): + return getattr(self._array, name) + + producer = Delegating(pa.array([1, 2, 3])) + assert _protocol_of(producer) == "__arrow_c_array__" + assert isinstance(producer, Delegating) + register_producer(Delegating) + assert total(producer) == 6 + + +def test_dtype_cache_skips_unhashable_hints(): + class Unhashable: + dtype = ["int", "64"] + + def __arrow_c_array__(self, requested_schema=None): + return pa.array([1], type=pa.int64()).__arrow_c_array__( + requested_schema) + + before = len(_DTYPE_CACHE) + assert dtype_of(Unhashable()) == pa.int64() + assert len(_DTYPE_CACHE) == before + + +def test_dtype_cache_is_bounded(): + class Hinted: + dtype = None + + def __init__(self, hint): + self.dtype = hint + + def __arrow_c_array__(self, requested_schema=None): + return pa.array([1], type=pa.int64()).__arrow_c_array__( + requested_schema) + + for k in range(_DTYPE_CACHE_LIMIT + 44): + dtype_of(Hinted(f"int64-{k}")) + assert len(_DTYPE_CACHE) <= _DTYPE_CACHE_LIMIT + + +def test_producer_buffers_are_not_kept_alive_by_the_call(): + seen = [] + + class Producer(ArrayProducer): + def __arrow_c_array__(self, requested_schema=None): + seen.append(weakref.ref(self._array)) + return super().__arrow_c_array__(requested_schema) + + register_producer(Producer) + array = pa.array([1, 2, 3]) + assert total(Producer(array)) == 6 + + del array + gc.collect() + assert seen[0]() is None # nothing from the call is kept alive + + +def test_capsule_struct_matches_the_c_layout(): + assert ctypes.sizeof(ArrowArray) == 80 + assert [name for name, _ in ArrowArray._fields_] == [ + "length", "null_count", "offset", "n_buffers", "n_children", + "buffers", "children", "dictionary", "release", "private_data", + ] + assert ctypes.sizeof(ArrowArrayStream) == 40 + assert [name for name, _ in ArrowArrayStream._fields_] == [ + "get_schema", "get_next", "get_last_error", "release", "private_data", + ] + assert [name for name, _ in ArrowSchema._fields_] == [ + "format", "name", "metadata", "flags", "n_children", "children", + "dictionary", "release", "private_data", + ] + + +def test_typing_a_stream_producer_is_cached(): + """Numba re-types per call: the schema must not be read every time.""" + opened = [] + + class Producer(StreamProducer): + dtype = "int64" # cheap, hashable, stands in for the schema + + def __arrow_c_stream__(self, requested_schema=None): + opened.append(1) + return super().__arrow_c_stream__(requested_schema) + + register_producer(Producer) + producer = Producer(pa.chunked_array([[1, 2, 3]])) + assert total(producer) == 6 # one stream for typing, one for data + + before = len(opened) + assert total(producer) == 6 + assert len(opened) - before == 1 # typing came from the cache + + +def test_stream_typing_cache_also_skips_the_schema(): + """``from_stream`` is what reads a schema, so count the capsules.""" + opened = [] + + class Producer(StreamProducer): + def __arrow_c_stream__(self, requested_schema=None): + opened.append(1) + return super().__arrow_c_stream__(requested_schema) + + producer = Producer(pa.chunked_array([[1, 2, 3]])) + assert from_stream(producer.__arrow_c_stream__(), pa.int64()).length == 3 + assert len(opened) == 1 + + +def test_producer_with_too_few_buffers_is_refused(): + """A struct with fewer buffers than its type needs must raise, not read + past the end of the buffer array.""" + class Liar: + """Says "string", exports an int64 struct (two buffers, not three).""" + + def __arrow_c_array__(self): + schema, _ = pa.array(["a"]).__arrow_c_array__() + _, array = pa.array([1, 2]).__arrow_c_array__() + return schema, array + + slot, release = _array_slot() + with pytest.raises(ValueError, match="needs 3"): + take_array_into(Liar(), ctypes.addressof(slot), pa.string()) + release() + + # the refused struct is released, so repeated refusals do not leak + pool = pa.default_memory_pool() + big = pa.array(np.arange(100_000)).cast(pa.int32()) + take_array_into(ArrayProducer(big), ctypes.addressof(slot), pa.int32()) + release_struct(slot) + + before = pool.bytes_allocated() + for _ in range(50): + slot, release = _array_slot() + with pytest.raises(ValueError, match="needs 3"): + take_array_into(Liar(), ctypes.addressof(slot), pa.string()) + release() + gc.collect() + assert pool.bytes_allocated() - before < 1 << 20 + + +def test_unknown_null_count_without_a_bitmap_means_no_nulls(): + """The C data interface allows ``null_count == -1`` ("not computed") with + no validity buffer: the array then has no nulls at all. + + pyarrow always exports a computed count, so the struct is patched to look + like a producer that does not compute it. + """ + class UnknownCount: + def __arrow_c_array__(self, requested_schema=None): + schema, array = pa.array(np.arange(200)).__arrow_c_array__() + struct = ArrowArray.from_address( + capsule_pointer(array, b"arrow_array")) + assert not struct.buffers[0] # dense: no validity buffer + struct.null_count = -1 + return schema, array + + register_producer(UnknownCount) + assert valid_flags(UnknownCount()).all() + assert sum_and_nulls(UnknownCount()) == (sum(range(200)), 0) + + +def test_object_dtype_columns_do_not_share_a_cached_type(): + """Two pandas object columns can hold a string and a struct: the dtype + cache must not answer the second with the first one's type.""" + pandas = pytest.importorskip("pandas") + + _DTYPE_CACHE.clear() + words = pandas.Series([{"x": "a"}, {"x": "b"}], dtype=object) + numbers = pandas.Series([{"x": 1}, {"x": 2}], dtype=object) + + assert dtype_of(words) == pa.string() + assert dtype_of(numbers) == pa.int64() diff --git a/python/pyarrow/tests/test_numba_helpers.py b/python/pyarrow/tests/test_numba_helpers.py new file mode 100644 index 000000000000..e0a8ab6731e4 --- /dev/null +++ b/python/pyarrow/tests/test_numba_helpers.py @@ -0,0 +1,153 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Direct tests for the pure helpers behind the extension.""" + +import pathlib +import re + +import pytest + +import pyarrow as pa + +pytest.importorskip("numba") +import numpy as np # noqa: E402 (numba requires numpy) + +from pyarrow.numba import _register, is_valid, string_len # noqa: E402 +from pyarrow.numba import decimal_to_float # noqa: E402 +from pyarrow.numba._capsule import _dtype_hint, num_buffers # noqa: E402 +from pyarrow.numba._utils import ( # noqa: E402 + _arrow_type_to_nb_type, + _is_var_width, +) + +_register() + + +@pytest.mark.parametrize("arrow_type,expected", [ + (pa.string(), True), + (pa.large_string(), True), + (pa.binary(), True), + (pa.large_binary(), True), + (pa.binary(8), True), + (pa.int64(), False), + (pa.date32(), False), + (pa.bool_(), False), +]) +def test_is_var_width(arrow_type, expected): + assert _is_var_width(arrow_type) is expected + + +@pytest.mark.parametrize("arrow_type,bitwidth,signed", [ + (pa.int8(), 8, True), + (pa.int64(), 64, True), + (pa.uint16(), 16, False), + (pa.uint64(), 64, False), +]) +def test_integer_type_mapping(arrow_type, bitwidth, signed): + mapped = _arrow_type_to_nb_type(arrow_type) + assert mapped.bitwidth == bitwidth + assert mapped.signed is signed + + +@pytest.mark.parametrize("arrow_type,expected", [ + (pa.float32(), "float32"), + (pa.float64(), "float64"), + (pa.date32(), "int32"), + (pa.time32("s"), "int32"), + (pa.date64(), "int64"), + (pa.time64("us"), "int64"), + (pa.timestamp("us"), "int64"), + (pa.duration("s"), "int64"), + (pa.bool_(), "bool"), +]) +def test_scalar_type_mapping(arrow_type, expected): + assert str(_arrow_type_to_nb_type(arrow_type)) == expected + + +def test_var_width_and_decimal_mapping(): + import numba.core.types as nbt + + assert _arrow_type_to_nb_type(pa.string()) == nbt.uint8 + assert _arrow_type_to_nb_type(pa.decimal128(20, 2)) == nbt.Tuple( + (nbt.int64, nbt.uint64)) + with pytest.raises(TypeError, match="Unsupported PyArrow type"): + _arrow_type_to_nb_type(pa.decimal256(40, 2)) + with pytest.raises(TypeError, match="Unsupported PyArrow type"): + _arrow_type_to_nb_type(pa.list_(pa.int64())) + + +def test_builder_buffer_types(): + from pyarrow.numba.builder import _data_buffer_type, _offsets_type + + assert _data_buffer_type(pa.string()) == pa.uint8() + assert _data_buffer_type(pa.int64()) == pa.int64() + assert _offsets_type(pa.string()) == pa.int32() + assert _offsets_type(pa.large_string()) == pa.int64() + assert _offsets_type(pa.large_binary()) == pa.int64() + + +def test_num_buffers_per_type(): + assert num_buffers(pa.int64()) == 2 + assert num_buffers(pa.bool_()) == 2 + assert num_buffers(pa.binary(4)) == 2 + assert num_buffers(pa.string()) == 3 + assert num_buffers(pa.large_binary()) == 3 + + +def test_dtype_hint_rejects_what_it_cannot_represent(): + class Opaque: + pass + + class ObjectDtype: + dtype = np.dtype(object) + + assert _dtype_hint(Opaque()) is None # no dtype, no types + assert _dtype_hint(pa.array([1, 2])) is None # pyarrow array: no hint + assert _dtype_hint(ObjectDtype()) is None # an object column says nothing + + +def test_types_attribute_is_a_hint(): + class WithTypes: + types = ("int64",) + + assert _dtype_hint(WithTypes()) == (WithTypes, ("int64",)) + + +def test_compiled_only_helpers_raise_in_python(): + array = pa.array([1]) + for call in (lambda: is_valid(array, 0), + lambda: string_len(b"x"), + lambda: decimal_to_float((0, 1), 2)): + with pytest.raises(NotImplementedError, + match="only callable from nopython code"): + call() + + +@pytest.mark.skipif(not pathlib.Path("/proc/self/maps").exists(), + reason="needs /proc/self/maps") +def test_libarrow_python_is_loaded_once(): + """Symbols resolve through pyarrow.lib: one copy of the extension library.""" + paths = set() + for line in pathlib.Path("/proc/self/maps").read_text().splitlines(): + columns = line.split() + if len(columns) >= 6: + mapped = columns[-1] + if re.fullmatch(r"libarrow_python\.so(\.[\w.]+)?", + pathlib.Path(mapped).name): + paths.add(mapped) + assert len(paths) == 1, paths diff --git a/python/pyproject.toml b/python/pyproject.toml index b404c261f32f..b351a860e2db 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -56,6 +56,9 @@ Documentation = "https://arrow.apache.org/docs/python" Repository = "https://github.com/apache/arrow" Issues = "https://github.com/apache/arrow/issues" +[project.entry-points.numba_extensions] +init = "pyarrow.numba:_register" + [dependency-groups] test = [ 'pytest',