Skip to content

GH-41388: [Python] Preserve interior null bytes when converting NumPy bytes arrays to Binary/LargeBinary - #55808

Open
Aditya060806 wants to merge 1 commit into
apache:mainfrom
Aditya060806:fix/gh-41388-numpy-bytes-interior-null
Open

Aditya060806 wants to merge 1 commit into
apache:mainfrom
Aditya060806:fix/gh-41388-numpy-bytes-interior-null

Conversation

@Aditya060806

Copy link
Copy Markdown

Rationale for this change

Fixes GitHub issue #41388 (Status: confirmed, Type: bug, Component: Python). When a numpy.ndarray with a fixed-width bytes dtype (S) is converted to a pyarrow Binary or LargeBinary array, NumPyConverter::VisitBinary uses strnlen to compute each value's length. strnlen stops at the first null byte, so every value gets silently truncated at its first interior \x00 and real payload data is dropped.

Minimal reproducer from the issue:

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'

On pyarrow 23.0.0 the assertion fails with b'This data contains '.

NumPy's S dtype documents only trailing zero-padding of short values, so stripping just trailing null bytes matches NumPy semantics while preserving all genuine interior data. Arrow committer jorisvandenbossche pointed 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 — the AppendNotNull lambda inside template <typename T> Status NumPyConverter::VisitBinary(T* builder) no longer uses strnlen. It now starts from itemsize_ and decrements past trailing zero bytes only:

auto AppendNotNull = [builder, this](const uint8_t* data) {
  // 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<size_t>(itemsize_);
  while (item_size > 0 && data[item_size - 1] == 0) {
    --item_size;
  }
  return builder->Append(data, static_cast<int32_t>(item_size));
};

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.

Diff size: 1 C++ file, +7/-4; 1 test file, +36/-0.

Are these changes tested?

Yes. python/pyarrow/tests/test_array.py gains test_binary_array_from_numpy_preserves_interior_nulls, placed next to the existing test_binary_array_masked / test_binary_array_strided block. It covers:

  • Variable-length pa.binary() and pa.large_binary() from an S-dtype numpy array with interior nulls.
  • The trailing-padding case (b'short' inside an S10) that test_binary_array_masked already depends on, to confirm no regression.
  • Table.from_pydict taking the same converter path.
  • Masked and strided numpy inputs with interior nulls.

Target invocation (from the commit message):

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 plus a matching pip 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 has strnlen); it fails exactly as expected on the interior-null assertion and the trailing-padding sanity check still passes:

$ 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.

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 \x00 bytes through pa.array(..., type=pa.binary()), pa.array(..., type=pa.large_binary()), or pa.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 outside python/.

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:

  • Human
  • AI

Reviewed before submission by:

  • Human
  • AI
  • Not reviewed

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.

… 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
Aditya060806 marked this pull request as ready for review November 26, 2026 23:36
Copilot AI balanced review requested due to automatic review settings November 26, 2026 23:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants