From 9841e6feef01d78bb6f05c2c8be8da26dcad4009 Mon Sep 17 00:00:00 2001 From: Aditya Pandey Date: Fri, 27 Nov 2026 04:55:06 +0530 Subject: [PATCH] GH-41388: [Python] Preserve interior null bytes when converting NumPy bytes arrays to Binary/LargeBinary When a numpy.ndarray with a fixed-width bytes dtype (``S``) is converted to a pyarrow Binary or LargeBinary array, ``NumPyConverter::VisitBinary`` used ``strnlen`` to determine the length of each value. That truncated every value at the first interior null byte, silently dropping real payload data. NumPy's ``S`` dtype only zero-pads *trailing* bytes of short values, so stripping just trailing null bytes preserves NumPy's documented semantics while keeping all genuine interior data. The fix replaces the ``strnlen``-based length computation inside the ``AppendNotNull`` lambda in ``python/pyarrow/src/arrow/python/numpy_to_arrow.cc`` with a loop that decrements past trailing null bytes only. The lambda feeds both ``Visit(const BinaryType&)`` and ``Visit(const LargeBinaryType&)``, so both variable-length binary types are fixed by one change. ``FixedSizeBinaryType`` uses a separate code path and is unaffected. The direction (``strnlen`` -> strip trailing nulls) was proposed by Arrow committer jorisvandenbossche in https://github.com/apache/arrow/issues/41388#issuecomment-2088180177. Reproducer (from issue #41388) ------------------------------ import numpy as np import pyarrow as pa np_array = np.array([ b'This data contains \x00 and bytes after it', b'This data does not have any null bytes.', ]) pa_arr = pa.array(np_array, type=pa.binary()) assert pa_arr[0].as_py() == b'This data contains \x00 and bytes after it' Before this change (pyarrow 23.0.0): got: b'This data contains ' expected: b'This data contains \x00 and bytes after it' After this change the full byte string round-trips unchanged. Tests ----- Added ``test_binary_array_from_numpy_preserves_interior_nulls`` in ``python/pyarrow/tests/test_array.py`` covering the Binary + LargeBinary paths, masked and strided inputs, plus the backwards-compatible trailing-padding stripping that ``test_binary_array_masked`` / ``test_binary_array_strided`` already rely on. The target test invocation is: pytest python/pyarrow/tests/test_array.py -k "binary or interior_nulls" -v Running the pyarrow test suite requires a locally built Arrow C++ with ``ARROW_PYTHON=ON`` and a matching ``pip install -e python[dev]``; that build is not reproducible on this Windows workstation (no bootstrapped vcpkg/conda Arrow stack available in the current environment), so the new test logic was executed as a standalone script against the released pyarrow 23.0.0 to confirm that it correctly fails against the unfixed code and that its trailing-padding assertion does not regress existing behaviour: $ python arrow/_tmp_verify_test.py Traceback (most recent call last): File "arrow\_tmp_verify_test.py", line 38, in test_binary_array_from_numpy_preserves_interior_nulls() File "arrow\_tmp_verify_test.py", line 16, in test_binary_array_from_numpy_preserves_interior_nulls assert arr.to_pylist() == values, f"binary: {arr.to_pylist()!r}" AssertionError: binary: [b'contains ', b'no nulls here'] $ python -c "import numpy as np, pyarrow as pa; short = np.array([b'short', b'exactlyten']); print(pa.array(short, type=pa.binary()).to_pylist())" [b'short', b'exactlyten'] Full cross-platform validation is deferred to Apache Arrow CI, which rebuilds Arrow C++ and pyarrow and runs the Python test suite on all supported platforms when the PR is submitted. Signed-off-by: Aditya Pandey --- .../src/arrow/python/numpy_to_arrow.cc | 11 +++--- python/pyarrow/tests/test_array.py | 36 +++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/python/pyarrow/src/arrow/python/numpy_to_arrow.cc b/python/pyarrow/src/arrow/python/numpy_to_arrow.cc index d4e859d1c707..ea7df38343d2 100644 --- a/python/pyarrow/src/arrow/python/numpy_to_arrow.cc +++ b/python/pyarrow/src/arrow/python/numpy_to_arrow.cc @@ -578,10 +578,13 @@ Status NumPyConverter::VisitBinary(T* builder) { auto data = reinterpret_cast(PyArray_DATA(arr_)); auto AppendNotNull = [builder, this](const uint8_t* data) { - // This is annoying. NumPy allows strings to have nul-terminators, so - // we must check for them here - const size_t item_size = - strnlen(reinterpret_cast(data), static_cast(itemsize_)); + // NumPy's fixed-width bytes dtype (``S``) zero-pads values shorter than + // the item width. Strip only *trailing* null bytes so that genuine + // interior null bytes are preserved (GH-41388). + size_t item_size = static_cast(itemsize_); + while (item_size > 0 && data[item_size - 1] == 0) { + --item_size; + } return builder->Append(data, static_cast(item_size)); }; diff --git a/python/pyarrow/tests/test_array.py b/python/pyarrow/tests/test_array.py index ca063bc6b695..df4b624eb539 100644 --- a/python/pyarrow/tests/test_array.py +++ b/python/pyarrow/tests/test_array.py @@ -3894,6 +3894,42 @@ def test_binary_array_strided(): assert [b"ab", b"ef"] == arrow_array.to_pylist() +@pytest.mark.numpy +def test_binary_array_from_numpy_preserves_interior_nulls(): + # GH-41388: numpy fixed-width bytes arrays with interior '\x00' bytes + # used to be truncated at the first null. NumPy only pads *trailing* + # bytes, so only trailing nulls should be stripped. + values = [b'contains \x00 interior', b'no nulls here'] + np_array = np.array(values) # dtype='S20' + + # Variable-length binary + arr = pa.array(np_array, type=pa.binary()) + assert arr.to_pylist() == values + + # Large binary uses the same converter path + arr_large = pa.array(np_array, type=pa.large_binary()) + assert arr_large.to_pylist() == values + + # Trailing padding on short values is still stripped (NumPy 'S' semantics) + short = np.array([b'short', b'exactlyten']) # dtype='S10' + arr_short = pa.array(short, type=pa.binary()) + assert arr_short.to_pylist() == [b'short', b'exactlyten'] + + # Table.from_pydict goes through the same path + table = pa.Table.from_pydict({'x': np_array}) + assert table['x'].to_pylist() == values + + # Masked variant still preserves interior nulls + masked = pa.array(np_array, type=pa.binary(), + mask=np.array([False, False])) + assert masked.to_pylist() == values + + # Strided variant still preserves interior nulls + stride = np.array([b'one \x00 one', b'two \x00 two', b'three']) + strided = pa.array(stride[::2], type=pa.binary()) + assert strided.to_pylist() == [b'one \x00 one', b'three'] + + @pytest.mark.numpy def test_array_invalid_mask_raises(): # ARROW-10742