Repository navigation
GH-41388: [Python] Preserve interior null bytes when converting NumPy bytes arrays to Binary/LargeBinary - #55808
Open
Aditya060806 wants to merge 1 commit into
Conversation
… 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 apache#41388 (comment). Reproducer (from issue apache#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 <module> 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 <aditya060806@gmail.com>
Aditya060806
marked this pull request as ready for review
November 26, 2026 23:36
Aditya060806
requested review from
AlenkaF,
pitrou,
raulcd and
rok
as code owners
November 26, 2026 23:36
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Rationale for this change
Fixes GitHub issue #41388 (
Status: confirmed,Type: bug,Component: Python). When anumpy.ndarraywith a fixed-width bytes dtype (S) is converted to a pyarrowBinaryorLargeBinaryarray,NumPyConverter::VisitBinaryusesstrnlento compute each value's length.strnlenstops at the first null byte, so every value gets silently truncated at its first interior\x00and real payload data is dropped.Minimal reproducer from the issue:
On pyarrow 23.0.0 the assertion fails with
b'This data contains '.NumPy's
Sdtype documents only trailing zero-padding of short values, so stripping just trailing null bytes matches NumPy semantics while preserving all genuine interior data. Arrow committerjorisvandenbosschepointed at the exact file and lines and proposed this direction in comment 2088180177.What changes are included in this PR?
python/pyarrow/src/arrow/python/numpy_to_arrow.cc— theAppendNotNulllambda insidetemplate <typename T> Status NumPyConverter::VisitBinary(T* builder)no longer usesstrnlen. It now starts fromitemsize_and decrements past trailing zero bytes only:The lambda feeds both
Visit(const BinaryType&)andVisit(const LargeBinaryType&), so both variable-length binary types are fixed by one change.FixedSizeBinaryTypeuses a separate code path and is unaffected.Diff size: 1 C++ file, +7/-4; 1 test file, +36/-0.
Are these changes tested?
Yes.
python/pyarrow/tests/test_array.pygainstest_binary_array_from_numpy_preserves_interior_nulls, placed next to the existingtest_binary_array_masked/test_binary_array_stridedblock. It covers:pa.binary()andpa.large_binary()from anS-dtype numpy array with interior nulls.b'short'inside anS10) thattest_binary_array_maskedalready depends on, to confirm no regression.Table.from_pydicttaking the same converter path.Target invocation (from the commit message):
Running the pyarrow test suite requires a locally built Arrow C++ with
ARROW_PYTHON=ONplus a matchingpip install -e python[dev], and that stack is not bootstrapped on this Windows workstation. To make sure the new test actually exercises the bug rather than tautologically passing, the test body was run as a standalone script against released pyarrow 23.0.0 (which still hasstrnlen); it fails exactly as expected on the interior-null assertion and the trailing-padding sanity check still passes: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.
Are there any user-facing changes?
Yes, but only in the sense that previously-dropped data is now preserved. Any pyarrow caller that converts a numpy
S-dtype array with interior\x00bytes throughpa.array(..., type=pa.binary()),pa.array(..., type=pa.large_binary()), orpa.Table.from_pydict(...)now gets the full byte string instead of a value truncated at the first interior null. No public API signature changes. No changes outsidepython/.This PR contains a "Critical Fix". Per the template's definition, it fixes "a bug that caused incorrect or invalid data to be produced": binary payloads were being silently truncated during NumPy → Arrow conversion with no warning.
Was AI used for this PR?
In accordance to the AI generation guidelines, please disclose below whether and how AI was used in this PR.
PR code and description written by:
Reviewed before submission by:
The change was debugged and owned by me: the direction follows
jorisvandenbossche's comment on the issue, the diff is a 5-line lambda body plus one focused test, and the test was executed against stock pyarrow 23.0.0 to confirm it fails against the unfixed code before being added. No maintainers were pinged.np.ndarraywith bytes data type to binary pyarrow array discards all bytes after the first null byte. #41388