Aditya060806 opened a new pull request, #55808:
URL: https://github.com/apache/arrow/pull/55808

   ### Rationale for this change
   
   Fixes GitHub issue [#41388](https://github.com/apache/arrow/issues/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:
   
   ```python
   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](https://github.com/apache/arrow/issues/41388#issuecomment-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:
   
   ```cpp
   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](https://arrow.apache.org/docs/dev/developers/overview.html#ai-generated-code),
 please disclose below whether and how AI was used in this PR.
   
   **PR code and description written by:**
   
   - [ ] Human
   - [x] AI
   
   **Reviewed before submission by:**
   
   - [x] 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.
   
   * GitHub Issue: #41388
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to