Skip to content

Commit e7b7f69

Browse files
apacheGH-49644: [Python] Validate tensor shape, reject permuted tensors, use PyArray_CheckFromAny
1 parent 832acee commit e7b7f69

3 files changed

Lines changed: 47 additions & 14 deletions

File tree

‎python/pyarrow/array.pxi‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,24 @@ def array(object obj, type=None, mask=None, size=None, from_pandas=None,
266266
if type is not None and type.id == _Type_EXTENSION:
267267
extension_type = type
268268
type = type.storage_type
269+
# GH-49644: when building a fixed_shape_tensor from a sequence of arrays,
270+
# the converter only sees the flat storage type, so validate the
271+
# tensor-specific constraints here where the type is still known.
272+
if (isinstance(extension_type, FixedShapeTensorType)
273+
and isinstance(obj, (list, tuple))):
274+
if extension_type.permutation is not None:
275+
raise NotImplementedError(
276+
"Converting a sequence of arrays to a fixed_shape_tensor with "
277+
"a permutation is not supported; use "
278+
"FixedShapeTensorArray.from_numpy_ndarray instead")
279+
if np is not None:
280+
expected_shape = tuple(extension_type.shape)
281+
for element in obj:
282+
if (isinstance(element, np.ndarray) and element.ndim >= 2
283+
and tuple(element.shape) != expected_shape):
284+
raise ValueError(
285+
f"Cannot convert array of shape {element.shape} to a "
286+
f"fixed_shape_tensor of shape {expected_shape}")
269287

270288
if from_pandas is None:
271289
c_from_pandas = False

‎python/pyarrow/src/arrow/python/python_to_arrow.cc‎

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -908,25 +908,32 @@ class PyListConverter : public ListConverter<T, PyConverter, PyConverterTrait> {
908908

909909
Status AppendNdarray(PyObject* value) {
910910
PyArrayObject* ndarray = reinterpret_cast<PyArrayObject*>(value);
911+
if (PyArray_ISBYTESWAPPED(ndarray)) {
912+
// TODO
913+
return Status::NotImplemented("Byte-swapped arrays not supported");
914+
}
911915
OwnedRef flattened;
912916
if (PyArray_NDIM(ndarray) != 1) {
913-
// GH-49644: a fixed-size list (e.g. the storage of a fixed-shape tensor)
914-
// can be built from a multi-dimensional array by flattening it in C
915-
// order. The total number of elements must still match the list size,
916-
// which the builder validates below. 0-dimensional arrays and
917-
// variable-sized lists remain restricted to 1-dimensional values.
917+
// GH-49644: a fixed-size list (e.g. fixed-shape-tensor storage) can be
918+
// built from a multi-dimensional array, always flattened in C order
919+
// regardless of the input's memory layout.
918920
if (PyArray_NDIM(ndarray) < 2 || this->list_type_->id() != Type::FIXED_SIZE_LIST) {
919-
return Status::Invalid("Can only convert 1-dimensional array values");
921+
return Status::Invalid(
922+
"Can only convert 1-dimensional array values to a variable-sized list");
920923
}
921-
flattened.reset(PyArray_Ravel(ndarray, NPY_CORDER));
924+
// Get an aligned, C-contiguous array (copying only if needed), then view
925+
// it as 1-D so its values can be read directly in C order.
926+
PyObject* contiguous =
927+
PyArray_CheckFromAny(value, nullptr, /*min_depth=*/0, /*max_depth=*/0,
928+
NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_ALIGNED, nullptr);
929+
RETURN_IF_PYERROR();
930+
flattened.reset(
931+
PyArray_Ravel(reinterpret_cast<PyArrayObject*>(contiguous), NPY_CORDER));
932+
Py_DECREF(contiguous);
922933
RETURN_IF_PYERROR();
923934
value = flattened.obj();
924935
ndarray = reinterpret_cast<PyArrayObject*>(value);
925936
}
926-
if (PyArray_ISBYTESWAPPED(ndarray)) {
927-
// TODO
928-
return Status::NotImplemented("Byte-swapped arrays not supported");
929-
}
930937
const int64_t size = PyArray_SIZE(ndarray);
931938
RETURN_NOT_OK(AppendTo(this->list_type_, size));
932939
RETURN_NOT_OK(this->list_builder_->ValidateOverflow(size));

‎python/pyarrow/tests/test_extension_type.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1767,9 +1767,17 @@ def test_tensor_array_from_list_of_ndarrays(np_type_str):
17671767
assert result_with_null.null_count == 1
17681768
assert result_with_null[1].as_py() is None
17691769

1770-
# A flattened size that doesn't match the tensor shape is rejected
1771-
with pytest.raises(pa.lib.ArrowInvalid):
1772-
pa.array([np.arange(8, dtype=np_dtype).reshape(2, 4)], type=tensor_type)
1770+
# A multi-dimensional element whose shape doesn't match the tensor shape is
1771+
# rejected, even when the total number of elements is the same (GH-49644).
1772+
with pytest.raises(ValueError, match="shape"):
1773+
pa.array([np.arange(6, dtype=np_dtype).reshape(3, 2)], type=tensor_type)
1774+
1775+
# Permuted tensor types can't be built from a sequence (the flatten would
1776+
# store the wrong layout), so they're rejected for now.
1777+
permuted_type = pa.fixed_shape_tensor(
1778+
pa.from_numpy_dtype(np_dtype), (2, 3), permutation=[1, 0])
1779+
with pytest.raises(NotImplementedError, match="permutation"):
1780+
pa.array(elements, type=permuted_type)
17731781

17741782

17751783
@pytest.mark.numpy

0 commit comments

Comments
 (0)