From 956b39703a1157ce421163c98767a7d5affbed1f Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Wed, 18 Nov 2026 19:55:28 +0000 Subject: [PATCH] feat(python): add ChunkedArray.from_chunks Python had no way to combine Vortex arrays that are already in memory into a chunked array. A caller that holds arrays from several sources or from earlier reads made one take for each array that a batch touched, then concatenated the parts and put the rows back in the order of the request. `vortex.open_dataset` reads rows across files, but it scans the files again, so it does not replace a take on arrays that are already in memory. `ChunkedArray.from_chunks(chunks, *, dtype=None)` combines arrays of one dtype with no copy. One take on the result then reads rows of all the arrays, in any order. - The chunks of a chunked input become chunks of the result, so the result has one level of chunks. - Chunks can differ in nullability. If one chunk is nullable, the result is nullable, and a non-nullable chunk gets a cast to the nullable dtype. The cast changes only the nullability, so it copies no data. A non-nullable chunk can also go into a nullable `dtype`. - Chunks of a different type are an error, as before. - `dtype` is necessary only when `chunks` is empty. --- vortex-python/python/vortex/_lib/arrays.pyi | 2 + vortex-python/src/arrays/builtins/chunked.rs | 104 +++++++++++++++++++ vortex-python/test/test_array.py | 52 ++++++++++ 3 files changed, 158 insertions(+) diff --git a/vortex-python/python/vortex/_lib/arrays.pyi b/vortex-python/python/vortex/_lib/arrays.pyi index 0ded6ebf993..170c6e27df3 100644 --- a/vortex-python/python/vortex/_lib/arrays.pyi +++ b/vortex-python/python/vortex/_lib/arrays.pyi @@ -99,6 +99,8 @@ class ConstantArray(Array): @final class ChunkedArray(Array): def chunks(self) -> list[Array]: ... + @staticmethod + def from_chunks(chunks: list[Array], *, dtype: DType | None = None) -> ChunkedArray: ... @final class ByteBoolArray(Array): ... diff --git a/vortex-python/src/arrays/builtins/chunked.rs b/vortex-python/src/arrays/builtins/chunked.rs index 5ca1aafd67f..396d7c02e39 100644 --- a/vortex-python/src/arrays/builtins/chunked.rs +++ b/vortex-python/src/arrays/builtins/chunked.rs @@ -1,15 +1,27 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use pyo3::Bound; use pyo3::PyRef; +use pyo3::exceptions::PyValueError; use pyo3::pyclass; use pyo3::pymethods; +use vortex::array::ArrayRef; +use vortex::array::IntoArray; use vortex::array::arrays::Chunked; +use vortex::array::arrays::ChunkedArray; use vortex::array::arrays::chunked::ChunkedArrayExt; +use vortex::array::builtins::ArrayBuiltins; +use vortex::array::optimizer::ArrayOptimizer; +use vortex::dtype::DType; +use vortex::error::VortexResult; use crate::arrays::PyArrayRef; use crate::arrays::native::EncodingSubclass; use crate::arrays::native::PyNativeArray; +use crate::dtype::PyDType; +use crate::error::PyVortexResult; +use crate::session::session; /// Concrete class for arrays with `vortex.chunked` encoding. #[pyclass(name = "ChunkedArray", module = "vortex", extends=PyNativeArray, frozen)] @@ -30,4 +42,96 @@ impl PyChunkedArray { .map(|chunk| PyArrayRef::from(chunk.clone())) .collect() } + + /// Combine arrays of one data type into a chunked array, with no copy. + /// + /// Use it for arrays that are already in memory, such as the results of earlier reads or of + /// several sources. One `take` on the result then reads rows of all the arrays, in any order. + /// + /// The chunks of a chunked array in `chunks` become chunks of the result, so the result has + /// one level of chunks. + /// + /// Parameters + /// ---------- + /// chunks: list[vortex.Array] + /// The arrays to combine, in order. They must all have the same data type, but they can + /// differ in nullability. If one of them is nullable, the result is nullable. + /// dtype: vortex.DType | None + /// The data type of the result. It is necessary only when `chunks` is empty. A + /// non-nullable chunk can go into a nullable `dtype`. + /// + /// Returns + /// ------- + /// :class:`~vortex.ChunkedArray` + /// + /// Examples + /// -------- + /// + /// ```python + /// >>> a = vx.array([1, 2, 3]) + /// >>> b = vx.array([4, 5]) + /// >>> chunked = vx.ChunkedArray.from_chunks([a, b]) + /// >>> chunked.take(vx.array([4, 0])).to_arrow_array() + /// + /// [ + /// 5, + /// 1 + /// ] + /// ``` + #[staticmethod] + #[pyo3(signature = (chunks, *, dtype = None))] + fn from_chunks( + chunks: Vec, + dtype: Option>, + ) -> PyVortexResult { + let mut flat: Vec = Vec::with_capacity(chunks.len()); + + for chunk in chunks { + let chunk = chunk.into_inner(); + + match chunk.as_opt::() { + Some(chunked) => flat.extend(chunked.iter_chunks().cloned()), + None => flat.push(chunk), + } + } + + let dtype = match (dtype, flat.first()) { + (Some(dtype), _) => dtype.get().inner().clone(), + + // A chunk with nulls makes the result nullable. + (None, Some(first)) if flat.iter().any(|chunk| chunk.dtype().is_nullable()) => { + first.dtype().as_nullable() + } + + (None, Some(first)) => first.dtype().clone(), + + (None, None) => { + return Err(PyValueError::new_err( + "Cannot infer the dtype of a chunked array with no chunks; pass dtype.", + ) + .into()); + } + }; + + let flat = flat + .into_iter() + .map(|chunk| as_nullable_chunk(chunk, &dtype)) + .collect::>>()?; + + Ok(PyArrayRef::from( + ChunkedArray::try_new(flat, dtype)?.into_array(), + )) + } +} + +/// Cast a non-nullable chunk to `dtype` if `dtype` is the same type, but nullable. +/// +/// The cast changes only the nullability, so it copies no data. Other chunks do not change, and +/// `ChunkedArray::try_new` rejects a chunk of a different type. +fn as_nullable_chunk(chunk: ArrayRef, dtype: &DType) -> VortexResult { + if chunk.dtype().is_nullable() || &chunk.dtype().as_nullable() != dtype { + return Ok(chunk); + } + + chunk.cast(dtype.clone())?.optimize_ctx(session()) } diff --git a/vortex-python/test/test_array.py b/vortex-python/test/test_array.py index d1ded4e0de5..12d18b6a4f0 100644 --- a/vortex-python/test/test_array.py +++ b/vortex-python/test/test_array.py @@ -28,6 +28,58 @@ def test_chunked_array_with_nulls_round_trip() -> None: assert arr.to_arrow_array() == a +def test_chunked_array_from_chunks_takes_across_chunks() -> None: + a = vortex.array(pa.chunked_array([[0, 1, 2], [3, 4]])) + b = vortex.array(pa.array([5, 6, 7])) + + chunked = vortex.ChunkedArray.from_chunks([a, b]) + + # The chunks of a chunked input become chunks of the result. + assert len(chunked.chunks()) == 3 + assert len(chunked) == 8 + + taken = chunked.take(vortex.array(pa.array([7, 0, 3, 3, 5], type=pa.uint64()))) + assert taken.to_arrow_array().equals(pa.array([7, 0, 3, 3, 5])) + + +def test_chunked_array_from_chunks_empty() -> None: + dtype = vortex.array(pa.array([1])).dtype + + empty = vortex.ChunkedArray.from_chunks([], dtype=dtype) + assert len(empty) == 0 + assert empty.dtype == dtype + + with pytest.raises(ValueError): + vortex.ChunkedArray.from_chunks([]) + + +def test_chunked_array_from_chunks_rejects_mixed_dtypes() -> None: + with pytest.raises(RuntimeError, match="expected type"): + vortex.ChunkedArray.from_chunks([vortex.array(pa.array([1])), vortex.array(pa.array(["a"]))]) + + +def test_chunked_array_from_chunks_mixed_nullability() -> None: + non_nullable = vortex.array(pa.array([1, 2])) + nullable = vortex.array(pa.array([3, None])) + + # A nullable chunk makes the result nullable, in any position. + for chunks in ([non_nullable, nullable], [nullable, non_nullable]): + chunked = vortex.ChunkedArray.from_chunks(chunks) + assert chunked.dtype == nullable.dtype + + chunked = vortex.ChunkedArray.from_chunks([non_nullable, nullable]) + taken = chunked.take(vortex.array(pa.array([3, 0, 2], type=pa.uint64()))) + assert taken.to_arrow_array().equals(pa.array([None, 1, 3])) + + # A non-nullable chunk goes into a nullable dtype. + chunked = vortex.ChunkedArray.from_chunks([non_nullable], dtype=nullable.dtype) + assert chunked.dtype == nullable.dtype + + # A nullable chunk does not go into a non-nullable dtype. + with pytest.raises(RuntimeError, match="expected type"): + vortex.ChunkedArray.from_chunks([nullable], dtype=non_nullable.dtype) + + def test_decimal_array() -> None: a = pa.array([decimal.Decimal("1.23"), None], type=pa.decimal128(10, 2)) arr = vortex.array(a)