Skip to content

[Data] Fix TensorArray.take row corruption with missing indices - #66997

Open
DogerW666 wants to merge 3 commits into
ray-project:masterfrom
DogerW666:fix/tensor-array-take-fill
Open

DogerW666 wants to merge 3 commits into
ray-project:masterfrom
DogerW666:fix/tensor-array-take-fill

Conversation

@DogerW666

@DogerW666 DogerW666 commented Oct 14, 2026 •

Copy link
Copy Markdown

Description

Fix silent data corruption in TensorArray.take(..., allow_fill=True) when an indexer mixes valid tensor rows with missing (-1) entries.

The existing np.put call treats row positions as flattened scalar offsets. As a result, a pandas Series.reindex that only appends a missing label can replace an existing tensor row with NaNs. Assigning along the leading axis copies complete tensor rows and leaves only the missing rows filled.

This changes only row placement, leaving dtype selection and existing ragged-tensor missing-value behavior unchanged.

Add 23 test cases covering scalar, zero-width, vector, matrix and higher-rank tensors; default and explicit fill values; repeated and reordered indices; the no-fill paths; pandas Series.reindex; and variable-shaped tensors with no missing indices or only missing indices.

Related issues

Fixes #66992.

Duplicate check

Searched all-state issues and open PRs for TensorArray allow_fill, TensorArray reindex, tensor reindex, TensorArray take, and np.put, and checked open PRs referencing #66992. No matching report or in-flight fix was found before opening #66992. #52977 addresses constructor null-safety and does not modify TensorArray.take or pandas reindexing. #29590 was a separate, closed Arrow row-conversion issue.

Validation

Environment: Python 3.11.15, NumPy 2.2.6, pandas 2.2.3, PyArrow 22.0.0, macOS arm64.

The published Ray 2.55.1 runtime reproduces the problem. Local source validation loads this checkout's tensor modules over that runtime, using a temporary process-only runner (/tmp/ray-tensor-fix-pytest.py). It loads utils.py, arrow.py, and pandas.py from the checkout, refreshes the Arrow type registrations, and uses the unchanged tensor context fixtures from the repository. It does not modify the installed Ray environment. Unrelated cluster/auth conftest setup is excluded.

python /tmp/ray-tensor-fix-pytest.py \
  --tensor-source-deps --tensor-fixtures --noconftest \
  -p no:cacheprovider -q --tb=short \
  -k 'not test_large_arrow_tensor_array' \
  python/ray/data/tests/test_tensor_extension.py
  • Before the fix, with the same tests and dependencies: 13 failed, 205 passed, 3 deselected.
  • After the fix: 218 passed, 3 deselected.
  • All 23 newly added cases pass, including five variable-shaped boundary controls added following review.
  • The three deselected format variants each allocate approximately 2.2 GB. A complete native master build and distributed Ray integration tests were not run.
SKIP=buildifier,buildifier-lint,check-cpp-files-inclusion,check-json,check-toml,check-train-circular-imports,clang-format,cpplint,cython-lint,data-tests-location,eslint,mypy,prettier,pretty-format-java,pyrefly-serve,rst-directive-colons,rst-inline-touching-normal,shellcheck \
  pre-commit run --files \
  python/ray/data/_internal/tensor_extensions/pandas.py \
  python/ray/data/tests/test_tensor_extension.py
git diff --check

The SKIP list contains only hooks that pre-commit's own file classifier confirms have no matching changed files and are not always_run; it avoids installing unrelated language environments. No applicable check is skipped, and the repository hook configuration is unchanged.

All 13 applicable hook invocations passed, including both Ruff checks, pydoclint, Black, and the always-run repository-link check. They passed again automatically during the signed-off commit. git diff --check passed. A disposable real-commit probe also confirmed that the installed pre-commit hook rejects trailing whitespace.

@DogerW666
DogerW666 requested a review from a team as a code owner October 14, 2026 07:11

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request simplifies tensor assignment in pandas.py by replacing np.put with direct boolean indexing, and adds comprehensive unit tests for take operations and pandas Series reindexing. A review comment points out a potential ValueError when self._tensor is an object array (for variable-shaped tensors) because values is initialized as a float array, and suggests casting values to object dtype before assignment.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Oct 14, 2026

@Jadiouo Jadiouo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Independently verified against base 1ba2dca1 (parent of the first PR commit) and PR head ed1ac38b (Python 3.13, numpy 2.5.3, pandas 3.0.6).

  • The issue repro Series.reindex([0, 1, 2]) returns [[10, 11], [nan, nan], [nan, nan]] on base and [[10, 11], [20, 21], [nan, nan]] with the PR.
  • Of the 23 new tests, 13 fail on base and all pass with the PR.
  • The rest of test_tensor_extension.py shows no new failures. 4 tests fail on both base and the PR in my environment (test_tensor_array_scalar_cast x3, test_variable_shaped_null_rows_to_pandas_unchanged), probably due to newer numpy/pandas.

On the gemini comment: variable-shaped take([0, -1, 1], allow_fill=True) raises the same ValueError on base, so it's not a regression. I also tried the suggested object cast, and it breaks take([-1, -1]), which works today, so I agree with keeping it out of this PR.

LGTM.

One possible direction for the ragged case later, not for this PR: build the result as an object array row by row and use a small fill_value array (e.g. np.full((1,) * ndim, fill_value)) for missing rows, so the constructor accepts it. In a quick prototype, this made take([0, -1, 1]) work on ragged tensors while all-missing, empty and fixed-shape cases stayed identical to this PR. But isna() currently only treats None as missing (which the constructor rejects), so it would also need a decision on how a null ragged row is represented. Happy to open an issue if that's useful.

@DogerW666

Copy link
Copy Markdown
Author

Thanks @Jadiouo for the independent verification! Could a Ray Data code owner review this PR, and could a maintainer trigger the full CI with the go label or enable auto-merge when ready?

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Nov 3, 2026
@DogerW666

Copy link
Copy Markdown
Author

Hi @goutamvenkat-anyscale, I noticed your recent review of #67647 and merge of #67579 in the tensor/schema area. Could you take a look at this focused TensorArray.take fix, or help route it to the appropriate Ray Data code owner?

It fixes silent corruption of existing tensor rows when allow_fill=True is used, including through pandas Series.reindex. The PR includes regression tests, and there is independent reproduction and verification in the review above.

Thanks for your time!

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Nov 4, 2026
goutamvenkat-anyscale pushed a commit that referenced this pull request Nov 18, 2026
…able-shaped one (#67266)

## Description

`ArrowVariableShapedTensorArray.to_var_shaped_tensor_array()` fails
whenever the target `ndim` is larger than the array's own, so a tensor
column that is fixed-shape in one block and variable-shaped with fewer
dimensions in another can't be concatenated. Two lines were wrong, and
null rows weren't handled:

- `shapes_array.to_pylist()` returns lists, and
`_pad_shape_with_singleton_axes()` does `(1,) * k + shape`, so it raised
`TypeError: can only concatenate tuple (not "list") to tuple`. The
shapes are now converted with `tuple(s)`.
- `pa.StructArray.from_arrays()` was called without field names and
raised `ValueError: Must pass either names or fields`. It now passes
`["data", "shape"]`, the same as the other two places in the file that
build this storage.
- Null rows have a `None` shape, so they are skipped when padding, and
the source null mask is passed to `StructArray.from_arrays()` so they
stay null.
- When every row is null or there are no rows, `pa.array()` infers a
null type for the padded shapes and wrapping the storage fails with
`Incompatible storage type`. The shape type is now passed explicitly
(raised in review).

Added `test_unify_fixed_shaped_with_lower_ndim_variable_shaped`, which
unifies and concatenates a fixed-shape 2D array with a variable-shaped
1D one in both orders, `..._null_rows`, which does the same with a
sliced array that has a null row, and `..._no_valid_rows`, which uses an
all-null and an empty variable-shaped array in both orders. Existing
tests only unified arrays with the same `ndim`, so this branch wasn't
covered. The null-row tests read rows one at a time because `to_numpy()`
on null variable-shaped rows fails on master regardless of this change
(#67236 addresses that).

The 1D tensors come back as `(1, n)` because of the existing
singleton-axis padding. This PR doesn't change that.

## Related issues

Closes #67265

## Additional information

- Not a duplicate: #60389 had the same two changes as part of a larger
rework of `unify_tensor_arrays`, but it was closed as stale in February.
This PR only takes those two lines, handles null rows, and adds tests. I
searched open PRs for `to_var_shaped_tensor_array`,
`_pad_shape_with_singleton_axes`, `unify_tensor_arrays` and
tensor-related keywords; #66997 and #67236 touch other functions.
- Tests, run locally on master `7da1b4c` (`python/ray/data` from source
on a nightly wheel), Python 3.12.3, pyarrow 26.0.0, numpy 2.5.4:
- `pytest python/ray/data/tests/test_tensor_extension.py -k
unify_fixed_shaped_with_lower_ndim`: 21 passed. Without the fix, the
first 9 fail with `TypeError`. With the `None` guard but no mask, the
null-row test fails because the null row becomes valid. Without the
explicit shape type, the 12 `no_valid_rows` cases fail with
`Incompatible storage type`.
- The repro in #67265 and its `repartition(1).take_all()` variants in
both union orders now succeed.
- `pytest python/ray/data/tests/test_tensor_extension.py
python/ray/data/tests/test_transform_pyarrow.py
python/ray/data/tests/test_tensor.py
python/ray/data/tests/test_arrow_block.py
python/ray/data/tests/test_union.py`: 356 passed, 3 skipped, 5 failed.
The 5 fail the same way on unmodified master in my environment:
`test_tensor_array_scalar_cast` (3 formats),
`test_variable_shaped_null_rows_to_pandas_unchanged`, and
`test_tensors_sort[ARROW_NATIVE]`.
  - `pre-commit run --files <changed files>`: passed.
- AI assistance was used to prepare this PR.

---------

Signed-off-by: rayo5o <[email protected]>

This branch has not been deployed

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

Labels

community-contribution Contributed by the community data Ray Data-related issues unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] TensorArray.take silently corrupts tensor rows when filling missing indices

2 participants