Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
f4a3d5b
chore(tools): add a compatibility differential against a baseline zarr
d-v-b Nov 29, 2026
d6e1fb1
refactor(array): read and write Array through private _ArrayIO routines
d-v-b Nov 29, 2026
effcf45
refactor(array): split the routines into AsyncArrayIO and a sync ArrayIO
d-v-b Nov 29, 2026
a60dd4e
fix(array): keep AsyncArray's repair hooks in charge of its writes
d-v-b Nov 29, 2026
86305a1
refactor(array): run ArrayIO's coroutines through a runner in its con…
d-v-b Nov 29, 2026
ab1148e
fix(array): let AsyncArray's hook clear the repair mark
d-v-b Nov 29, 2026
e901d02
docs: add the changelog fragment for #470
d-v-b Nov 29, 2026
49854fa
refactor(array): take AsyncArrayIO's parts by keyword and derive the …
d-v-b Nov 29, 2026
aed95d8
refactor(array): reshape AsyncArrayIO and ArrayIO after zarrista
d-v-b Nov 29, 2026
869da17
fix(array): make ArrayIO values stateless and refuse writes that lose…
d-v-b Nov 29, 2026
6bb24a3
fix(array): refuse only writes that do not fit, and take metadata as …
d-v-b Nov 29, 2026
0ad8b6e
fix(array): accept leading length-1 axes and read chunk indices once
d-v-b Nov 29, 2026
968d103
fix(array): broadcast data to the region once before an ArrayIO write
d-v-b Nov 29, 2026
31cacfa
fix(array): only check that ArrayIO write data fits, leaving casts to…
d-v-b Nov 29, 2026
1a69bf5
test(array): cover ArrayIO's memoryview trimming and unbroadcast scalars
d-v-b Nov 29, 2026
48608f0
docs: file the changelog fragment for #470 as a feature
d-v-b Nov 29, 2026
19d95e8
feat(array): choose ArrayIO's runtime settings per call
d-v-b Nov 29, 2026
e90a6b9
refactor(array): keep no runtime configuration in an ArrayIO value
d-v-b Nov 29, 2026
78c6d4b
refactor(array): drop dtype and ndim from ArrayIO
d-v-b Nov 29, 2026
bf5cc0a
feat(array): define ArrayIO and AsyncArrayIO as protocols
d-v-b Nov 29, 2026
d0cef56
refactor(array): keep ZarrArrayIO's store private
d-v-b Nov 30, 2026
4549282
feat(array): limit ArrayIO selections to array subsets
d-v-b Nov 30, 2026
ae0e3e1
docs(array): state how ArrayIO slice bounds are read
d-v-b Nov 30, 2026
961ba8f
refactor(array): drop path from the ArrayIO protocols
d-v-b Nov 30, 2026
b3145ac
feat(array): write only exact DLPack arrays through ArrayIO
d-v-b Nov 30, 2026
30a7a76
fix(array): accept ArrayIO write data in either byte order
d-v-b Nov 30, 2026
928e55b
feat(array): read and write ArrayIO chunks in their full shape
d-v-b Nov 30, 2026
6522119
test(array): check ZarrArrayIO against zarrista
d-v-b Nov 30, 2026
5fc05be
fix(array): convert ArrayIO write data to the array's byte order
d-v-b Nov 30, 2026
4e99606
test(array): cross-read stores and compare bits against zarrista
d-v-b Nov 30, 2026
15d853b
build: include zarrista-tests in the dev dependency group
d-v-b Nov 30, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/470.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add `zarr.abc.array_io`, an interface of protocols for reading and writing an array as a value: `AsyncArrayIO`, `ArrayIO` (its synchronous counterpart), `ArrayResult` (what reads return) and `ArrayData` (what writes accept). zarr-python implements it with `AsyncZarrArrayIO` and `ZarrArrayIO`, which `AsyncArray` reads and writes through; `Array` and `AsyncArray` behave as before.
8 changes: 8 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,12 @@ test = [
"pytest-codspeed==5.0.4",
"uv==0.13.7",
]
# tests/test_array_io_zarrista.py checks ZarrArrayIO against zarrista. Only machines
# with zarrista wheels (elsewhere it builds from source, in Rust); not in min_deps,
# whose NumPy 2.0 and typing_extensions 4.14 zarrista does not support.
zarrista-tests = [
"zarrista==0.1.0; platform_machine == 'x86_64' or platform_machine == 'AMD64' or platform_machine == 'arm64' or platform_machine == 'aarch64'",
]
remote-tests = [
{include-group = "test"},
"fsspec>=2023.10.0",
Expand Down Expand Up @@ -157,6 +163,7 @@ docs = [
dev = [
{include-group = "test"},
{include-group = "remote-tests"},
{include-group = "zarrista-tests"},
{include-group = "docs"},
"universal-pathlib",
"mypy==2.4.1",
Expand Down Expand Up @@ -205,6 +212,7 @@ matrix.deps.features = [
]
matrix.deps.dependency-groups = [
{value = "remote-tests", if = ["optional"]},
{value = "zarrista-tests", if = ["optional"]},
]

[tool.hatch.envs.gputest]
Expand Down
282 changes: 282 additions & 0 deletions src/zarr/abc/array_io.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,282 @@
"""The interface for reading and writing an array as a value: `ArrayIO` (synchronous)
and `AsyncArrayIO` (asynchronous).

An implementation holds an array's metadata, bound to a location in a store. It is a
value: metadata changes (`with_shape`, `with_attrs`) return a new value and store
nothing, `store_metadata` stores a value's metadata, and every operation acts on the
value's metadata as it is, whatever the store holds now. How a value is made (opening
an array, binding metadata) is up to each implementation and is not part of the
interface.

zarr-python implements it with `zarr.core.array.ZarrArrayIO` and
`zarr.core.array.AsyncZarrArrayIO`. The interface is kept to what another
implementation, such as one built on zarrs, can provide without zarr-python's
internals:

- A selection is an array subset: slices with a step of 1 and `Ellipsis`, and the
data read or written has the subset's shape. Slice bounds mean what they mean to
NumPy: a negative bound counts from the end, a bound past the end is clipped, and a
slice that ends before it starts is empty. A tuple with fewer entries than
dimensions selects all of the trailing ones. The type of the error an
implementation raises for a selection it refuses is not part of the interface.
Integers are not selections, because implementations differ on whether an integer
keeps its axis; select one element of an axis with `slice(i, i + 1)`. NumPy
indexing (integers that drop axes, steps, index arrays) belongs to a layer above,
such as `zarr.Array`.
- Data read comes back as an array that `numpy.asarray` accepts (`ArrayResult`),
which may also export through DLPack, for `numpy.from_dlpack` or another library's
`from_dlpack`. Data written is an array that exports through DLPack (`ArrayData`),
with exactly the selected region's shape and the array's data type: nothing is
broadcast or cast, so that the same data means the same values to every
implementation. Byte order is not part of the data type; DLPack carries native
byte order, which every implementation reads. An implementation may refuse data it
cannot import: on a device it cannot read, of a data type or byte order it does not
take (DLPack has no strings, for example), or not in C order. Refusals differ
between implementations; values written do not.
- Chunk indices are non-negative integers, one for each dimension. Reading or
writing a chunk outside the chunk grid is not part of the interface. A chunk is
read and written in its full shape, as zarrs reads and writes it: a chunk at the
array's edge includes the part past the array's shape. That part's values are not
part of the interface: what it reads as for a stored chunk, and whether data
written there counts when deciding if a chunk holds only the fill value and is not
stored (a missing chunk reads as the fill value there as everywhere).
- Runtime choices are per operation: `read_missing_chunks` on reads,
`store_empty_chunks` on writes. Implementations may take more keyword options.
"""

from __future__ import annotations

from types import EllipsisType
from typing import TYPE_CHECKING, Any, Protocol, Self, runtime_checkable

from typing_extensions import CapsuleType

if TYPE_CHECKING:
from collections.abc import Iterable, Mapping, Sequence


__all__ = [
"ArrayData",
"ArrayIO",
"ArrayResult",
"AsyncArrayIO",
"Selection",
"SupportsDLPack",
]

type Selection = slice | EllipsisType | tuple[slice | EllipsisType, ...]
"""An array subset: slices with a step of 1 and at most one `Ellipsis`."""


@runtime_checkable
class SupportsDLPack(Protocol):
"""An array that exports its data through DLPack, as NumPy, CuPy, PyTorch and JAX
arrays do."""

def __dlpack__(
self,
*,
stream: int | None = None,
max_version: tuple[int, int] | None = None,
dl_device: tuple[int, int] | None = None,
copy: bool | None = None,
) -> CapsuleType:
"""Export the data as a DLPack capsule, with the keywords of the Python array
API standard."""
...

def __dlpack_device__(self) -> tuple[int, int]: ...


@runtime_checkable
class ArrayResult(Protocol):
"""Data read from an array: an array that `numpy.asarray` accepts, through
`__array__`. A NumPy array is one. A result may also export through DLPack
(`SupportsDLPack`), for `numpy.from_dlpack` and other libraries' `from_dlpack`, but
not every result can: DLPack has no strings or other variable-length data, and
NumPy exports only native byte order."""

def __array__(self, dtype: Any = ..., /, *, copy: bool | None = ...) -> Any: ...


type ArrayData = SupportsDLPack
"""Data to write to an array: an array that exports through DLPack, such as a NumPy,
CuPy, PyTorch or JAX array, with exactly the selected region's shape and the array's
data type. An implementation may refuse data on a device it cannot read, or of a data
type it cannot import."""


@runtime_checkable
class AsyncArrayIO(Protocol):
"""An array as a value, read and written asynchronously (see the module
documentation)."""

@property
def metadata(self) -> Mapping[str, object]:
"""The array's metadata document, which another value can be made from."""
...

@property
def attrs(self) -> Mapping[str, object]:
"""The array's user attributes."""
...

@property
def shape(self) -> Sequence[int]:
"""The shape of the array."""
...

@property
def needs_repair(self) -> bool:
"""Whether chunks cannot be stored until `store_metadata` has stored this
value's metadata, because it was repaired from a stored document in a way that
moves chunks. An implementation that repairs nothing returns `False`."""
...

def with_shape(self, shape: Sequence[int], /) -> Self:
"""This array with `shape`; nothing is stored and no chunk is erased."""
...

def with_attrs(self, attrs: Mapping[str, Any], /) -> Self:
"""This array with the user attributes `attrs`, which replace the old ones;
nothing is stored."""
...

async def store_metadata(self) -> Self:
"""Store this value's metadata, replacing what is stored, and return the array
as stored."""
...

async def erase_metadata(self) -> None:
"""Delete the array's metadata from the store; succeeds if there is none."""
...

async def erase_chunk(self, chunk_indices: Sequence[int], /) -> None:
"""Delete the chunk at `chunk_indices`; succeeds if there is none."""
...

async def erase_chunks(self, chunk_indices: Iterable[Sequence[int]], /) -> None:
"""Delete the chunk at each of `chunk_indices`."""
...

async def retrieve_array_subset(
self, selection: Selection, /, *, read_missing_chunks: bool = True
) -> ArrayResult:
"""The values at `selection`. A missing chunk reads as the fill value, or
raises with `read_missing_chunks=False`."""
...

async def store_array_subset(
self, selection: Selection, data: ArrayData, /, *, store_empty_chunks: bool = False
) -> None:
"""Write `data` at `selection`. A chunk left holding only the fill value is
deleted, unless `store_empty_chunks`."""
...

async def retrieve_chunk(
self, chunk_indices: Sequence[int], /, *, read_missing_chunks: bool = True
) -> ArrayResult:
"""The values of the chunk at `chunk_indices`, in the chunk's full shape."""
...

async def store_chunk(
self,
chunk_indices: Sequence[int],
data: ArrayData,
/,
*,
store_empty_chunks: bool = False,
) -> None:
"""Write `data`, in the chunk's full shape, as the chunk at `chunk_indices`."""
...

async def __getitem__(self, selection: Selection, /) -> ArrayResult:
"""`retrieve_array_subset(selection)`."""
...


@runtime_checkable
class ArrayIO(Protocol):
"""An array as a value, read and written synchronously: the same operations as
`AsyncArrayIO`, returning their results directly (see the module documentation)."""

@property
def metadata(self) -> Mapping[str, object]:
"""See `AsyncArrayIO.metadata`."""
...

@property
def attrs(self) -> Mapping[str, object]:
"""See `AsyncArrayIO.attrs`."""
...

@property
def shape(self) -> Sequence[int]:
"""See `AsyncArrayIO.shape`."""
...

@property
def needs_repair(self) -> bool:
"""See `AsyncArrayIO.needs_repair`."""
...

def with_shape(self, shape: Sequence[int], /) -> Self:
"""See `AsyncArrayIO.with_shape`."""
...

def with_attrs(self, attrs: Mapping[str, Any], /) -> Self:
"""See `AsyncArrayIO.with_attrs`."""
...

def store_metadata(self) -> Self:
"""See `AsyncArrayIO.store_metadata`."""
...

def erase_metadata(self) -> None:
"""See `AsyncArrayIO.erase_metadata`."""
...

def erase_chunk(self, chunk_indices: Sequence[int], /) -> None:
"""See `AsyncArrayIO.erase_chunk`."""
...

def erase_chunks(self, chunk_indices: Iterable[Sequence[int]], /) -> None:
"""See `AsyncArrayIO.erase_chunks`."""
...

def retrieve_array_subset(
self, selection: Selection, /, *, read_missing_chunks: bool = True
) -> ArrayResult:
"""See `AsyncArrayIO.retrieve_array_subset`."""
...

def store_array_subset(
self, selection: Selection, data: ArrayData, /, *, store_empty_chunks: bool = False
) -> None:
"""See `AsyncArrayIO.store_array_subset`."""
...

def retrieve_chunk(
self, chunk_indices: Sequence[int], /, *, read_missing_chunks: bool = True
) -> ArrayResult:
"""See `AsyncArrayIO.retrieve_chunk`."""
...

def store_chunk(
self,
chunk_indices: Sequence[int],
data: ArrayData,
/,
*,
store_empty_chunks: bool = False,
) -> None:
"""See `AsyncArrayIO.store_chunk`."""
...

def __getitem__(self, selection: Selection, /) -> ArrayResult:
"""See `AsyncArrayIO.retrieve_array_subset`."""
...

def __setitem__(self, selection: Selection, data: ArrayData, /) -> None:
"""See `AsyncArrayIO.store_array_subset`."""
...
Loading
Loading