diff --git a/changes/470.feature.md b/changes/470.feature.md new file mode 100644 index 0000000000..c469cf2a7c --- /dev/null +++ b/changes/470.feature.md @@ -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. diff --git a/pyproject.toml b/pyproject.toml index 839b5fdef8..dcb20c3fd9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", @@ -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", @@ -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] diff --git a/src/zarr/abc/array_io.py b/src/zarr/abc/array_io.py new file mode 100644 index 0000000000..fcdce31e8a --- /dev/null +++ b/src/zarr/abc/array_io.py @@ -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`.""" + ... diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 3735a4da18..d9285306f0 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -3,6 +3,7 @@ import contextlib import copy import math +import operator import warnings from asyncio import gather from collections.abc import Iterable, Mapping, Sequence @@ -12,9 +13,11 @@ from typing import ( TYPE_CHECKING, Any, + Final, Literal, TypedDict, cast, + final, overload, ) from warnings import warn @@ -23,6 +26,8 @@ from typing_extensions import Sentinel, deprecated import zarr +from zarr.abc.array_io import Selection as ArraySubsetSelection +from zarr.abc.array_io import SupportsDLPack from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec, Codec from zarr.abc.numcodec import Numcodec, _is_numcodec from zarr.codecs._v2 import V2Codec @@ -142,10 +147,11 @@ create_chunk_grid_metadata, parse_node_type_array, ) -from zarr.core.sync import sync +from zarr.core.sync import SyncContext, sync from zarr.errors import ( ArrayNotFoundError, ChunkNotFoundError, + MetadataRepairRequiredError, MetadataValidationError, ZarrDeprecationWarning, ZarrUserWarning, @@ -161,11 +167,12 @@ from zarr.storage._utils import _relativize_path if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Coroutine, Iterator from typing import Self import numpy.typing as npt + from zarr.abc.array_io import ArrayData, ArrayResult from zarr.abc.codec import CodecPipeline from zarr.abc.store import Store from zarr.codecs.sharding import IndexLocation, ShardingCodec @@ -1474,16 +1481,8 @@ async def _get_selection( out: NDBuffer | None = None, fields: Fields | None = None, ) -> NDArrayLikeOrScalar: - return await _get_selection( - self.store_path, - self.metadata, - self.codec_pipeline, - self.config, - self._chunk_grid, - indexer, - prototype=prototype, - out=out, - fields=fields, + return await AsyncZarrArrayIO._of(self)._get_selection( + indexer, prototype=prototype, out=out, fields=fields, config=self.config ) async def getitem( @@ -1625,7 +1624,7 @@ def _stored_document_replaced(self) -> None: holds, which a consolidated group handle may share, then stops standing for the document it was read from (see `mark_repaired`), so no later write through either handle stores that document again.""" - object.__setattr__(self.metadata, "_stored_document", None) + _stored_document_replaced(self.metadata) async def _store_repaired_document(self) -> None: """Store the repair of this array's current stored document, if it needs one, @@ -1647,20 +1646,9 @@ async def _store_repaired_document(self) -> None: """ if self.metadata._stored_document is None: return - zarr_format = self.metadata.zarr_format - documents = await read_documents(self.store_path, ARRAY_DOCUMENTS[zarr_format]) - try: - current = parse_stored_array(documents, zarr_format, str(self.store_path)) - except ArrayNotFoundError: - pass - else: - if _chunk_layout(current) != _chunk_layout(self.metadata): - raise ValueError( - f"Array {str(self.store_path)!r}: the metadata stored has changed since " - "this array was opened; reopen the array to write to it. Nothing was stored." - ) - if current._stored_document is not None: - await upsert_metadata(self.store_path, current, documents) + await AsyncZarrArrayIO._of(self)._store_repair_document() + # The mark is cleared through the method, as always, so a subclass that + # overrides it decides. self._stored_document_replaced() async def _set_selection( @@ -1675,16 +1663,10 @@ async def _set_selection( # Chunks are about to be stored under the repaired metadata, so store it # first: every reader of the store then agrees with them. await self._store_repaired_document() - return await _set_selection( - self.store_path, - self.metadata, - self.codec_pipeline, - self.config, - self._chunk_grid, - indexer, - value, - prototype=prototype, - fields=fields, + # `_store_repaired_document` is this array's repair policy, which a subclass may + # override, so the write is not checked against the repair a second time. + return await AsyncZarrArrayIO._of(self)._write_selection( + indexer, value, prototype=prototype, fields=fields, config=self.config ) async def setitem( @@ -1920,6 +1902,886 @@ def _info( ) +def _stored_document_replaced(metadata: ArrayMetadata) -> None: + """Record that the store no longer holds a document of the array `metadata` was read + from that needs a repair: it holds the repair, a valid document, or none. `metadata`, + which several handles may share, then stops standing for that document (see + `mark_repaired`), so no later write through any of them stores it again.""" + object.__setattr__(metadata, "_stored_document", None) + + +def _appended( + shape: tuple[int, ...], data: npt.ArrayLike, axis: int +) -> tuple[Any, tuple[int, ...], tuple[slice, ...]]: + """For appending `data` along `axis` to an array of `shape`: `data` as an array, the + new shape, and the selection the data is written to.""" + # ensure data is array-like + if not hasattr(data, "shape"): + data = np.asanyarray(data) + + self_shape_preserved = tuple(s for i, s in enumerate(shape) if i != axis) + data_shape_preserved = tuple(s for i, s in enumerate(data.shape) if i != axis) + if self_shape_preserved != data_shape_preserved: + raise ValueError( + f"shape of data to append is not compatible with the array. " + f"The shape of the data is ({data_shape_preserved})" + f"and the shape of the array is ({self_shape_preserved})." + "All dimensions must match except for the dimension being " + "appended." + ) + new_shape = tuple( + shape[i] if i != axis else shape[i] + data.shape[i] for i in range(len(shape)) + ) + selection = tuple( + slice(None) if i != axis else slice(shape[i], new_shape[i]) for i in range(len(shape)) + ) + return data, new_shape, selection + + +async def _delete_chunk(key: StorePath) -> None: + await key.delete() + + +def _snapshot(metadata: ArrayMetadata) -> ArrayMetadata: + """A copy of `metadata` with attributes of its own, nested values included, so a + change to the attributes of the original (which an `AsyncArray` makes in place) + never reaches the copy. The repair mark, an instance attribute, is copied with it.""" + copied = copy.copy(metadata) + object.__setattr__(copied, "attributes", copy.deepcopy(metadata.attributes)) + return copied + + +_ARRAY_IO_CONFIG: Final = ArrayConfig(order="C", write_empty_chunks=False) +"""The runtime configuration `AsyncZarrArrayIO`'s public reads and writes start from: fixed, +not read from the global configuration. Each operation sets its own choices on it.""" + + +def _read_config(read_missing_chunks: bool) -> ArrayConfig: + """The configuration of one public read.""" + return replace(_ARRAY_IO_CONFIG, read_missing_chunks=read_missing_chunks) + + +def _write_config(store_empty_chunks: bool) -> ArrayConfig: + """The configuration of one public write.""" + return replace(_ARRAY_IO_CONFIG, write_empty_chunks=store_empty_chunks) + + +_DLPACK_CPU: Final = 1 +"""DLPack's device type for host memory (`kDLCPU`).""" + + +def _in_native_byte_order(dtype: np.dtype[Any]) -> np.dtype[Any]: + """`dtype` in native byte order, fields and subarrays included; a data type without + a byte order (`StringDType`) as it is.""" + try: + return dtype.newbyteorder("=") + except TypeError: + return dtype + + +def _exact_data(data: ArrayData, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: + """`data` to write to a region of `shape` of an array of `dtype`: an array that + exports through DLPack, as every NumPy array does, with exactly that shape and data + type. Byte order is not part of the data type: it changes no value, and DLPack + carries only native byte order, so data in either order is written, converted to + the array's byte order here (codecs such as numcodecs filters read the bytes of + the data as the array's data type). Nothing is broadcast or cast. Raises + `TypeError` for other data or another data type, and `ValueError` for another + shape. + + Host data with `__array__` is read with `numpy.asarray`, as that data's own NumPy + view, since some of it (NumPy string and record arrays, non-native byte order) + cannot export through DLPack; host data without it is viewed through + `numpy.from_dlpack`. Device data with `__array__` (CuPy) is passed on as it is, for a + device prototype to write.""" + if not isinstance(data, SupportsDLPack): + raise TypeError( + f"Data to write must be an array that exports through DLPack, such as a NumPy " + f"array, not {type(data).__name__}." + ) + device = data.__dlpack_device__() + array: Any + if device[0] == _DLPACK_CPU: + array = np.asarray(data) if hasattr(data, "__array__") else np.from_dlpack(data) + elif hasattr(data, "__array__"): + array = data + else: + raise TypeError( + f"Data that exports only through DLPack must be in host memory; it is on " + f"DLPack device {device}." + ) + if tuple(array.shape) != shape: + raise ValueError( + f"Data of shape {tuple(array.shape)} does not match the region's shape {shape}." + ) + try: + given = np.dtype(array.dtype) + except TypeError: + raise TypeError( + f"Data of data type {array.dtype}, which NumPy cannot read, does not match the " + f"array's data type {dtype}." + ) from None + if _in_native_byte_order(given) != _in_native_byte_order(np.dtype(dtype)): + raise TypeError( + f"Data of data type {array.dtype} does not match the array's data type " + f"{dtype}; cast it first." + ) + return array if given == dtype else array.astype(dtype) + + +@final +@dataclass(frozen=True, slots=True, eq=False, init=False, repr=False) +class AsyncZarrArrayIO: + """An array, as a value: its metadata, bound to a location in a store. + + Make one with `open` (reads the metadata from the store), `from_metadata` (binds + metadata you already have, storing and checking nothing) or `of` (the array an + `Array` or `AsyncArray` reads and writes). + + Metadata changes are values too. `with_shape` and `with_attrs` return a new value + and store nothing; `store_metadata` stores a value's metadata. Every operation acts + on this value's metadata as it is, whatever the store holds now: an older value + still describes the array as it was, and storing its metadata replaces newer + metadata. Chunks are erased only on request (`erase_chunk`, `erase_chunks`). + + Nothing is repaired implicitly. A value whose metadata was read from a document + that needs a repair that moves chunks (such as a stored chunk size of 0) holds the + repaired metadata and `needs_repair` is true; storing chunks raises + `MetadataRepairRequiredError` until `store_metadata` has stored the repaired + metadata. + + Runtime choices belong to the operation, not the value: a read takes + `read_missing_chunks`, a write takes `store_empty_chunks`. Data is returned in C + order, except that a Zarr format 2 array keeps the order its metadata declares. + """ + + _metadata: ArrayMetadata + _store_path: StorePath + _codec_pipeline: CodecPipeline + _chunk_grid: ChunkGrid + _needs_repair: bool + + def __init__(self) -> None: + raise TypeError( + "Make an AsyncZarrArrayIO with AsyncZarrArrayIO.open, AsyncZarrArrayIO.from_metadata or " + "AsyncZarrArrayIO.of." + ) + + @classmethod + def _from_parts( + cls, + metadata: ArrayMetadata, + store_path: StorePath, + codec_pipeline: CodecPipeline, + chunk_grid: ChunkGrid, + needs_repair: bool, + ) -> AsyncZarrArrayIO: + io = object.__new__(cls) + object.__setattr__(io, "_metadata", metadata) + object.__setattr__(io, "_store_path", store_path) + object.__setattr__(io, "_codec_pipeline", codec_pipeline) + object.__setattr__(io, "_chunk_grid", chunk_grid) + object.__setattr__(io, "_needs_repair", needs_repair) + return io + + @classmethod + def _bound( + cls, metadata: ArrayMetadata | ArrayMetadataDict, store_path: StorePath + ) -> AsyncZarrArrayIO: + """A value over `metadata`, read as `AsyncArray` reads it, deriving its codec + pipeline and chunk grid.""" + parsed = parse_array_metadata(metadata, str(store_path)) + return cls._from_parts( + parsed, + store_path, + create_codec_pipeline(metadata=parsed, store=store_path.store), + ChunkGrid.from_metadata(parsed), + parsed._stored_document is not None, + ) + + @classmethod + async def open( + cls, + store: Store, + path: str = "", + *, + zarr_format: ZarrFormat | None = None, + ) -> AsyncZarrArrayIO: + """The array whose metadata `store` holds at `path`, of either Zarr format + unless `zarr_format` says which. + + Raises `ArrayNotFoundError` if there is no array metadata there, and + `NodeTypeValidationError` if a group's is.""" + store_path = StorePath(store, path) + document = await get_array_metadata(store_path, zarr_format=zarr_format) + return cls._bound(cast("ArrayMetadataDict", document), store_path) + + @classmethod + def from_metadata( + cls, + metadata: ArrayMetadata | Mapping[str, JSON], + store: Store, + path: str = "", + ) -> AsyncZarrArrayIO: + """An array at `path` in `store` with `metadata`, a metadata object or document. + + Nothing is stored and nothing is checked against the store: call + `store_metadata` to store the metadata, and do so before storing chunks unless + the store already holds it.""" + bound: ArrayMetadata | ArrayMetadataDict = ( + _snapshot(metadata) + if isinstance(metadata, ArrayV2Metadata | ArrayV3Metadata) + else cast("ArrayMetadataDict", copy.deepcopy(dict(metadata))) + ) + return cls._bound(bound, StorePath(store, path)) + + @classmethod + def of(cls, array: AsyncArray[Any] | Array[Any]) -> AsyncZarrArrayIO: + """The array `array` reads and writes, as it is now. Later changes through + `array` do not reach the value.""" + source = array.async_array if isinstance(array, Array) else array + metadata = _snapshot(source.metadata) + return cls._from_parts( + metadata, + source.store_path, + source.codec_pipeline, + source._chunk_grid, + metadata._stored_document is not None, + ) + + @classmethod + def _of(cls, array: AsyncArray[Any]) -> AsyncZarrArrayIO: + """The routines over `array`'s own fields, sharing its metadata, for `AsyncArray` + to read and write through.""" + return cls._from_parts( + array.metadata, + array.store_path, + array.codec_pipeline, + array._chunk_grid, + array.metadata._stored_document is not None, + ) + + def as_sync(self, *, context: SyncContext) -> ZarrArrayIO: + """This array, read and written synchronously with the runner `context` holds: + one that runs coroutines where this value's store clients can run them.""" + return ZarrArrayIO._wrap(self, context) + + def __repr__(self) -> str: + dtype = self._metadata.dtype.to_native_dtype() + return f"" + + @property + def metadata(self) -> dict[str, JSON]: + """The array's metadata as a document of its own, which `from_metadata` reads + back: the `zarr.json` document for Zarr format 3, or for format 2 the `.zarray` + document with the attributes under `"attributes"`.""" + return copy.deepcopy(self._metadata.to_dict()) + + @property + def attrs(self) -> dict[str, JSON]: + """The array's user attributes, as a dict of its own.""" + return copy.deepcopy(self._metadata.attributes) + + @property + def shape(self) -> tuple[int, ...]: + """The shape of the array.""" + return self._metadata.shape + + @property + def path(self) -> str: + """The array's path in its store.""" + return self._store_path.path + + @property + def needs_repair(self) -> bool: + """Whether this value's metadata was repaired from a stored document in a way + that moves chunks, and has not been stored since: chunks cannot be stored until + `store_metadata` has stored it, and are then stored through the value it + returns. A repair that reads a regular grid's edge lists as a rectilinear grid + can be stored only while rectilinear chunk grids are enabled.""" + return self._needs_repair + + def with_shape(self, shape: ShapeLike, /) -> AsyncZarrArrayIO: + """This array with `shape`. Nothing is stored and no chunk is erased: chunks + outside a smaller shape stay in the store until erased (`erase_chunks`), and + growing again reads what they and the edge chunks still hold beyond the old + shape; the new region reads as the fill value only where no chunk was stored.""" + new_shape = parse_shapelike(shape) + if len(new_shape) != len(self._metadata.shape): + raise ValueError( + f"The new shape must have the same number of dimensions as the array. " + f"Got {len(new_shape)} dimension(s), expected {len(self._metadata.shape)}." + ) + new_metadata = self._metadata.update_shape(new_shape) + return AsyncZarrArrayIO._from_parts( + new_metadata, + self._store_path, + self._codec_pipeline, + ChunkGrid.from_metadata(new_metadata), + self._needs_repair, + ) + + def with_attrs(self, attrs: Mapping[str, JSON], /) -> AsyncZarrArrayIO: + """This array with the user attributes `attrs`, which replace the old ones: + merge them yourself to keep them (`io.with_attrs({**io.attrs, "units": "m"})`). + Nothing is stored.""" + return AsyncZarrArrayIO._from_parts( + self._metadata.update_attributes(copy.deepcopy(dict(attrs))), + self._store_path, + self._codec_pipeline, + self._chunk_grid, + self._needs_repair, + ) + + async def store_metadata(self) -> AsyncZarrArrayIO: + """Store this value's metadata at the array's path, replacing whatever metadata + is there, and return the array as stored: if this value needed a repair, the + returned one does not.""" + await save_metadata(self._store_path, self._metadata) + return AsyncZarrArrayIO._from_parts( + self._metadata, + self._store_path, + self._codec_pipeline, + self._chunk_grid, + False, + ) + + async def erase_metadata(self) -> None: + """Delete the array's metadata documents from the store; succeeds if there are + none.""" + keys = ARRAY_DOCUMENTS[self._metadata.zarr_format] + await gather(*((self._store_path / key).delete() for key in keys)) + + def _chunk_indices(self, chunk_indices: Iterable[int], *, in_grid: bool) -> tuple[int, ...]: + """`chunk_indices` as a tuple of non-negative ints, one for each dimension; with + `in_grid`, within the chunk grid.""" + given = tuple(chunk_indices) + if any(isinstance(index, bool | np.bool_) for index in given): + raise TypeError(f"Chunk indices must be integers, not booleans: {given}.") + indices = tuple(operator.index(index) for index in given) + ndim = len(self._metadata.shape) + if len(indices) != ndim: + raise ValueError( + f"Chunk indices {indices} do not have one index for each of the array's " + f"{ndim} dimensions." + ) + if any(index < 0 for index in indices): + raise ValueError(f"Chunk indices {indices} must be non-negative.") + grid_shape = self._chunk_grid.grid_shape + if in_grid and any( + index >= extent for index, extent in zip(indices, grid_shape, strict=True) + ): + raise IndexError(f"Chunk indices {indices} are outside the chunk grid {grid_shape}.") + return indices + + def _subset_indexer(self, selection: ArraySubsetSelection) -> BasicIndexer: + """The indexer for `selection`, which must hold only slices with a step of 1 and + `Ellipsis`.""" + selectors = selection if isinstance(selection, tuple) else (selection,) + for selector in selectors: + if isinstance(selector, slice): + if selector.step not in (None, 1): + raise ValueError(f"A selection takes slices with a step of 1, not {selector}.") + elif selector is not Ellipsis: + raise TypeError( + f"A selection takes slices and Ellipsis, not {type(selector).__name__} " + f"({selector!r}). For one element of an axis, select slice(i, i + 1)." + ) + return BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) + + async def erase_chunk(self, chunk_indices: Iterable[int], /) -> None: + """Delete the chunk at `chunk_indices` from the store; it then reads as the fill + value. Succeeds if there is none. Indices outside the chunk grid are allowed, + to reclaim chunks left outside a smaller shape.""" + indices = self._chunk_indices(chunk_indices, in_grid=False) + await (self._store_path / self._metadata.encode_chunk_key(indices)).delete() + + async def erase_chunks(self, chunk_indices: Iterable[Iterable[int]], /) -> None: + """Delete the chunk at each of `chunk_indices`, as `erase_chunk` does.""" + keys = [ + ( + self._store_path + / self._metadata.encode_chunk_key(self._chunk_indices(indices, in_grid=False)), + ) + for indices in chunk_indices + ] + if keys: + # `None` lifts the I/O concurrency limit, but the worker pool still needs a + # bound; 1000 keeps the pool far smaller than the work. + limit = zarr_config.get("async.concurrency") or 1000 + await concurrent_foreach(iter(keys), _delete_chunk, min(limit, len(keys))) + + async def retrieve_array_subset( + self, + selection: ArraySubsetSelection, + /, + *, + read_missing_chunks: bool = True, + prototype: BufferPrototype | None = None, + ) -> ArrayResult: + """The values in the array subset `selection`: slices with a step of 1 and + `Ellipsis`, with the subset's shape. Raises `TypeError` for any other selector, + integers included, and `ValueError` for another step. + + A chunk missing from the store reads as the fill value; with + `read_missing_chunks=False`, it raises `ChunkNotFoundError` instead, for data + known to be complete that is read over a connection that can fail.""" + indexer = self._subset_indexer(selection) + return await self._retrieve( + indexer, + prototype=default_buffer_prototype() if prototype is None else prototype, + read_missing_chunks=read_missing_chunks, + ) + + async def store_array_subset( + self, + selection: ArraySubsetSelection, + data: ArrayData, + /, + *, + store_empty_chunks: bool = False, + prototype: BufferPrototype | None = None, + ) -> None: + """Write `data` to the array subset `selection`, which is as for + `retrieve_array_subset`. + + `data` is an array that exports through DLPack, such as a NumPy array, with + exactly the region's shape and the array's data type (`TypeError` for other data + or another data type, `ValueError` for another shape); nothing is broadcast or + cast, so cast first (`data.astype(...)`). A chunk left holding only the fill + value is deleted from the store, unless `store_empty_chunks`. Raises + `MetadataRepairRequiredError` while `needs_repair` is true. Nothing is written + when it raises.""" + indexer = self._subset_indexer(selection) + await self._set_selection( + indexer, + _exact_data(data, self._metadata.dtype.to_native_dtype(), indexer.shape), + prototype=default_buffer_prototype() if prototype is None else prototype, + config=_write_config(store_empty_chunks), + ) + + async def retrieve_chunk( + self, + chunk_indices: Iterable[int], + /, + *, + read_missing_chunks: bool = True, + prototype: BufferPrototype | None = None, + ) -> ArrayResult: + """The decoded values of the chunk at `chunk_indices`, in the chunk's full shape, + as zarrs reads it: a chunk at the array's edge includes the part past the array's + shape, which reads as the fill value. A missing chunk is handled as + `retrieve_array_subset` handles it.""" + indices = self._chunk_indices(chunk_indices, in_grid=True) + prototype = default_buffer_prototype() if prototype is None else prototype + indexer = BlockIndexer(indices, self._metadata.shape, self._chunk_grid) + inside = self._chunk_inside(indices) + if inside is None: + return await self._retrieve( + indexer, prototype=prototype, read_missing_chunks=read_missing_chunks + ) + full_shape, region = inside + out = prototype.nd_buffer.create( + shape=full_shape, + dtype=self._metadata.dtype.to_native_dtype(), + order=self._metadata.order if isinstance(self._metadata, ArrayV2Metadata) else "C", + fill_value=self._fill_value(), + ) + await self._get_selection( + indexer, + prototype=prototype, + out=out[region], + config=_read_config(read_missing_chunks), + ) + return cast("ArrayResult", out.as_ndarray_like()) + + async def store_chunk( + self, + chunk_indices: Iterable[int], + data: ArrayData, + /, + *, + store_empty_chunks: bool = False, + prototype: BufferPrototype | None = None, + ) -> None: + """Encode `data` as the chunk at `chunk_indices` and write it. `data` has the + chunk's full shape, as `retrieve_chunk` gives it and as zarrs takes it; for a + chunk at the array's edge, the part past the array's shape is not stored (it + reads as the fill value). The data's requirements, `store_empty_chunks` and + errors are as for `store_array_subset`.""" + indices = self._chunk_indices(chunk_indices, in_grid=True) + indexer = BlockIndexer(indices, self._metadata.shape, self._chunk_grid) + inside = self._chunk_inside(indices) + dtype = self._metadata.dtype.to_native_dtype() + if inside is None: + value = _exact_data(data, dtype, indexer.shape) + else: + full_shape, region = inside + value = _exact_data(data, dtype, full_shape)[region] + await self._set_selection( + indexer, + value, + prototype=default_buffer_prototype() if prototype is None else prototype, + config=_write_config(store_empty_chunks), + ) + + def _chunk_inside( + self, indices: tuple[int, ...] + ) -> tuple[tuple[int, ...], tuple[slice, ...]] | None: + """For a chunk that extends past the array's shape, its full shape and the + region of it inside the array; `None` for a chunk wholly inside.""" + spec = self._chunk_grid[indices] + if spec is None or not spec.is_boundary: + return None + return spec.codec_shape, tuple(slice(0, extent) for extent in spec.shape) + + def _fill_value(self) -> Any: + """The array's fill value as a scalar of its data type; a Zarr format 2 array + without one reads as the data type's default.""" + fill_value = self._metadata.fill_value + return self._metadata.dtype.default_scalar() if fill_value is None else fill_value + + async def __getitem__(self, selection: ArraySubsetSelection, /) -> ArrayResult: + """`retrieve_array_subset(selection)`.""" + return await self.retrieve_array_subset(selection) + + async def _retrieve( + self, indexer: Indexer, *, prototype: BufferPrototype, read_missing_chunks: bool + ) -> ArrayResult: + """A public read: an array of the prototype's kind, 0-d for a 0-d array. That + read goes into a 0-d buffer of the array's data type, because + `_get_selection` would return a scalar, which loses the data type (a byte order, + `StringDType`) and the prototype's kind.""" + config = _read_config(read_missing_chunks) + if indexer.shape != (): + return cast( + "ArrayResult", + await self._get_selection(indexer, prototype=prototype, config=config), + ) + out = prototype.nd_buffer.empty(shape=(), dtype=self._metadata.dtype.to_native_dtype()) + await self._get_selection(indexer, prototype=prototype, out=out, config=config) + return cast("ArrayResult", out.as_ndarray_like()) + + async def _get_selection( + self, + indexer: Indexer, + *, + prototype: BufferPrototype, + out: NDBuffer | None = None, + fields: Fields | None = None, + config: ArrayConfig, + ) -> NDArrayLikeOrScalar: + """Read through the codec pipeline with the runtime configuration `config`: a + public read's, or an `AsyncArray`'s own.""" + return await _get_selection( + self._store_path, + self._metadata, + self._codec_pipeline, + config, + self._chunk_grid, + indexer, + prototype=prototype, + out=out, + fields=fields, + ) + + async def _set_selection( + self, + indexer: Indexer, + value: npt.ArrayLike, + *, + prototype: BufferPrototype, + fields: Fields | None = None, + config: ArrayConfig, + ) -> None: + """`_write_selection`, refused while `needs_repair` is true.""" + if product(indexer.shape) > 0 and self._needs_repair: + raise MetadataRepairRequiredError( + f"Array {str(self._store_path)!r}: the stored metadata document needs a " + "repair that moves chunks; store the repaired metadata with " + "`store_metadata()` and write through the value it returns. Nothing was " + "written." + ) + await self._write_selection( + indexer, value, prototype=prototype, fields=fields, config=config + ) + + async def _write_selection( + self, + indexer: Indexer, + value: npt.ArrayLike, + *, + prototype: BufferPrototype, + fields: Fields | None = None, + config: ArrayConfig, + ) -> None: + """Write with the runtime configuration `config`, without the check against a + repair that has not been stored, for a caller that applies its own repair policy + first (`AsyncArray`).""" + await _set_selection( + self._store_path, + self._metadata, + self._codec_pipeline, + config, + self._chunk_grid, + indexer, + value, + prototype=prototype, + fields=fields, + ) + + async def _store_repair_document(self) -> None: + """Store the repair of the array's current stored document, for `AsyncArray`, + which reads the stored document again and clears the shared repair mark itself. + + The store may hold a newer document than this metadata. If that one lays out + chunks differently (another writer stored a different chunk size since), chunks + written under this metadata would be found by no reader, so it raises and + stores nothing. If it needs no repair (the array was re-saved since, possibly by + another implementation), it is left as written; if there is none, there is + nothing to repair. Storing the same repair twice is harmless; the read and the + store are not one atomic step, as with any two metadata writes that race. + """ + zarr_format = self._metadata.zarr_format + documents = await read_documents(self._store_path, ARRAY_DOCUMENTS[zarr_format]) + try: + current = parse_stored_array(documents, zarr_format, str(self._store_path)) + except ArrayNotFoundError: + pass + else: + if _chunk_layout(current) != _chunk_layout(self._metadata): + raise ValueError( + f"Array {str(self._store_path)!r}: the metadata stored has changed since " + "this array was opened; reopen the array to write to it. Nothing was stored." + ) + if current._stored_document is not None: + await upsert_metadata(self._store_path, current, documents) + + async def _resized(self, new_shape: ShapeLike, delete_outside_chunks: bool) -> AsyncZarrArrayIO: + """Store the metadata of the array resized to `new_shape`, deleting the chunks + outside it if `delete_outside_chunks`, for `AsyncArray.resize`, which clears the + shared repair mark itself. The new metadata is encoded before any chunk is + deleted: metadata that cannot be stored then fails with the store untouched.""" + resized = self.with_shape(new_shape) + documents = encode_documents(self._store_path, resized._metadata) + if delete_outside_chunks: + old_grid_shape = self._chunk_grid.grid_shape + new_grid_shape = resized._chunk_grid.grid_shape + # Chunks of the old grid outside the box it shares with the new grid. + # Zero whenever no axis loses a whole chunk, including pure growth. + n_delete = math.prod(old_grid_shape) - math.prod( + min(old, new) for old, new in zip(old_grid_shape, new_grid_shape, strict=True) + ) + if n_delete > 0: + # `None` lifts the I/O concurrency limit, but the worker pool still + # needs a bound; 1000 keeps the pool far smaller than the grid. + limit = zarr_config.get("async.concurrency") or 1000 + await concurrent_foreach( + ( + (self._store_path / self._metadata.encode_chunk_key(coords),) + for coords in _iter_chunk_coords_to_delete(old_grid_shape, new_grid_shape) + ), + _delete_chunk, + min(limit, n_delete), + ) + await store_documents(self._store_path, documents) + return resized + + +@final +@dataclass(frozen=True, slots=True, eq=False, init=False, repr=False) +class ZarrArrayIO: + """An array, as a value, read and written synchronously: each operation runs the + matching `AsyncZarrArrayIO` operation with the runner its `SyncContext` holds. + + Make one with `open`, `from_metadata` or `of`, as for `AsyncZarrArrayIO`, whose + documentation describes the value and its metadata changes. + """ + + _async_io: AsyncZarrArrayIO + _context: SyncContext + + def __init__(self) -> None: + raise TypeError( + "Make a ZarrArrayIO with ZarrArrayIO.open, ZarrArrayIO.from_metadata or ZarrArrayIO.of." + ) + + @classmethod + def _wrap(cls, async_io: AsyncZarrArrayIO, context: SyncContext) -> ZarrArrayIO: + io = object.__new__(cls) + object.__setattr__(io, "_async_io", async_io) + object.__setattr__(io, "_context", context) + return io + + def _rewrap(self, async_io: AsyncZarrArrayIO) -> ZarrArrayIO: + return ZarrArrayIO._wrap(async_io, self._context) + + def _run[T](self, coroutine: Coroutine[Any, Any, T]) -> T: + return self._context.runner.run(coroutine) + + @classmethod + def open( + cls, + store: Store, + path: str = "", + *, + zarr_format: ZarrFormat | None = None, + context: SyncContext | None = None, + ) -> ZarrArrayIO: + """See `AsyncZarrArrayIO.open`.""" + context = SyncContext() if context is None else context + opened = context.runner.run(AsyncZarrArrayIO.open(store, path, zarr_format=zarr_format)) + return cls._wrap(opened, context) + + @classmethod + def from_metadata( + cls, + metadata: ArrayMetadata | Mapping[str, JSON], + store: Store, + path: str = "", + *, + context: SyncContext | None = None, + ) -> ZarrArrayIO: + """See `AsyncZarrArrayIO.from_metadata`.""" + return cls._wrap( + AsyncZarrArrayIO.from_metadata(metadata, store, path), + SyncContext() if context is None else context, + ) + + @classmethod + def of( + cls, array: AsyncArray[Any] | Array[Any], *, context: SyncContext | None = None + ) -> ZarrArrayIO: + """See `AsyncZarrArrayIO.of`.""" + return cls._wrap(AsyncZarrArrayIO.of(array), SyncContext() if context is None else context) + + def as_async(self) -> AsyncZarrArrayIO: + """This array, read and written asynchronously.""" + return self._async_io + + def __repr__(self) -> str: + return " dict[str, JSON]: + """See `AsyncZarrArrayIO.metadata`.""" + return self._async_io.metadata + + @property + def attrs(self) -> dict[str, JSON]: + """See `AsyncZarrArrayIO.attrs`.""" + return self._async_io.attrs + + @property + def shape(self) -> tuple[int, ...]: + """See `AsyncZarrArrayIO.shape`.""" + return self._async_io.shape + + @property + def path(self) -> str: + """See `AsyncZarrArrayIO.path`.""" + return self._async_io.path + + @property + def needs_repair(self) -> bool: + """See `AsyncZarrArrayIO.needs_repair`.""" + return self._async_io.needs_repair + + def with_shape(self, shape: ShapeLike, /) -> ZarrArrayIO: + """See `AsyncZarrArrayIO.with_shape`.""" + return self._rewrap(self._async_io.with_shape(shape)) + + def with_attrs(self, attrs: Mapping[str, JSON], /) -> ZarrArrayIO: + """See `AsyncZarrArrayIO.with_attrs`.""" + return self._rewrap(self._async_io.with_attrs(attrs)) + + def store_metadata(self) -> ZarrArrayIO: + """See `AsyncZarrArrayIO.store_metadata`.""" + return self._rewrap(self._run(self._async_io.store_metadata())) + + def erase_metadata(self) -> None: + """See `AsyncZarrArrayIO.erase_metadata`.""" + self._run(self._async_io.erase_metadata()) + + def erase_chunk(self, chunk_indices: Iterable[int], /) -> None: + """See `AsyncZarrArrayIO.erase_chunk`.""" + self._run(self._async_io.erase_chunk(chunk_indices)) + + def erase_chunks(self, chunk_indices: Iterable[Iterable[int]], /) -> None: + """See `AsyncZarrArrayIO.erase_chunks`.""" + self._run(self._async_io.erase_chunks(chunk_indices)) + + def retrieve_array_subset( + self, + selection: ArraySubsetSelection, + /, + *, + read_missing_chunks: bool = True, + prototype: BufferPrototype | None = None, + ) -> ArrayResult: + """See `AsyncZarrArrayIO.retrieve_array_subset`.""" + return self._run( + self._async_io.retrieve_array_subset( + selection, read_missing_chunks=read_missing_chunks, prototype=prototype + ) + ) + + def store_array_subset( + self, + selection: ArraySubsetSelection, + data: ArrayData, + /, + *, + store_empty_chunks: bool = False, + prototype: BufferPrototype | None = None, + ) -> None: + """See `AsyncZarrArrayIO.store_array_subset`.""" + self._run( + self._async_io.store_array_subset( + selection, data, store_empty_chunks=store_empty_chunks, prototype=prototype + ) + ) + + def retrieve_chunk( + self, + chunk_indices: Iterable[int], + /, + *, + read_missing_chunks: bool = True, + prototype: BufferPrototype | None = None, + ) -> ArrayResult: + """See `AsyncZarrArrayIO.retrieve_chunk`.""" + return self._run( + self._async_io.retrieve_chunk( + chunk_indices, read_missing_chunks=read_missing_chunks, prototype=prototype + ) + ) + + def store_chunk( + self, + chunk_indices: Iterable[int], + data: ArrayData, + /, + *, + store_empty_chunks: bool = False, + prototype: BufferPrototype | None = None, + ) -> None: + """See `AsyncZarrArrayIO.store_chunk`.""" + self._run( + self._async_io.store_chunk( + chunk_indices, data, store_empty_chunks=store_empty_chunks, prototype=prototype + ) + ) + + def __getitem__(self, selection: ArraySubsetSelection, /) -> ArrayResult: + """`retrieve_array_subset(selection)`.""" + return self.retrieve_array_subset(selection) + + def __setitem__(self, selection: ArraySubsetSelection, data: ArrayData, /) -> None: + """`store_array_subset(selection, data)`.""" + self.store_array_subset(selection, data) + + # TODO: Array can be a frozen data class again once property setters (e.g. shape) are removed @dataclass(frozen=False) class Array[T_ArrayMetadata: (ArrayV2Metadata, ArrayV3Metadata)]: @@ -5948,52 +6810,14 @@ async def _resize( If True (default), chunks that fall outside the new shape will be deleted. If False, the data in those chunks will be preserved. """ - new_shape = parse_shapelike(new_shape) - if len(new_shape) != len(array.metadata.shape): - raise ValueError( - f"The new shape must have the same number of dimensions as the array. " - f"Got {len(new_shape)} dimension(s), expected {len(array.metadata.shape)}." - ) - - new_metadata = array.metadata.update_shape(new_shape) - new_chunk_grid = ChunkGrid.from_metadata(new_metadata) - - # Encode the new metadata before deleting any chunk: metadata that cannot be stored - # then fails with the store untouched. - documents = encode_documents(array.store_path, new_metadata) - - if delete_outside_chunks: - old_grid_shape = array._chunk_grid.grid_shape - new_grid_shape = new_chunk_grid.grid_shape - # Chunks of the old grid outside the box it shares with the new grid. - # Zero whenever no axis loses a whole chunk, including pure growth. - n_delete = math.prod(old_grid_shape) - math.prod( - min(old, new) for old, new in zip(old_grid_shape, new_grid_shape, strict=True) - ) - if n_delete > 0: - - async def _delete_chunk(coords: tuple[int, ...]) -> None: - await (array.store_path / array.metadata.encode_chunk_key(coords)).delete() - - # `None` lifts the I/O concurrency limit, but the worker pool still - # needs a bound; 1000 keeps the pool far smaller than the grid. - limit = zarr_config.get("async.concurrency") or 1000 - await concurrent_foreach( - ( - (coords,) - for coords in _iter_chunk_coords_to_delete(old_grid_shape, new_grid_shape) - ), - _delete_chunk, - min(limit, n_delete), - ) - - # Write new metadata - await store_documents(array.store_path, documents) + resized = await AsyncZarrArrayIO._of(array)._resized(new_shape, delete_outside_chunks) + # The mark is cleared through the method, as always, so a subclass that overrides + # it decides. array._stored_document_replaced() # Update metadata and chunk_grid (in place) - object.__setattr__(array, "metadata", new_metadata) - object.__setattr__(array, "_chunk_grid", new_chunk_grid) + object.__setattr__(array, "metadata", resized._metadata) + object.__setattr__(array, "_chunk_grid", resized._chunk_grid) async def _append( @@ -6023,37 +6847,12 @@ async def _append( The size of all dimensions other than `axis` must match between the array and `data`. """ - # ensure data is array-like - if not hasattr(data, "shape"): - data = np.asanyarray(data) - - self_shape_preserved = tuple(s for i, s in enumerate(array.shape) if i != axis) - data_shape_preserved = tuple(s for i, s in enumerate(data.shape) if i != axis) - if self_shape_preserved != data_shape_preserved: - raise ValueError( - f"shape of data to append is not compatible with the array. " - f"The shape of the data is ({data_shape_preserved})" - f"and the shape of the array is ({self_shape_preserved})." - "All dimensions must match except for the dimension being " - "appended." - ) - # remember old shape - old_shape = array.shape - - # determine new shape - new_shape = tuple( - array.shape[i] if i != axis else array.shape[i] + data.shape[i] - for i in range(len(array.shape)) - ) + data, new_shape, append_selection = _appended(array.shape, data, axis) # resize await _resize(array, new_shape) # store data - append_selection = tuple( - slice(None) if i != axis else slice(old_shape[i], new_shape[i]) - for i in range(len(array.shape)) - ) await array.setitem(append_selection, data) return new_shape diff --git a/src/zarr/core/sync.py b/src/zarr/core/sync.py index 16b1c577ff..c91e6c3094 100644 --- a/src/zarr/core/sync.py +++ b/src/zarr/core/sync.py @@ -6,13 +6,13 @@ import os import threading from concurrent.futures import ThreadPoolExecutor, wait -from typing import TYPE_CHECKING +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Protocol from zarr.core.config import config if TYPE_CHECKING: from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine - from typing import Any logger = logging.getLogger(__name__) @@ -222,3 +222,29 @@ async def _with_semaphore[T]( return await func() async with semaphore: return await func() + + +class Runner(Protocol): + """Runs coroutines to completion, as `asyncio.Runner` does: `run` returns each + coroutine's result, or raises its exception.""" + + def run[T](self, coroutine: Coroutine[Any, Any, T], /) -> T: ... + + +class _ZarrLoopRunner: + """Runs coroutines on zarr's own event loop, on zarr's IO thread (see `sync`).""" + + def run[T](self, coroutine: Coroutine[Any, Any, T], /) -> T: + return sync(coroutine) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class SyncContext: + """How a synchronous API runs the coroutines it is built on.""" + + runner: Runner = field(default_factory=_ZarrLoopRunner) + """Runs each coroutine to completion for the thread that called the synchronous API, + which waits for it. The default runs it on zarr's own event loop, on zarr's IO + thread, with no timeout; an `asyncio.Runner()` runs it on the calling thread. A + store whose async clients belong to one event loop (as fsspec's async filesystems + do) needs every operation on it run on that loop.""" diff --git a/src/zarr/errors.py b/src/zarr/errors.py index 803faf4884..34ad9ddb93 100644 --- a/src/zarr/errors.py +++ b/src/zarr/errors.py @@ -9,6 +9,7 @@ "ContainsGroupError", "DataTypeValidationError", "GroupNotFoundError", + "MetadataRepairRequiredError", "MetadataValidationError", "NegativeStepError", "NodeTypeValidationError", @@ -97,6 +98,14 @@ class MetadataValidationError(BaseZarrError): _msg = "Invalid value for '{}'. Expected '{}'. Got '{}'." +class MetadataRepairRequiredError(BaseZarrError): + """ + Raised when chunks would be stored under metadata repaired from a stored document in + a way that moves chunks, before the repaired metadata itself is stored: no reader of + the stored document would find them. + """ + + class UnknownCodecError(BaseZarrError): """ Raised when an unknown codec was used. diff --git a/tests/test_array_io.py b/tests/test_array_io.py new file mode 100644 index 0000000000..5aaa9b52e0 --- /dev/null +++ b/tests/test_array_io.py @@ -0,0 +1,697 @@ +"""`AsyncZarrArrayIO` and `ZarrArrayIO`: an array as a value, read and written explicitly.""" + +from __future__ import annotations + +import asyncio +import json +from types import MappingProxyType +from typing import TYPE_CHECKING, Any, Literal, cast + +import numcodecs +import numpy as np +import pytest +from typing_extensions import CapsuleType + +import zarr +from zarr.abc.array_io import ArrayIO, ArrayResult, AsyncArrayIO, SupportsDLPack +from zarr.codecs.numcodecs import Delta as NumcodecsDelta +from zarr.core.array import AsyncArray, AsyncZarrArrayIO, ZarrArrayIO +from zarr.core.sync import SyncContext, sync +from zarr.errors import ChunkNotFoundError, MetadataRepairRequiredError, ZarrUserWarning +from zarr.storage import LocalStore, MemoryStore, StorePath + +if TYPE_CHECKING: + from collections.abc import Coroutine, Iterator + from pathlib import Path + + +class _CountingRunner: + """Runs coroutines through `runner`, or zarr's `sync` without one, counting them.""" + + def __init__(self, runner: asyncio.Runner | None = None) -> None: + self.runner = runner + self.runs = 0 + + def run[T](self, coroutine: Coroutine[Any, Any, T], /) -> T: + self.runs += 1 + return sync(coroutine) if self.runner is None else self.runner.run(coroutine) + + +@pytest.fixture +def calling_thread_runner() -> Iterator[asyncio.Runner]: + """An `asyncio.Runner`, which runs coroutines on the calling thread.""" + with asyncio.Runner() as runner: + yield runner + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("made_by", ["open", "from_metadata", "of", "of-async"]) +@pytest.mark.parametrize("on_calling_thread", [False, True]) +def test_array_io_reads_writes_and_changes_metadata( + zarr_format: Literal[2, 3], + made_by: str, + on_calling_thread: bool, + calling_thread_runner: asyncio.Runner, +) -> None: + """An `ZarrArrayIO` reads and writes through the runner its context holds. Metadata + changes return new values and store nothing until `store_metadata`; the values they + were made from, and the array a value was made from, are left as they were. + `with_attrs` replaces the attributes, and no attribute dict a value takes in or hands + out reaches another value or the array.""" + store = MemoryStore() + array = zarr.create_array( + store, + name="a", + shape=(4,), + chunks=(2,), + dtype="int64", + zarr_format=zarr_format, + attributes={"old": 0, "n": [1]}, + ) + runner = _CountingRunner(calling_thread_runner if on_calling_thread else None) + context = SyncContext(runner=runner) + if made_by == "open": + io = ZarrArrayIO.open(store, "a", context=context) + elif made_by == "from_metadata": + io = ZarrArrayIO.from_metadata(array.metadata, store, "a", context=context) + elif made_by == "of": + io = ZarrArrayIO.of(array, context=context) + else: + io = ZarrArrayIO.of(array.async_array, context=context) + array.attrs["late"] = 1 + cast("list[int]", io.attrs["n"]).append(2) + cast("list[int]", cast("dict[str, Any]", io.metadata["attributes"])["n"]).append(3) + attrs = {"a": [1]} + + io[:] = np.arange(4) + io.store_chunk([1], np.asarray([7, 8])) + grown = io.with_shape((6,)) + stored_before = zarr.open_array(store, path="a").shape + labeled = grown.store_metadata().with_attrs(attrs).store_metadata() + attrs["a"].append(2) + labeled.erase_chunk([0]) + + np.testing.assert_array_equal(labeled[:], [0, 0, 7, 8, 0, 0]) + np.testing.assert_array_equal(labeled.retrieve_chunk([1]), [7, 8]) + assert stored_before == (4,) + assert (io.shape, io.attrs, labeled.attrs) == ((4,), {"old": 0, "n": [1]}, {"a": [1]}) + reopened = zarr.open_array(store, path="a") + assert (reopened.shape, dict(reopened.attrs)) == ((6,), {"a": [1]}) + # One run for each read and write, and for opening. + assert runner.runs == 7 + (made_by == "open") + + +async def test_async_array_io_reads_and_writes() -> None: + """`AsyncZarrArrayIO` opens, reads and writes an array asynchronously, and `as_sync` and + `as_async` move between it and `ZarrArrayIO`.""" + store = MemoryStore() + zarr.create_array(store, name="a", shape=(4,), chunks=(2,), dtype="int64") + io = await AsyncZarrArrayIO.open(store, "a") + + await io.store_array_subset(slice(None), np.arange(4)) + + np.testing.assert_array_equal(await io[1:3], [1, 2]) + np.testing.assert_array_equal(await io.retrieve_chunk([1]), [2, 3]) + assert io.as_sync(context=SyncContext()).as_async() is io + assert repr(io.as_sync(context=SyncContext())) == repr(io).replace( + "" + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_store_metadata_stores_the_repair(tmp_path: Path, zarr_format: Literal[2, 3]) -> None: + """A value opened from a stored document whose repair moves chunks needs a repair; + storing its metadata stores the repair, and the value returned writes chunks.""" + path = tmp_path / "legacy.zarr" + _legacy_array(path, zarr_format) + with pytest.warns(ZarrUserWarning, match="is read as"): + io = ZarrArrayIO.open(LocalStore(path)) + + repaired = io.store_metadata() + repaired[:] = np.asarray([1, 2, 3], dtype="int16") + + assert (io.needs_repair, repaired.needs_repair) == (True, False) + assert _stored_chunks(path, zarr_format) == [1] + np.testing.assert_array_equal(zarr.open_array(path)[:], [1, 2, 3]) + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_chunks_are_refused_until_the_repair_is_stored( + tmp_path: Path, zarr_format: Literal[2, 3] +) -> None: + """Storing chunks under metadata whose repair moves chunks, or under a value derived + from it, raises and writes nothing until the repaired metadata is stored.""" + path = tmp_path / "legacy.zarr" + _legacy_array(path, zarr_format) + with pytest.warns(ZarrUserWarning, match="is read as"): + io = ZarrArrayIO.open(LocalStore(path)).with_attrs({"a": 1}) + before = {p: p.read_bytes() for p in path.rglob("*") if p.is_file()} + + with pytest.raises(MetadataRepairRequiredError, match=r"store_metadata\(\)"): + io[:] = np.asarray([1, 2, 3], dtype="int16") + + assert {p: p.read_bytes() for p in path.rglob("*") if p.is_file()} == before + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("separator", [".", "/"]) +def test_erase_deletes_chunks_and_metadata(zarr_format: Literal[2, 3], separator: str) -> None: + """`erase_chunk` and `erase_chunks` delete chunks, inside the chunk grid or left + outside a smaller shape, and `erase_metadata` deletes the array's documents.""" + store = MemoryStore() + array = zarr.create_array( + store, + name="a", + shape=(6,), + chunks=(2,), + dtype="int64", + zarr_format=zarr_format, + chunk_key_encoding={ + "name": "v2" if zarr_format == 2 else "default", + "separator": separator, + }, + ) + array[:] = np.arange(1, 7) + io = ZarrArrayIO.of(array).with_shape((2,)).store_metadata() + + io.erase_chunks([[1], [2]]) + regrown = io.with_shape((6,)) + io.erase_chunk([0]) + + np.testing.assert_array_equal(regrown[:], [0, 0, 0, 0, 0, 0]) + io.erase_metadata() + # The root group's documents stay. + assert [key for key in sync(_keys(store)) if key.startswith("a/")] == [] + + +def test_a_value_keeps_attributes_changed_where_it_came_from() -> None: + """Nested attribute values changed through the array a value was taken from, or in + the document a value was made from, do not reach the value.""" + store = MemoryStore() + array = zarr.create_array(store, name="a", shape=(2,), dtype="int8", attributes={"n": [1]}) + document = array.metadata.to_dict() + taken = ZarrArrayIO.of(array) + made = ZarrArrayIO.from_metadata(MappingProxyType(document), store, "a") + + cast("list[int]", array.attrs["n"]).append(2) + cast("list[int]", cast("dict[str, Any]", document["attributes"])["n"]).append(3) + + assert (taken.attrs, made.attrs) == ({"n": [1]}, {"n": [1]}) + + +def test_values_not_taken_from_an_array_ignore_the_global_configuration() -> None: + """`open` and `from_metadata` use fixed defaults, not the global configuration: an + all-fill-value chunk is not stored, whatever `array.write_empty_chunks` says.""" + store = MemoryStore() + array = zarr.create_array(store, name="a", shape=(4,), chunks=(2,), dtype="int8") + with zarr.config.set({"array.write_empty_chunks": True}): + opened = ZarrArrayIO.open(store, "a") + made = ZarrArrayIO.from_metadata(array.metadata, store, "a") + opened[0:2] = np.zeros(2, dtype="int8") + made[2:4] = np.zeros(2, dtype="int8") + + assert [key for key in sync(_keys(store)) if key.startswith("a/c")] == [] + + +def test_runtime_choices_are_made_per_call() -> None: + """Whether an all-fill-value chunk is stored, and whether a missing chunk reads as + the fill value, are chosen by each call, whatever the array the value was taken + from was configured with; data reads in C order.""" + store = MemoryStore() + array = zarr.create_array( + store, + name="a", + shape=(2, 4), + chunks=(2, 2), + dtype="int8", + config={"write_empty_chunks": True, "read_missing_chunks": False, "order": "F"}, + ) + io = ZarrArrayIO.of(array) + + zeros = np.zeros((2, 2), dtype="int8") + io[:, 0:2] = zeros + io.store_array_subset((slice(None), slice(2, 4)), zeros, store_empty_chunks=True) + stored = sorted(key for key in sync(_keys(store)) if key.startswith("a/c")) + io.store_chunk([0, 0], zeros, store_empty_chunks=True) + io.store_chunk([0, 1], zeros) + restored = sorted(key for key in sync(_keys(store)) if key.startswith("a/c")) + + assert (stored, restored) == (["a/c/0/1"], ["a/c/0/0"]) + assert cast("np.ndarray[Any, Any]", io[:]).flags.c_contiguous + np.testing.assert_array_equal(io.retrieve_chunk([0, 1]), np.zeros((2, 2))) + with pytest.raises(ChunkNotFoundError): + io.retrieve_array_subset(slice(None), read_missing_chunks=False) + with pytest.raises(ChunkNotFoundError): + io.retrieve_chunk([0, 1], read_missing_chunks=False) + + +class _DLPackOnly: + """An array that exports only through DLPack, as a PyTorch or JAX tensor can.""" + + def __init__(self, array: np.ndarray[Any, Any]) -> None: + self._array = array + + 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: + # NumPy 2.0 (the oldest NumPy supported) takes none of the keywords. + return self._array.__dlpack__() + + def __dlpack_device__(self) -> tuple[int, int]: + return self._array.__dlpack_device__() + + +def test_zarr_array_io_implements_the_interface() -> None: + """`ZarrArrayIO` and `AsyncZarrArrayIO` are `ArrayIO` and `AsyncArrayIO`: they + write data that exports only through DLPack, and read `ArrayResult`s with the + subset's shape that export numeric data through DLPack.""" + array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") + io: ArrayIO = ZarrArrayIO.of(array) + async_io: AsyncArrayIO = AsyncZarrArrayIO.of(array) + + io[:] = _DLPackOnly(np.arange(4)) + point = io[1:2] + + assert isinstance(io, ArrayIO) + assert isinstance(async_io, AsyncArrayIO) + assert isinstance(point, ArrayResult) + assert np.asarray(point).shape == (1,) + numeric = io[:] + assert isinstance(numeric, SupportsDLPack) + np.testing.assert_array_equal(np.from_dlpack(numeric), [0, 1, 2, 3]) + + +class _ArrayWithoutDLPackExport: + """Data with `__array__` whose DLPack export fails, as a pyarrow array with nulls + or strings does; it has no `shape`.""" + + def __init__(self, values: list[float]) -> None: + self._values = values + + def __array__(self, dtype: Any = None, copy: bool | None = None) -> np.ndarray[Any, Any]: + return np.asarray(self._values, dtype=dtype) + + def __dlpack__(self, **kwargs: object) -> CapsuleType: + raise BufferError("cannot export through DLPack") + + def __dlpack_device__(self) -> tuple[int, int]: + return (1, 0) + + +class _DLPackOnlyOnDevice: + """Data that exports only through DLPack, from a device other than the host.""" + + def __dlpack__(self, **kwargs: object) -> CapsuleType: + raise AssertionError("not exported") + + def __dlpack_device__(self) -> tuple[int, int]: + return (2, 0) + + +@pytest.mark.parametrize( + ("dtype", "zarr_format", "value"), + [ + (str, 3, "ab\x00"), + (str, 2, "ab\x00"), + (">i4", 2, 7), + ("int64", 3, 7), + ], +) +def test_zero_dimensional_reads_keep_the_data_type( + dtype: str | type, zarr_format: Literal[2, 3], value: object +) -> None: + """A 0-d array reads as a 0-d array of its data type, with the value intact (a + string keeps its trailing NULs); writes take host data with `__array__` through it, + even when its DLPack export fails.""" + array = zarr.create_array(MemoryStore(), shape=(), dtype=dtype, zarr_format=zarr_format) + io = ZarrArrayIO.of(array) + io[...] = np.asarray(value, dtype=array.dtype) + floats = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(2,), dtype="float64")) + floats[:] = _ArrayWithoutDLPackExport([1.0, np.nan]) + + point = np.asarray(io[...]) + + assert point.shape == () + assert point.dtype == array.dtype + assert point.item() == value + np.testing.assert_array_equal(np.asarray(floats[:]), [1.0, np.nan]) + + +def test_store_array_subset_refuses_dlpack_only_data_off_the_host() -> None: + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(2,), dtype="float64")) + with pytest.raises(TypeError, match=r"must be in host memory; it is on DLPack device \(2, 0\)"): + io[:] = cast("Any", _DLPackOnlyOnDevice()) + + +@pytest.mark.parametrize( + ("region", "data"), + [ + (slice(0, 2), np.asarray([[5, 6]])), + (slice(0, 2), np.arange(3)), + (slice(0, 2), np.asarray(5)), + (slice(0, 1), np.asarray(5)), + ], + ids=["leading-axis", "longer", "scalar", "one-element-scalar"], +) +def test_store_array_subset_refuses_data_of_another_shape(region: slice, data: Any) -> None: + """Data is not broadcast, and leading axes of length 1 are not dropped.""" + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + with pytest.raises(ValueError, match="does not match the region's shape"): + io[region] = data + + +def test_store_chunk_refuses_data_of_only_the_inside_of_an_edge_chunk() -> None: + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(5,), chunks=(2,), dtype="int64")) + with pytest.raises(ValueError, match="does not match the region's shape"): + io.store_chunk([2], np.asarray([1])) + + +@pytest.mark.parametrize( + ("layout", "chunk", "full_shape"), + [ + ({"chunks": (2, 2)}, (2, 1), (2, 2)), + ({"chunks": (2, 2)}, (1, 0), (2, 2)), + ({"shards": (4, 4), "chunks": (2, 2)}, (1, 0), (4, 4)), + ( + { + "chunks": (2, 2), + "filters": [{"name": "transpose", "configuration": {"order": [1, 0]}}], + }, + (2, 1), + (2, 2), + ), + ], + ids=["edge", "inside", "sharded-edge", "transposed-edge"], +) +def test_chunks_are_read_and_written_in_their_full_shape( + layout: dict[str, Any], chunk: tuple[int, int], full_shape: tuple[int, int] +) -> None: + """A chunk has its full shape, as zarrs gives it: past the array's edge it reads as + the fill value, and data written there is not stored.""" + io = ZarrArrayIO.of( + zarr.create_array(MemoryStore(), shape=(5, 3), dtype="int64", fill_value=-1, **layout) + ) + io[...] = np.arange(15).reshape(5, 3) + region = tuple( + slice(i * n, min((i + 1) * n, extent)) + for i, n, extent in zip(chunk, full_shape, (5, 3), strict=True) + ) + expected = np.full(full_shape, -1) + inside = tuple(slice(0, s.stop - s.start) for s in region) + expected[inside] = np.arange(15).reshape(5, 3)[region] + + read = np.asarray(io.retrieve_chunk(chunk)) + io.store_chunk(chunk, np.full(full_shape, 7)) + + np.testing.assert_array_equal(read, expected) + np.testing.assert_array_equal(np.asarray(io[region]), np.full(expected[inside].shape, 7)) + expected[inside] = 7 + np.testing.assert_array_equal(np.asarray(io.retrieve_chunk(chunk)), expected) + + +@pytest.mark.parametrize( + "data", + [[1, 2], (1, 2), 1, b"12", bytearray(b"12"), memoryview(np.arange(2))], + ids=["list", "tuple", "int", "bytes", "bytearray", "memoryview"], +) +def test_store_array_subset_refuses_data_that_is_not_a_dlpack_array(data: Any) -> None: + """Only arrays are written: what a list, a scalar or a byte buffer means differs + between implementations (`b"12"` is one value to NumPy and two bytes to zarrs).""" + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(2,), dtype="uint8")) + with pytest.raises(TypeError, match="must be an array that exports through DLPack"): + io[:] = data + with pytest.raises(TypeError, match="must be an array that exports through DLPack"): + io.store_chunk([0], data) + + +@pytest.mark.parametrize( + ("dtype", "zarr_format", "data"), + [ + ("int64", 3, np.asarray([1.0, 2.0])), + ("int64", 3, np.asarray([1, 2], dtype="int32")), + ("uint8", 3, np.asarray([1, 300])), + (">i4", 2, np.asarray([1, 2], dtype=">i8")), + (str, 3, np.asarray(["a", "b"])), + ], +) +def test_store_array_subset_refuses_data_of_another_data_type( + dtype: Any, zarr_format: Literal[2, 3], data: Any +) -> None: + """Data is not cast, not even when the cast is safe.""" + io = ZarrArrayIO.of( + zarr.create_array(MemoryStore(), shape=(2,), dtype=dtype, zarr_format=zarr_format) + ) + with pytest.raises(TypeError, match="does not match the array's data type"): + io[:] = data + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("made_by", ["of", "open"]) +@pytest.mark.parametrize( + ("array_dtype", "data", "delta"), + [ + (">i4", np.asarray([1, 2], dtype="i4", np.asarray([1, 2], dtype=">i4"), False), + (">f8", np.asarray([1.5, 2.5], dtype="U2", np.asarray(["ab", "c"], dtype="i4"), ("y", "f8")]), + False, + ), + ], +) +def test_store_array_subset_writes_data_in_either_byte_order( + zarr_format: Literal[2, 3], made_by: str, array_dtype: Any, data: Any, delta: bool +) -> None: + """Byte order is not part of the data type, however the value was made: data in + either order writes the same values, through filters that read the data's bytes + as the array's data type (numcodecs' `Delta`) too, and what one value reads + another writes.""" + store = MemoryStore() + filters: Any = "auto" + if delta: + filters = ( + [numcodecs.Delta(dtype=array_dtype)] + if zarr_format == 2 + else [NumcodecsDelta(dtype=array_dtype)] + ) + array = zarr.create_array( + store, shape=(2,), dtype=array_dtype, zarr_format=zarr_format, filters=filters + ) + io = ZarrArrayIO.of(array) if made_by == "of" else ZarrArrayIO.open(store) + + io[:] = data + ZarrArrayIO.open(store)[:] = np.asarray(ZarrArrayIO.of(array)[:]) + + np.testing.assert_array_equal(np.asarray(io[:]), data) + np.testing.assert_array_equal(array[:], data) + + +@pytest.mark.parametrize( + ("dtype", "data"), + [ + ([("x", "i4"), ("y", "f8")], [(1, 2.0), (3, 4.0), (5, 6.0), (7, 8.0)]), + ("uint8", [0, 1, 2, 3]), + ("bool", [False, True, True, False]), + ("float32", [1.5, 0.0, -2.0, 3.0]), + (" None: + """An array of the array's own data type is written as `Array` writes it, data types + DLPack cannot carry (records, strings) included, across chunks.""" + io_store, array_store = MemoryStore(), MemoryStore() + io = ZarrArrayIO.of(zarr.create_array(io_store, shape=(4,), chunks=(2,), dtype=dtype)) + array = zarr.create_array(array_store, shape=(4,), chunks=(2,), dtype=dtype) + + io[:] = np.asarray(data, dtype=array.dtype) + io[1:3] = np.asarray(data[:2], dtype=array.dtype) + array[:] = data + array[1:3] = data[:2] + + np.testing.assert_array_equal(io[:], array[:]) + + +@pytest.mark.parametrize( + "selection", [1, np.int64(1), True, (slice(None), 0), None, [0], ((slice(None),),)] +) +def test_selections_refuse_anything_but_slices_and_ellipsis(selection: Any) -> None: + """Integers are not selections, for reads or writes: implementations differ on + whether one keeps its axis.""" + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4, 3), dtype="int64")) + with pytest.raises(TypeError, match="takes slices and Ellipsis"): + io.retrieve_array_subset(selection) + with pytest.raises(TypeError, match="takes slices and Ellipsis"): + io.store_array_subset(selection, np.asarray(0)) + + +@pytest.mark.parametrize("step", [2, 0, -1]) +def test_selections_refuse_slices_with_a_step(step: int) -> None: + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), dtype="int64")) + with pytest.raises(ValueError, match="step of 1"): + io.retrieve_array_subset(slice(0, 4, step)) + with pytest.raises(ValueError, match="step of 1"): + io.store_array_subset(slice(0, 4, step), np.asarray(0)) + + +@pytest.mark.parametrize( + "selection", + [ + (slice(-2, None),), + (slice(None, -1), slice(1, 2)), + slice(2, 100), + slice(3, 1), + (Ellipsis, slice(-1, None)), + slice(None, None, 1), + (), + ], +) +def test_slice_bounds_mean_what_they_mean_to_numpy(selection: Any) -> None: + """Negative bounds count from the end, bounds past the end are clipped, a reversed + slice is empty and missing trailing entries select whole dimensions, for reads and + writes alike.""" + expected = np.arange(12).reshape(4, 3) + io = ZarrArrayIO.of( + zarr.create_array(MemoryStore(), shape=(4, 3), chunks=(2, 2), dtype="int64") + ) + io[...] = expected + + np.testing.assert_array_equal(io[selection], expected[selection]) + io[selection] = np.full_like(expected[selection], -1) + expected[selection] = -1 + np.testing.assert_array_equal(io[...], expected) + + +def test_chunk_indices_must_be_non_negative() -> None: + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + with pytest.raises(ValueError, match="non-negative"): + io.erase_chunk([-1]) + + +def test_chunk_indices_need_one_index_for_each_dimension() -> None: + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + with pytest.raises(ValueError, match="one index for each"): + io.erase_chunk([]) + + +def test_chunk_indices_are_not_booleans() -> None: + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + with pytest.raises(TypeError, match="not booleans"): + io.retrieve_chunk([True]) + + +def test_chunk_indices_may_be_any_iterable() -> None: + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + io.store_chunk((index for index in (1,)), np.asarray([7, 8])) + np.testing.assert_array_equal(io.retrieve_chunk(iter([1])), [7, 8]) + + +def test_chunk_reads_need_indices_inside_the_chunk_grid() -> None: + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + with pytest.raises(IndexError, match="outside the chunk grid"): + io.retrieve_chunk([2]) + + +def test_array_io_is_made_only_by_its_constructors() -> None: + with pytest.raises(TypeError, match="AsyncZarrArrayIO.open"): + AsyncZarrArrayIO() + with pytest.raises(TypeError, match="ZarrArrayIO.open"): + ZarrArrayIO() + + +def test_with_shape_rejects_another_number_of_dimensions() -> None: + array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") + with pytest.raises(ValueError, match="same number of dimensions"): + AsyncZarrArrayIO.of(array).with_shape((4, 4)) + + +class _HookedAsyncArray(AsyncArray[Any]): + """An `AsyncArray` subclass that records its repair hooks and stores no repair.""" + + async def _store_repaired_document(self) -> None: + vars(self).setdefault("_calls", []).append("repair") + + def _stored_document_replaced(self) -> None: + vars(self).setdefault("_calls", []).append("replaced") + super()._stored_document_replaced() + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_async_array_goes_through_its_repair_hooks( + tmp_path: Path, zarr_format: Literal[2, 3] +) -> None: + """`AsyncArray` stores the repair and records it through its own methods, so a + subclass that overrides them decides: one that stores no repair writes its chunks, + and its resize goes through `_stored_document_replaced`.""" + path = tmp_path / "legacy.zarr" + _legacy_array(path, zarr_format) + with pytest.warns(ZarrUserWarning, match="is read as"): + opened = zarr.open_array(path, mode="r+").async_array + hooked = _HookedAsyncArray(opened.metadata, opened.store_path, opened.config) + + zarr.Array(hooked)[:] = [1, 2, 3] + zarr.Array(hooked).resize((4,)) + + assert vars(hooked)["_calls"] == ["repair", "replaced"] + assert hooked.shape == (4,) + + +class _KeepsMarkAsyncArray(AsyncArray[Any]): + """An `AsyncArray` subclass whose `_stored_document_replaced` keeps the mark.""" + + def _stored_document_replaced(self) -> None: + vars(self).setdefault("_calls", []).append("replaced") + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_async_array_clears_the_repair_mark_through_its_hook( + tmp_path: Path, zarr_format: Literal[2, 3] +) -> None: + """`AsyncArray` clears the mark of a stored repair only through its own + `_stored_document_replaced`: a subclass that keeps it stores the repair again + before its next chunk write.""" + path = tmp_path / "legacy.zarr" + _legacy_array(path, zarr_format) + with pytest.warns(ZarrUserWarning, match="is read as"): + opened = zarr.open_array(path, mode="r+").async_array + keeps = _KeepsMarkAsyncArray(opened.metadata, opened.store_path, opened.config) + + zarr.Array(keeps)[:] = [1, 2, 3] + zarr.Array(keeps)[:] = [4, 5, 6] + + assert vars(keeps)["_calls"] == ["replaced", "replaced"] + assert keeps.metadata._stored_document is not None + + +async def _keys(store: MemoryStore) -> list[str]: + return [key async for key in store.list()] + + +def _stored_chunks(path: Path, zarr_format: Literal[2, 3]) -> Any: + if zarr_format == 2: + return json.loads((path / ".zarray").read_text())["chunks"] + return json.loads((path / "zarr.json").read_text())["chunk_grid"]["configuration"][ + "chunk_shape" + ] + + +def _legacy_array(path: Path, zarr_format: Literal[2, 3]) -> None: + """Store an array of shape (3,) whose stored chunk shape is `[0]`.""" + zarr.create_array(store=path, shape=(3,), chunks=(3,), dtype="int16", zarr_format=zarr_format) + document_path = path / (".zarray" if zarr_format == 2 else "zarr.json") + document = json.loads(document_path.read_text()) + if zarr_format == 2: + document["chunks"] = [0] + else: + document["chunk_grid"]["configuration"]["chunk_shape"] = [0] + document_path.write_text(json.dumps(document)) diff --git a/tests/test_array_io_zarrista.py b/tests/test_array_io_zarrista.py new file mode 100644 index 0000000000..ba82d91dcf --- /dev/null +++ b/tests/test_array_io_zarrista.py @@ -0,0 +1,241 @@ +"""`ZarrArrayIO` against zarrista, a zarrs-based implementation of the same interface. + +The same reads and writes on the same stored array must give bit-identical values, +store the same chunk keys and chunks each can read, and refuse the same data. It +covers subset and chunk reads and writes, `store_empty_chunks` and `erase_chunk`; +the metadata members differ between the two (see the PR's table) and are not +compared. zarrista's `store_chunk` takes `ArrayBytes` and its chunk indices are +lists, so the test translates those two. +""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +from zarr.core.array import ZarrArrayIO +from zarr.storage import LocalStore + +if TYPE_CHECKING: + from pathlib import Path + +zarrista = pytest.importorskip("zarrista") +if np.lib.NumpyVersion(np.__version__) < "2.1.0": + pytest.skip("zarrista exports through DLPack 1.0, from NumPy 2.1", allow_module_level=True) + +_SHAPE = (5, 3) +_BYTES = {"name": "bytes", "configuration": {"endian": "little"}} +_LAYOUTS: dict[str, tuple[list[int], list[dict[str, Any]]]] = { + "regular": ([2, 2], [_BYTES]), + "big-endian": ([2, 2], [{"name": "bytes", "configuration": {"endian": "big"}}]), + "transposed": ( + [2, 2], + [{"name": "transpose", "configuration": {"order": [1, 0]}}, _BYTES], + ), + "sharded": ( + [4, 4], + [ + { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": [2, 2], + "codecs": [_BYTES], + "index_codecs": [_BYTES, {"name": "crc32c"}], + "index_location": "end", + }, + } + ], + ), +} +_DATA_TYPES = [ + ("int8", -1), + ("uint16", 0), + ("int32", 7), + ("int64", 0), + ("float32", 0.5), + ("float64", 0.0), + ("bool", False), +] + + +class _Zarrista: + """A zarrista array with zarr-python's spelling of `store_chunk` and chunk indices.""" + + def __init__(self, array: Any) -> None: + self._array = array + + def __getitem__(self, selection: Any) -> Any: + return self._array[selection] + + def __setitem__(self, selection: Any, data: Any) -> None: + self._array[selection] = data + + def store_array_subset(self, selection: Any, data: Any, *, store_empty_chunks: bool) -> None: + self._array.store_array_subset(selection, data, store_empty_chunks=store_empty_chunks) + + def retrieve_chunk(self, indices: tuple[int, ...]) -> Any: + return self._array.retrieve_chunk(list(indices)) + + def store_chunk( + self, + indices: tuple[int, ...], + data: np.ndarray[Any, Any], + *, + store_empty_chunks: bool = False, + ) -> None: + self._array.store_chunk( + list(indices), + zarrista.ArrayBytes(data.tobytes()), + store_empty_chunks=store_empty_chunks, + ) + + def erase_chunk(self, indices: tuple[int, ...]) -> None: + self._array.erase_chunk(list(indices)) + + +def _metadata(dtype: str, fill_value: Any, layout: str) -> dict[str, Any]: + chunk_shape, codecs = _LAYOUTS[layout] + return { + "zarr_format": 3, + "node_type": "array", + "shape": list(_SHAPE), + "data_type": dtype, + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": chunk_shape}}, + "chunk_key_encoding": {"name": "default", "configuration": {"separator": "/"}}, + "fill_value": fill_value, + "codecs": codecs, + "attributes": {}, + } + + +def _ours(root: Path) -> ZarrArrayIO: + return ZarrArrayIO.open(LocalStore(root), "a") + + +def _theirs(root: Path) -> _Zarrista: + return _Zarrista(zarrista.Array.open(zarrista.store.FilesystemStore(str(root)), "/a")) + + +def _open_both(tmp_path: Path, metadata: dict[str, Any]) -> tuple[Any, Any, Path, Path]: + roots = (tmp_path / "zarr-python", tmp_path / "zarrista") + for root in roots: + (root / "a").mkdir(parents=True) + (root / "a" / "zarr.json").write_text(json.dumps(metadata)) + return _ours(roots[0]), _theirs(roots[1]), *roots + + +def _chunk_keys(root: Path) -> list[str]: + return sorted( + str(path.relative_to(root)) + for path in root.rglob("*") + if path.is_file() and path.name != "zarr.json" + ) + + +def _values(rng: np.random.Generator, dtype: str, shape: tuple[int, ...]) -> np.ndarray[Any, Any]: + if dtype == "bool": + return rng.integers(0, 2, size=shape).astype(bool) + info = np.iinfo(dtype) if np.dtype(dtype).kind in "iu" else None + if info is None: + return rng.normal(size=shape).astype(dtype) + return rng.integers(info.min, info.max, size=shape, dtype=dtype, endpoint=True) + + +def _assert_bits_equal(first: Any, second: Any) -> None: + """Equal data types, shapes and bytes: `-0.0` is not `0.0`, nor one NaN another.""" + first, second = np.ascontiguousarray(first), np.ascontiguousarray(second) + assert (first.dtype, first.shape) == (second.dtype, second.shape) + assert first.tobytes() == second.tobytes() + + +def _assert_same(ours: Any, theirs: Any, roots: tuple[Path, Path], grid: tuple[int, ...]) -> None: + """Both read the same values, subsets and chunks from their own stores, each reads + the other's store the same way, and both stored the same chunk keys.""" + readers = [ours, theirs, _theirs(roots[0]), _ours(roots[1])] + for selection in [..., (slice(1, 3), slice(-2, None)), (slice(3, 100),), (slice(2, 2),), ()]: + expected = np.asarray(ours[selection]) + for reader in readers[1:]: + _assert_bits_equal(expected, np.asarray(reader[selection])) + for indices in np.ndindex(*grid): + expected = np.asarray(ours.retrieve_chunk(indices)) + for reader in readers[1:]: + _assert_bits_equal(expected, np.asarray(reader.retrieve_chunk(indices))) + assert _chunk_keys(roots[0]) == _chunk_keys(roots[1]) + + +@pytest.mark.parametrize("layout", list(_LAYOUTS)) +@pytest.mark.parametrize(("dtype", "fill_value"), _DATA_TYPES) +def test_writes_and_reads_match_zarrista( + tmp_path: Path, layout: str, dtype: str, fill_value: Any +) -> None: + """After each write (whole array, partial, clipped and empty subsets, a full edge + chunk, all-fill chunks with and without `store_empty_chunks`, an erase), both read + the same values, subsets and chunks, read each other's stores, and store the same + chunk keys.""" + ours, theirs, *roots = _open_both(tmp_path, _metadata(dtype, fill_value, layout)) + chunk_shape = tuple(_LAYOUTS[layout][0]) + grid = tuple(-(-extent // size) for extent, size in zip(_SHAPE, chunk_shape, strict=True)) + edge = tuple(n - 1 for n in grid) + edge_inside = tuple( + extent - index * size for extent, index, size in zip(_SHAPE, edge, chunk_shape, strict=True) + ) + fill = np.full((), fill_value, dtype=dtype) + rng = np.random.default_rng(0) + + def write_subset(selection: Any, shape: tuple[int, ...]) -> None: + data = _values(rng, dtype, shape) + ours[selection] = data + theirs[selection] = data + + def write_chunk(indices: tuple[int, ...], data: np.ndarray[Any, Any]) -> None: + ours.store_chunk(indices, data) + theirs.store_chunk(indices, data) + + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + write_subset(..., _SHAPE) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + write_subset((slice(1, 3), slice(-2, None)), (2, 2)) + write_subset((slice(3, 100),), (2, 3)) + write_subset((slice(2, 2),), (0, 3)) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + # A full edge chunk whose part past the array's edge holds the fill value. + edge_chunk = np.full(chunk_shape, fill, dtype=dtype) + edge_chunk[tuple(slice(0, n) for n in edge_inside)] = _values(rng, dtype, edge_inside) + write_chunk(edge, edge_chunk) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + first = (0,) * len(grid) + write_chunk(first, np.full(chunk_shape, fill, dtype=dtype)) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + for target in (ours, theirs): + target.store_chunk(first, np.full(chunk_shape, fill, dtype=dtype), store_empty_chunks=True) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + # The whole of the first chunk, through a subset, with and without the option. + region = tuple(slice(0, n) for n in chunk_shape) + region_shape = tuple(min(n, extent) for n, extent in zip(chunk_shape, _SHAPE, strict=True)) + for store_empty_chunks in (False, True): + for target in (ours, theirs): + target.store_array_subset( + region, + np.full(region_shape, fill, dtype=dtype), + store_empty_chunks=store_empty_chunks, + ) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + ours.erase_chunk(edge) + theirs.erase_chunk(edge) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + + +@pytest.mark.parametrize( + "data", + [np.zeros((5, 3), dtype="int32"), np.zeros((5, 2), dtype="int64"), np.zeros((), "int64")], + ids=["data-type", "shape", "scalar"], +) +def test_both_refuse_data_that_is_not_exactly_the_region(tmp_path: Path, data: Any) -> None: + ours, theirs, *_ = _open_both(tmp_path, _metadata("int64", 0, "regular")) + with pytest.raises((TypeError, ValueError)): + ours[...] = data + with pytest.raises(Exception): # noqa: B017 + theirs[...] = data diff --git a/tools/compat/README.md b/tools/compat/README.md new file mode 100644 index 0000000000..50dd09c967 --- /dev/null +++ b/tools/compat/README.md @@ -0,0 +1,29 @@ +# Compatibility differential + +Checks that this checkout behaves as a baseline zarr does wherever existing code can +look: the synchronous `Array` API, `AsyncArray` used as a dataclass (fields, `replace`, +`asdict`, equality, `object.__setattr__`), copies, pickles carried between the two +versions in both directions, `AsyncArray` subclasses of several shapes (one overrides +`_set_selection`), arrays whose metadata documents another writer stored (chunk sizes +zarr reads only by repairing them), and writes through groups whose consolidated +metadata holds copies of such documents, at the root and in a subgroup. + +```bash +hatch run test.py3.12-optional:python tools/compat/compat.py --baseline "$(git merge-base HEAD upstream/main)" --seeds 2000 +``` + +`--baseline` takes any commit, branch or tag: the `main` a branch holds, as above, or a +release such as `v3.4.2`. The run takes about half a minute for 2000 seeds, prints the differences by class +(see `diff.py`) and leaves every run's steps in its work directory (`--work`). + +- `compat_scenarios.py` holds the scenarios. Random programs (one per seed) create or open + an array, then apply a seeded sequence of writes, reads, resizes, appends, attribute + updates, reopens and copies through several handles, recording what each step returns, + raises and warns, and the store's contents. The sequence depends only on the seed, so + both versions perform the same operations. +- `run.py` runs them under one source tree; `diff.py` compares two runs. + +A difference is a change a caller can observe, which is not always a break: read it, and +say in the change's notes why each one is intended. Steps labeled `internal:` look at +private state and are reported apart. The scenarios cover existing surfaces only: a new +API has no baseline to differ from, so its tests are the regular suite. diff --git a/tools/compat/compat.py b/tools/compat/compat.py new file mode 100644 index 0000000000..1159594b9c --- /dev/null +++ b/tools/compat/compat.py @@ -0,0 +1,137 @@ +""" +Check that this checkout behaves as a baseline zarr does, wherever code today can look. + + python tools/compat/compat.py --baseline REF [--seeds N] [--work DIR] + +Exports `src` at `REF` (a commit, branch or tag), runs the scenarios in +`compat_scenarios.py` under it and under this checkout's `src`, carries pickles each way +between the two, and prints the differences (see `diff.py` for how they are classed). +Run it with an interpreter that has this checkout's dependencies, such as the test +environment's. +""" + +from __future__ import annotations + +import argparse +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent + + +def export(ref: str, into: Path) -> Path: + """The `src` directory of `ref`, with the version file the build would write.""" + shutil.rmtree(into, ignore_errors=True) + into.mkdir(parents=True) + archive = subprocess.run( + ["git", "-C", str(ROOT), "archive", ref, "src"], check=True, capture_output=True + ).stdout + subprocess.run(["tar", "-x", "-C", str(into)], input=archive, check=True) + described = subprocess.run( + ["git", "-C", str(ROOT), "describe", "--tags", "--match", "v[0-9]*", ref], + capture_output=True, + text=True, + check=True, + ).stdout.strip() + # zarr refuses to import as version 0.0.0, so name the baseline after its tag. + tag, _, rest = described.removeprefix("v").partition("-") + distance, _, commit = rest.partition("-") + version = f"{tag}.post{distance}+{commit}" if rest else (tag or "999.0.0") + (into / "src" / "zarr" / "_version.py").write_text( + f"__version__ = version = {version!r}\n" + f"__version_tuple__ = version_tuple = (0, 0, 0, {version!r})\n" + "__commit_id__ = commit_id = None\n" + ) + return into / "src" + + +def run(src: Path, out: Path, work: Path, *args: str) -> None: + # `src` goes on PYTHONPATH, ahead of any installed zarr, so `run.py` imports it. + pythonpath = os.pathsep.join([str(src), os.environ.get("PYTHONPATH", "")]).rstrip(os.pathsep) + subprocess.run( + [ + sys.executable, + str(HERE / "run.py"), + str(src), + str(out), + "--tmp", + str(work / "tmp"), + *args, + ], + check=True, + env={**os.environ, "PYTHONPATH": pythonpath}, + ) + + +def diff(old: Path, new: Path, out: Path, title: str) -> None: + print(f"\n=== {title} ===", flush=True) + subprocess.run( + [sys.executable, str(HERE / "diff.py"), str(old), str(new), "--out", str(out)], check=True + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--baseline", required=True) + parser.add_argument("--seeds", type=int, default=200) + parser.add_argument("--work", type=Path) + args = parser.parse_args() + work = args.work or Path(tempfile.mkdtemp(prefix="zarr-compat-")) + work.mkdir(parents=True, exist_ok=True) + sources = {"base": export(args.baseline, work / "base"), "head": ROOT / "src"} + + for name, src in sources.items(): + run(src, work / f"scenarios-{name}.json", work, "--seeds", str(args.seeds)) + diff( + work / "scenarios-base.json", + work / "scenarios-head.json", + work / "diff-scenarios.json", + "scenarios", + ) + + # Pickles: each version dumps over its own stores, kept pristine, and each version loads + # every dump over a fresh copy of the stores it was made over. + for name, src in sources.items(): + stores = work / f"stores-{name}" + shutil.rmtree(stores, ignore_errors=True) + run( + src, + work / "unused.json", + work, + "--dump-pickles", + str(work / f"pickles-{name}"), + "--stores", + str(stores), + ) + shutil.rmtree(work / f"pristine-{name}", ignore_errors=True) + shutil.copytree(stores, work / f"pristine-{name}") + for dumped in sources: + for loader, src in sources.items(): + stores = work / f"stores-{dumped}" + shutil.rmtree(stores) + shutil.copytree(work / f"pristine-{dumped}", stores) + run( + src, + work / f"pickles-{dumped}-in-{loader}.json", + work, + "--load-pickles", + str(work / f"pickles-{dumped}"), + ) + reference = work / "pickles-base-in-base.json" + for dumped, loader in (("base", "head"), ("head", "base"), ("head", "head")): + diff( + reference, + work / f"pickles-{dumped}-in-{loader}.json", + work / f"diff-pickles-{dumped}-in-{loader}.json", + f"pickles dumped by {dumped}, loaded by {loader} (vs base in base)", + ) + print(f"\nwork directory: {work}") + + +if __name__ == "__main__": + main() diff --git a/tools/compat/compat_scenarios.py b/tools/compat/compat_scenarios.py new file mode 100644 index 0000000000..b34762b405 --- /dev/null +++ b/tools/compat/compat_scenarios.py @@ -0,0 +1,959 @@ +""" +Scenarios for the zarr compatibility differential (see `README.md`). + +Each scenario drives zarr the way existing code does (the synchronous `Array` API, +`AsyncArray` used as a dataclass, pickle, copy, subclasses, and stored documents written +by other software) and records what a caller can observe. `run.py` runs the scenarios +under one zarr source tree, and `diff.py` compares two runs. + +This module must import under every zarr version it runs against, so it uses only names +each of them has. It is imported as `compat_scenarios` in every process, so a pickle of +one of its subclasses loads in either version. +""" + +from __future__ import annotations + +import copy +import dataclasses +import hashlib +import json +import math +import pickle +import random +import re +import shutil +import warnings +from pathlib import Path +from typing import Any + +import numpy as np + +import zarr +import zarr.core.sync +import zarr.storage +from zarr.core.array import AsyncArray +from zarr.core.buffer import default_buffer_prototype + +_ADDRESS = re.compile(r"0x[0-9a-fA-F]+") +_MEMORY_STORE = re.compile(r"memory://\d+") +_METADATA_KEYS = (".zarray", ".zattrs", ".zgroup", ".zmetadata", "zarr.json") +_MAX_ELEMENTS = 512 + + +class Recorder: + """Records what each step of a scenario returned, raised, and warned.""" + + def __init__(self, tmp: Path) -> None: + self.events: list[dict[str, Any]] = [] + self.tmp = str(tmp) + self.scenario = "" + + def norm(self, text: str) -> str: + text = _MEMORY_STORE.sub("memory://?", _ADDRESS.sub("0x?", text)) + return text.replace(self.tmp, "") + + def step(self, label: str, fn: Any) -> tuple[bool, Any]: + """Run `fn`, record its outcome under `label`, and return whether it returned + and what.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + try: + value = fn() + except Exception as e: # noqa: BLE001 (any exception is an outcome to compare) + outcome: dict[str, Any] = { + "raises": f"{type(e).__module__}.{type(e).__qualname__}", + "message": self.norm(str(e)), + } + ok = False + value = None + else: + outcome = {"value": self.summarize(value)} + ok = True + if caught: + outcome["warnings"] = [[w.category.__name__, self.norm(str(w.message))] for w in caught] + self.events.append({"scenario": self.scenario, "label": label, **outcome}) + return ok, value + + def summarize(self, value: Any) -> Any: + """A JSON value that compares equal across processes exactly when what a caller + sees of `value` does.""" + if isinstance(value, str): + return self.norm(value) + if value is None or isinstance(value, bool): + return value + if isinstance(value, int): + return value + if isinstance(value, float): + return value if math.isfinite(value) else repr(value) + if isinstance(value, complex): + return {"complex": [self.summarize(value.real), self.summarize(value.imag)]} + if isinstance(value, np.ndarray): + flat = value.reshape(-1)[:_MAX_ELEMENTS] + return { + "ndarray": value.dtype.str, + "shape": list(value.shape), + "data": [self.summarize(v) for v in flat.tolist()], + } + if isinstance(value, np.generic): + return {"scalar": value.dtype.str, "value": self.summarize(value.item())} + if isinstance(value, bytes | bytearray | memoryview): + raw = bytes(value) + return {"bytes": hashlib.sha1(raw).hexdigest()[:16], "len": len(raw)} + if isinstance(value, tuple): + return {"tuple": [self.summarize(v) for v in value]} + if isinstance(value, list): + return [self.summarize(v) for v in value] + if isinstance(value, dict): + return {"dict": [[self.summarize(k), self.summarize(v)] for k, v in value.items()]} + if isinstance(value, zarr.Array): + return {"Array": type(value).__qualname__, "shape": list(value.shape)} + if isinstance(value, AsyncArray): + return {"AsyncArray": type(value).__qualname__, "shape": list(value.shape)} + if isinstance(value, zarr.Group): + return {"Group": type(value).__qualname__, "path": value.path} + return {"type": type(value).__qualname__, "repr": self.norm(repr(value))} + + +# Stores --------------------------------------------------------------------------------- + + +def snapshot(store: Any) -> dict[str, Any]: + """Every key of `store`: the text of a metadata document, or the digest of a chunk.""" + if isinstance(store, zarr.storage.LocalStore): + root = Path(store.root) + items = { + p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file() + } + else: + items = {k: v.to_bytes() for k, v in store._store_dict.items()} + out: dict[str, Any] = {} + for key in sorted(items): + raw = items[key] + if key.rsplit("/", 1)[-1] in _METADATA_KEYS: + out[key] = raw.decode() + else: + out[key] = hashlib.sha1(raw).hexdigest()[:16] + return out + + +def new_store(kind: str, tmp: Path, name: str) -> Any: + if kind == "memory": + return zarr.storage.MemoryStore() + path = tmp / name + shutil.rmtree(path, ignore_errors=True) + return zarr.storage.LocalStore(path) + + +def put_document(store: Any, key: str, document: dict[str, Any]) -> None: + """Write `document` at `key` as other software would: compact JSON, bytes as given.""" + text = json.dumps(document).encode() + if isinstance(store, zarr.storage.LocalStore): + path = Path(store.root) / key + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(text) + else: + store._store_dict[key] = default_buffer_prototype().buffer.from_bytes(text) + + +# Observations --------------------------------------------------------------------------- + + +def observe(rec: Recorder, name: str, arr: Any, store: Any) -> None: + """Record what a caller sees of `arr` and its store.""" + if arr is None: + rec.step(f"{name}:missing", lambda: None) + return + rec.step(f"{name}:shape", lambda: arr.shape) + rec.step(f"{name}:chunks", lambda: arr.chunks) + rec.step(f"{name}:shards", lambda: arr.shards) + rec.step(f"{name}:dtype", lambda: str(arr.dtype)) + rec.step(f"{name}:fill_value", lambda: arr.fill_value) + rec.step(f"{name}:order", lambda: arr.order) + rec.step(f"{name}:attrs", lambda: arr.attrs.asdict()) + rec.step(f"{name}:metadata", lambda: arr.metadata.to_dict()) + rec.step(f"{name}:metadata.type", lambda: type(arr.metadata).__qualname__) + rec.step(f"{name}:read", lambda: arr[...]) + rec.step(f"{name}:nchunks_initialized", lambda: arr.nchunks_initialized) + rec.step(f"{name}:read_only", lambda: arr.read_only) + rec.step(f"{name}:path", lambda: (arr.path, arr.name, arr.basename)) + rec.step(f"{name}:store", lambda: snapshot(store)) + + +def observe_surface(rec: Recorder, name: str, arr: Any, other: Any) -> None: + """Record `arr` as a dataclass and an object: what code that treats it as one sees.""" + aa = arr.async_array + rec.step(f"{name}:fields", lambda: [f.name for f in dataclasses.fields(aa)]) + rec.step( + f"{name}:fields.init", + lambda: [(f.name, f.init, f.compare, f.repr) for f in dataclasses.fields(type(aa))], + ) + rec.step(f"{name}:Array.fields", lambda: [f.name for f in dataclasses.fields(arr)]) + rec.step(f"{name}:eq.self", lambda: (aa == aa, arr == arr)) # noqa: PLR0124 + rec.step(f"{name}:eq.copy", lambda: aa == copy.copy(aa)) + rec.step(f"{name}:eq.other", lambda: (aa == other.async_array, arr == other)) + rec.step(f"{name}:hash", lambda: hash(aa) == hash(copy.copy(aa))) + rec.step(f"{name}:Array.hash", lambda: hash(arr) == hash(arr)) + rec.step(f"{name}:repr", lambda: (repr(arr), str(arr))) + rec.step(f"{name}:AsyncArray.repr", lambda: repr(aa)) + rec.step(f"{name}:asdict.keys", lambda: list(dataclasses.asdict(aa))) + rec.step(f"{name}:astuple.len", lambda: len(dataclasses.astuple(aa))) + rec.step(f"{name}:codec_pipeline.type", lambda: type(aa.codec_pipeline).__qualname__) + rec.step(f"{name}:config", lambda: aa.config) + rec.step(f"{name}:store_path", lambda: str(aa.store_path)) + rec.step(f"{name}:metadata.is", lambda: aa.metadata is arr.metadata) + rec.step(f"{name}:internal:vars", lambda: sorted(vars(aa))) + rec.step(f"{name}:internal:chunk_grid.type", lambda: type(aa._chunk_grid).__qualname__) + rec.step(f"{name}:frozen", lambda: setattr(aa, "metadata", aa.metadata)) + + +# Random programs ------------------------------------------------------------------------- + +_DTYPES = ["int8", "uint16", "int32", "float32", "float64", "bool", "complex64"] +_ATTRIBUTES: list[dict[str, Any] | None] = [ + None, + {}, + {"a": 1, "b": [1, 2]}, + {"z": 1, "a": {"n": None}}, +] + + +def _selection(rng: random.Random, shape: list[int]) -> tuple[str, Any]: + """A selection into an array of `shape`: its kind and the selection.""" + if not shape: + return "basic", rng.choice([(), Ellipsis]) + if all(n > 0 for n in shape) and rng.random() < 0.3: + kind = rng.choice(["oindex", "vindex"]) + if kind == "oindex": + return kind, tuple(sorted(rng.sample(range(n), rng.randint(1, n))) for n in shape) + k = rng.randint(1, 4) + return kind, tuple([rng.randrange(n) for _ in range(k)] for n in shape) + sel: list[Any] = [] + for n in shape: + r = rng.random() + if n > 0 and r < 0.25: + sel.append(rng.randrange(n)) + else: + start = rng.randint(0, n) + stop = rng.randint(start, n + 2) + sel.append(slice(start, stop, rng.choice([1, 1, 2]))) + return "basic", tuple(sel) + + +def _selected_shape(kind: str, sel: Any, shape: list[int]) -> tuple[int, ...]: + dummy = np.empty(shape, dtype="u1") + if kind == "oindex": + return dummy[np.ix_(*sel)].shape + if kind == "vindex": + return dummy[tuple(np.asarray(s) for s in sel)].shape + return dummy[sel].shape + + +def _values(rng: random.Random, dtype: str, shape: tuple[int, ...]) -> Any: + if rng.random() < 0.2: + return np.array(rng.randint(0, 5)).astype(dtype)[()] + size = int(np.prod(shape)) + return (np.arange(size) % 7 + rng.randint(0, 3)).reshape(shape).astype(dtype) + + +def _index(arr: Any, kind: str) -> Any: + return {"basic": arr, "oindex": arr.oindex, "vindex": arr.vindex}[kind] + + +def _write(arr: Any, kind: str, sel: Any, values: Any) -> None: + _index(arr, kind)[sel] = values + + +def run_program(rec: Recorder, seed: int, tmp: Path) -> None: + """A random sequence of operations on one array through several handles. The + sequence depends only on `seed`, never on what zarr returns, so both runs of a + seed perform the same operations.""" + rng = random.Random(seed) + zarr_format = rng.choice([2, 3]) + ndim = rng.choice([0, 1, 1, 2, 2, 3]) + shape = [rng.choice([0, 1, 3, 4, 7]) for _ in range(ndim)] + chunks = [rng.choice([1, 2, 3, 5, 8]) for _ in range(ndim)] + shards = None + if zarr_format == 3 and ndim > 0 and rng.random() < 0.4: + shards = [c * rng.choice([1, 2]) for c in chunks] + dtype = rng.choice(_DTYPES) + fill_value = rng.choice([None, 0, 1]) + if dtype == "bool" and fill_value is not None: + fill_value = bool(fill_value) + kwargs: dict[str, Any] = { + "shape": shape, + "chunks": chunks if ndim else "auto", + "dtype": dtype, + "zarr_format": zarr_format, + "attributes": rng.choice(_ATTRIBUTES), + "compressors": rng.choice(["auto", None]), + } + if fill_value is not None: + kwargs["fill_value"] = fill_value + if shards is not None: + kwargs["shards"] = shards + if zarr_format == 3 and ndim and rng.random() < 0.3: + kwargs["dimension_names"] = [f"d{i}" for i in range(ndim)] + if zarr_format == 2 and rng.random() < 0.3: + kwargs["order"] = "F" + if rng.random() < 0.3: + kwargs["chunk_key_encoding"] = ( + {"name": "v2", "separator": rng.choice([".", "/"])} + if zarr_format == 2 or rng.random() < 0.5 + else {"name": "default", "separator": "."} + ) + if rng.random() < 0.3: + kwargs["config"] = {"write_empty_chunks": rng.choice([True, False])} + store_kind = rng.choice(["memory", "local"]) + store = new_store(store_kind, tmp, f"program-{seed}") + path = rng.choice(["", "a", "g/a"]) + rec.step("create.kwargs", lambda: {k: str(v) for k, v in kwargs.items()}) + + legacy = None + if ndim and rng.random() < 0.35: + # A document another writer stored, with chunk sizes zarr reads only by repairing + # them: 0 or JSON false (an empty axis's `chunks=-1`), or JSON true. + stored = [ + rng.choice([c, c, 0, True] + ([False] if zarr_format == 3 else [])) for c in chunks + ] + legacy = _legacy_document(zarr_format, shape, stored, dtype, kwargs.get("attributes")) + if legacy is None: + ok, arr = rec.step("create", lambda: zarr.create_array(store, name=path, **kwargs)) + else: + rec.step("legacy.document", lambda: legacy) + prefix = f"{path}/" if path else "" + for key, document in legacy.items(): + put_document(store, prefix + key, document) + ok, arr = rec.step("create", lambda: zarr.open_array(store, path=path, mode="r+")) + handles: list[Any] = [arr if ok else None] + observe(rec, "h0", arr if ok else None, store) + + for step in range(rng.randint(6, 14)): + op = rng.choice( + [ + "write", "write", "read", "resize", "append", "attrs", "reopen", "reopen_ro", + "pickle", "copy", "deepcopy", "replace", "setattr", "with_config", "observe", + "surface", "replace_metadata", "from_dict", "async_read", "attrs_in_place", + ] + ) # fmt: skip + h = rng.randrange(len(handles)) + arr = handles[h] + tag = f"{step}:{op}:h{h}" + if op in ("write", "read"): + kind, sel = _selection(rng, shape) + values = _values(rng, dtype, _selected_shape(kind, sel, shape)) + if arr is None: + rec.step(f"{tag}:skipped", lambda: None) + continue + if op == "write": + rec.step( + f"{tag}:{kind}:{sel!r}", + lambda a=arr, k=kind, s=sel, v=values: _write(a, k, s, v), + ) + else: + rec.step(f"{tag}:{kind}:{sel!r}", lambda a=arr, k=kind, s=sel: _index(a, k)[s]) + elif op == "resize": + new = [rng.choice([0, 1, 2, 5, 9]) for _ in shape] + if arr is not None: + rec.step(f"{tag}:{new}", lambda a=arr, n=new: a.resize(n)) + shape = new + elif op == "append": + if not shape: + continue + axis = rng.randrange(len(shape)) + extra = [n if i != axis else rng.randint(1, 3) for i, n in enumerate(shape)] + data = (np.arange(int(np.prod(extra))) % 5).reshape(extra).astype(dtype) + if arr is not None: + rec.step(f"{tag}:{axis}", lambda a=arr, d=data, x=axis: a.append(d, axis=x)) + shape = [n + (extra[i] if i == axis else 0) for i, n in enumerate(shape)] + elif op == "attrs": + update = rng.choice([{}, {"a": 2}, {"new": [1, {"x": 1}]}, {"b": None, "a": 3}]) + if arr is not None: + rec.step(f"{tag}:{update}", lambda a=arr, u=update: a.update_attributes(u)) + elif op in ("reopen", "reopen_ro"): + mode = "r" if op == "reopen_ro" else "r+" + ok, new_arr = rec.step(tag, lambda m=mode: zarr.open_array(store, path=path, mode=m)) + handles.append(new_arr if ok else None) + elif op in ( + "pickle", + "copy", + "deepcopy", + "replace", + "setattr", + "replace_metadata", + "from_dict", + ): + if arr is None: + handles.append(None) + continue + make = { + "pickle": lambda a=arr: pickle.loads(pickle.dumps(a)), + "copy": lambda a=arr: copy.copy(a), + "deepcopy": lambda a=arr: copy.deepcopy(a), + "replace": lambda a=arr: zarr.Array(dataclasses.replace(a.async_array)), + "setattr": lambda a=arr: _setattr_copy(a), + "replace_metadata": lambda a=arr: _replace_metadata(a), + "from_dict": lambda a=arr: zarr.Array( + AsyncArray(a.metadata.to_dict(), a.async_array.store_path, a.async_array.config) + ), + }[op] + ok, new_arr = rec.step(tag, make) + handles.append(new_arr if ok else None) + elif op == "with_config": + if arr is None: + handles.append(None) + continue + cfg = {"write_empty_chunks": rng.choice([True, False])} + ok, new_arr = rec.step(tag, lambda a=arr, c=cfg: a.with_config(c)) + handles.append(new_arr if ok else None) + elif op == "observe": + observe(rec, tag, arr, store) + elif op == "attrs_in_place": + how = rng.choice(["set", "reorder", "nested"]) + if arr is not None: + rec.step(f"{tag}:{how}", lambda a=arr, w=how: _change_attributes_in_place(a, w)) + elif op == "async_read": + if arr is not None: + rec.step(tag, lambda a=arr: zarr.core.sync.sync(a.async_array.getitem(...))) + elif op == "surface": + if arr is not None and handles[0] is not None: + observe_surface(rec, tag, arr, handles[0]) + for i, arr in enumerate(handles): + if arr is not None: + rec.step(f"end:h{i}:read", lambda a=arr: a[...]) + rec.step(f"end:h{i}:attrs", lambda a=arr: a.attrs.asdict()) + rec.step(f"end:h{i}:shape", lambda a=arr: a.shape) + observe(rec, "end:fresh", zarr.open_array(store, path=path, mode="r"), store) + + +def _legacy_document( + zarr_format: int, shape: list[int], chunks: list[Any], dtype: str, attributes: Any +) -> dict[str, dict[str, Any]]: + """The documents, by key, of an array stored by another writer with chunk sizes + `chunks`.""" + fill: Any = False if dtype == "bool" else 0 + if zarr_format == 2: + out = { + ".zarray": { + "zarr_format": 2, "shape": shape, "chunks": chunks, "dtype": np.dtype(dtype).str, + "fill_value": fill, "order": "C", "filters": None, "compressor": None, + } + } # fmt: skip + if attributes: + out[".zattrs"] = attributes + return out + document = _v3_doc(shape, chunks) + document["data_type"] = dtype + document["fill_value"] = [0.0, 0.0] if dtype == "complex64" else fill + document["attributes"] = attributes or {} + if dtype in ("int8", "bool"): + document["codecs"] = [{"name": "bytes", "configuration": {}}] + return {"zarr.json": document} + + +def _change_attributes_in_place(arr: Any, how: str) -> Any: + """Change `arr`'s attributes in the metadata's own dict, as code that holds it does.""" + attributes = arr.metadata.attributes + if how == "set": + attributes["in_place"] = [1, 2] + elif how == "reorder": + for key in list(attributes): + attributes[key] = attributes.pop(key) + attributes["last"] = 0 + else: + attributes.setdefault("nested", {"n": []})["n"].append(len(attributes)) + return dict(attributes) + + +def _replace_metadata(arr: Any) -> Any: + """A copy of `arr` made by `dataclasses.replace` with metadata of other attributes.""" + metadata = dataclasses.replace(arr.metadata, attributes={"replaced": True}) + return zarr.Array(dataclasses.replace(arr.async_array, metadata=metadata)) + + +def _setattr_copy(arr: Any) -> Any: + """A copy of `arr` whose metadata is replaced the way frozen-dataclass code does it.""" + aa = copy.copy(arr.async_array) + metadata = dataclasses.replace(arr.metadata, attributes={"set": "by setattr"}) + object.__setattr__(aa, "metadata", metadata) + return zarr.Array(aa) + + +# Documents other software stored --------------------------------------------------------- + + +def _v2_doc(shape: list[int], chunks: list[Any]) -> dict[str, Any]: + return { + "zarr_format": 2, + "shape": shape, + "chunks": chunks, + "dtype": " dict[str, Any]: + bytes_codec: dict[str, Any] = {"name": "bytes", "configuration": {"endian": "little"}} + codecs: list[Any] = [bytes_codec] + if inner is not None: + codecs = [ + { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": inner, + "codecs": [bytes_codec], + "index_codecs": [bytes_codec, {"name": "crc32c"}], + "index_location": "end", + }, + } + ] + return { + "zarr_format": 3, + "node_type": "array", + "shape": shape, + "data_type": "int16", + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": chunk_shape}}, + "chunk_key_encoding": {"name": "default", "configuration": {"separator": "/"}}, + "fill_value": 0, + "codecs": codecs, + "attributes": {"z": 1, "a": 2}, + } + + +DOCUMENTS: dict[str, dict[str, Any]] = { + "v2-valid": _v2_doc([10, 10], [4, 5]), + "v3-valid-empty-axes": _v3_doc([0, 0], [1, 1]), + "v3-valid-sharded": _v3_doc([10], [4], inner=[2]), + "v2-zero-empty-axis": _v2_doc([0, 4], [0, 4]), + "v3-false-empty-axis": _v3_doc([0], [False]), + "v2-true": _v2_doc([5], [True]), + "v3-true": _v3_doc([5, 4], [True, 4]), + "v2-zero-grown-axis": _v2_doc([3], [0]), + "v3-zero-grown-axis": _v3_doc([4, 3], [4, 0]), + "v2-zero-empty-and-grown-axes": _v2_doc([0, 3], [0, 0]), + "v3-sharded-zero-empty-axis": _v3_doc([0], [0], inner=[4]), + "v3-sharded-zero-grown-axis": _v3_doc([10], [0], inner=[4]), + "v3-sharded-zero-2d": _v3_doc([0, 3], [0, 3], inner=[2, 3]), + "v3-sharded-true": _v3_doc([5], [True], inner=[True]), + "v2-float-chunk": _v2_doc([4], [2.0]), + "v3-float-chunk": _v3_doc([4], [2.0]), + "v2-negative-chunk": _v2_doc([4], [-1]), + "v3-edge-list-in-regular": _v3_doc([5], [[2, 3]]), + "v2-fill-nan-int": {**_v2_doc([4], [2]), "fill_value": "NaN"}, + "v2-zattrs-fields": {**_v2_doc([4], [2]), "dimension_separator": "/"}, + "v3-extra-field": {**_v3_doc([4], [2]), "extra": {"must_understand": False}}, +} + + +def run_document(rec: Recorder, name: str, tmp: Path) -> None: + """Open an array whose document other software stored, through two handles, and + write through one of them.""" + document = DOCUMENTS[name] + zarr_format = document["zarr_format"] + store = new_store("local", tmp, f"doc-{name}") + if zarr_format == 2: + put_document(store, ".zgroup", {"zarr_format": 2}) + put_document(store, "a/.zarray", document) + put_document(store, "a/.zattrs", {"z": 1, "a": 2}) + else: + put_document(store, "zarr.json", {"zarr_format": 3, "node_type": "group", "attributes": {}}) + put_document(store, "a/zarr.json", document) + + ok, first = rec.step("open", lambda: zarr.open_array(store, path="a", mode="r+")) + observe(rec, "first", first if ok else None, store) + ok2, second = rec.step("open.second", lambda: zarr.open_array(store, path="a", mode="r+")) + if not ok: + return + rec.step("pickle.first", lambda: pickle.loads(pickle.dumps(first)).metadata.to_dict()) + shape = first.shape + if all(n > 0 for n in shape): + rec.step( + "write.first", + lambda: first.__setitem__(..., np.arange(int(np.prod(shape))).reshape(shape)), + ) + rec.step("store.after_write", lambda: snapshot(store)) + if ok2: + rec.step("second.read", lambda: second[...]) + rec.step("second.resize", lambda: second.resize([n + 2 for n in shape])) + rec.step("second.write", lambda: second.__setitem__(..., 3)) + observe(rec, "second", second, store) + rec.step("first.read_after_second", lambda: first[...]) + rec.step("first.update_attributes", lambda: first.update_attributes({})) + rec.step("store.after_attrs", lambda: snapshot(store)) + _ = rec.step("consolidate", lambda: zarr.consolidate_metadata(store)) + rec.step("store.after_consolidate", lambda: snapshot(store)) + ok4, cgroup = rec.step("open_consolidated", lambda: zarr.open_consolidated(store, mode="r+")) + if ok4: + rec.step("consolidated.members", lambda: [k for k, _ in cgroup.members()]) + ok5, member = rec.step("consolidated.member", lambda: cgroup["a"]) + if ok5: + observe(rec, "member", member, store) + rec.step("member.write", lambda: member.__setitem__(..., 1)) + rec.step("group.to_dict", lambda: cgroup.metadata.to_dict()) + rec.step("store.end", lambda: snapshot(store)) + + +# Groups ------------------------------------------------------------------------------------- + + +def put_consolidated_group(store: Any, prefix: str, document: dict[str, Any]) -> None: + """Store, as other software would, a group at `prefix` holding the array `a` with + `document`, and consolidated metadata holding a copy of it.""" + at = f"{prefix}/" if prefix else "" + if document["zarr_format"] == 2: + attributes = {"z": 1, "a": 2} + zgroup = {"zarr_format": 2} + put_document(store, f"{at}.zgroup", zgroup) + put_document(store, f"{at}a/.zarray", document) + put_document(store, f"{at}a/.zattrs", attributes) + members = {".zgroup": zgroup, "a/.zarray": document, "a/.zattrs": attributes} + put_document(store, f"{at}.zmetadata", {"zarr_consolidated_format": 1, "metadata": members}) + else: + consolidated = {"kind": "inline", "must_understand": False, "metadata": {"a": document}} + put_document(store, f"{at}a/zarr.json", document) + put_document( + store, + f"{at}zarr.json", + { + "zarr_format": 3, + "node_type": "group", + "attributes": {}, + "consolidated_metadata": consolidated, + }, + ) + + +def _open_group_at(store: Any, prefix: str) -> Any: + """The group at `prefix`, reached through the root group when it is not the root.""" + root = zarr.open_group(store, mode="r+") + return root[prefix] if prefix else root + + +def _set_group_attribute(group: Any) -> None: + group.attrs["x"] = 1 + + +GROUP_FLOWS = ( + "attrs", + "array_then_attrs", + "attrs_then_array", + "members_then_attrs", + "member_write", + "create_array", + "reconsolidate", + "resaved_elsewhere", +) +GROUP_PREFIXES = ("", "g") + + +def run_group(rec: Recorder, name: str, prefix: str, flow: str, tmp: Path) -> None: + """Write through a group whose consolidated metadata other software stored: at the + root, or (`prefix`) in a subgroup of a root group that holds none.""" + document = DOCUMENTS[name] + zarr_format = document["zarr_format"] + store = new_store("local", tmp, f"group-{name}-{prefix or 'root'}-{flow}") + if prefix: + if zarr_format == 2: + put_document(store, ".zgroup", {"zarr_format": 2}) + else: + root = {"zarr_format": 3, "node_type": "group", "attributes": {}} + put_document(store, "zarr.json", root) + put_consolidated_group(store, prefix, document) + array_path = f"{prefix}/a" if prefix else "a" + + if flow in ("array_then_attrs", "resaved_elsewhere"): + rec.step("open_array", lambda: zarr.open_array(store, path=array_path, mode="r+").shape) + if flow == "resaved_elsewhere": + # Another store object over the same directory re-saves the array and consolidates. + other = zarr.storage.LocalStore(store.root) + rec.step( + "elsewhere.resave", + lambda: zarr.open_array(other, path=array_path, mode="r+").update_attributes({}).shape, + ) + rec.step( + "elsewhere.consolidate", + lambda: zarr.consolidate_metadata(other, path=prefix or None).metadata.to_dict(), + ) + ok, group = rec.step("open", lambda: _open_group_at(store, prefix)) + if ok: + if flow == "attrs_then_array": + rec.step("open_array", lambda: zarr.open_array(store, path=array_path, mode="r+").shape) + if flow == "members_then_attrs": + rec.step("members", lambda: sorted(k for k, _ in group.members())) + if flow == "member_write": + ok_member, member = rec.step("member", lambda: group["a"]) + if ok_member and all(n > 0 for n in member.shape): + rec.step("member.write", lambda: member.__setitem__(..., 1)) + rec.step("member.read", lambda: member[...]) + elif flow == "create_array": + rec.step( + "create_array", lambda: group.create_array("b", shape=(2,), dtype="int8").shape + ) + elif flow == "reconsolidate": + rec.step( + "consolidate", + lambda: zarr.consolidate_metadata(store, path=prefix or None).metadata.to_dict(), + ) + else: + rec.step("attrs", lambda: _set_group_attribute(group)) + rec.step("store.end", lambda: snapshot(store)) + + +# Subclasses -------------------------------------------------------------------------------- + + +@dataclasses.dataclass(frozen=True) +class TaggedAsyncArray(AsyncArray): # type: ignore[type-arg] + """A dataclass subclass with a field of its own.""" + + tag: str = "untagged" + + +class PlainAsyncArray(AsyncArray): # type: ignore[type-arg] + """A subclass that adds a method and nothing else.""" + + def describe(self) -> str: + return f"{type(self).__name__}{self.shape}" + + +class SlottedAsyncArray(AsyncArray): # type: ignore[type-arg] + """A subclass with a slot of its own.""" + + __slots__ = ("note",) + + +class ReducingAsyncArray(AsyncArray): # type: ignore[type-arg] + """A subclass that pickles through a reduction of its own.""" + + def __reduce__(self) -> Any: + return (_rebuild_reducing, (self.metadata, self.store_path, self.config)) + + +def _rebuild_reducing(metadata: Any, store_path: Any, config: Any) -> ReducingAsyncArray: + return ReducingAsyncArray(metadata, store_path, config) + + +class InitAsyncArray(AsyncArray): # type: ignore[type-arg] + """A subclass whose `__init__` builds state of its own.""" + + def __init__(self, metadata: Any, store_path: Any, config: Any = None) -> None: + super().__init__(metadata, store_path, config) + object.__setattr__(self, "built", tuple(self.shape)) + + +class ClassAttrAsyncArray(AsyncArray): # type: ignore[type-arg] + """A subclass with class attributes, one of them named like an internal.""" + + kind = "class-attr" + _io = "subclass-owned" + + +class OverridingAsyncArray(AsyncArray): # type: ignore[type-arg] + """A subclass that stores one more than each write gives it.""" + + async def _set_selection( + self, indexer: Any, value: Any, *, prototype: Any, fields: Any = None + ) -> None: + await super()._set_selection( + indexer, np.asarray(value) + 1, prototype=prototype, fields=fields + ) + + +SUBCLASSES = { + "tagged": TaggedAsyncArray, + "plain": PlainAsyncArray, + "slotted": SlottedAsyncArray, + "reducing": ReducingAsyncArray, + "init": InitAsyncArray, + "classattr": ClassAttrAsyncArray, + "overriding": OverridingAsyncArray, +} + + +def make_subclass_instance(name: str, base: Any) -> Any: + cls = SUBCLASSES[name] + aa = base.async_array + if cls is TaggedAsyncArray: + return cls(aa.metadata, aa.store_path, aa.config, tag="t") + obj = cls(aa.metadata, aa.store_path, aa.config) + if cls is SlottedAsyncArray: + object.__setattr__(obj, "note", "noted") + return obj + + +def run_subclass(rec: Recorder, name: str, zarr_format: int, tmp: Path) -> None: + store = new_store("local", tmp, f"sub-{name}-{zarr_format}") + base = zarr.create_array( + store, name="a", shape=(4, 3), chunks=(2, 2), dtype="int32", zarr_format=zarr_format, + attributes={"b": 1, "a": 2}, + ) # fmt: skip + base[...] = np.arange(12).reshape(4, 3) + ok, sub = rec.step("construct", lambda: make_subclass_instance(name, base)) + if not ok: + return + rec.step("type", lambda: type(sub).__qualname__) + rec.step("fields", lambda: [f.name for f in dataclasses.fields(sub)]) + rec.step( + "internal:vars.public", + lambda: ( + sorted(k for k in vars(sub) if not k.startswith("_")) + if hasattr(sub, "__dict__") + else None + ), + ) + rec.step("tag", lambda: getattr(sub, "tag", None)) + rec.step("note", lambda: getattr(sub, "note", None)) + rec.step("built", lambda: getattr(sub, "built", None)) + rec.step("kind", lambda: getattr(sub, "kind", None)) + rec.step("_io", lambda: type(sub).__dict__.get("_io")) + rec.step("describe", lambda: sub.describe() if hasattr(sub, "describe") else None) + rec.step("eq.copy", lambda: sub == copy.copy(sub)) + rec.step("read", lambda: zarr.Array(sub)[...]) + rec.step("async.setitem", lambda: zarr.core.sync.sync(sub.setitem((0, 0), 41))) + rec.step("async.getitem", lambda: zarr.core.sync.sync(sub.getitem((0, 0)))) + for how, make in { + "copy": lambda: copy.copy(sub), + "deepcopy": lambda: copy.deepcopy(sub), + "pickle": lambda: pickle.loads(pickle.dumps(sub)), + "replace": lambda: dataclasses.replace(sub), + "with_config": lambda: sub.with_config({"write_empty_chunks": True}), + }.items(): + ok, other = rec.step(f"{how}", make) + if not ok: + continue + rec.step(f"{how}.type", lambda o=other: type(o).__qualname__) + rec.step( + f"{how}.state", + lambda o=other: [getattr(o, k, None) for k in ("tag", "note", "built", "kind")], + ) + rec.step(f"{how}.metadata", lambda o=other: o.metadata.to_dict()) + rec.step(f"{how}.eq", lambda o=other: o == sub) + rec.step(f"{how}.read", lambda o=other: zarr.Array(o)[...]) + rec.step(f"{how}.write", lambda o=other: zarr.Array(o).__setitem__((0, 0), 99)) + rec.step(f"{how}.resize", lambda o=other: zarr.Array(o).resize((5, 3))) + rec.step(f"{how}.attrs", lambda o=other: zarr.Array(o).update_attributes({"c": 3})) + rec.step(f"{how}.after", lambda o=other: (o.shape, o.metadata.attributes)) + rec.step("sub.after", lambda: (sub.shape, sub.metadata.to_dict())) + rec.step("store.end", lambda: snapshot(store)) + + +# Pickles carried between versions ------------------------------------------------------------ + + +def _dump(directory: Path, name: str, make: Any) -> None: + """Pickle what `make` returns now, or a note of why it could not be made or pickled.""" + try: + data = pickle.dumps(make(), protocol=4) + except Exception as e: # noqa: BLE001 (recorded, for the loading run to compare) + data = pickle.dumps({"unpicklable": f"{type(e).__name__}: {e}"}) + (directory / f"{name}.pkl").write_bytes(data) + + +def dump_pickles(directory: Path, stores: Path) -> None: + """Pickle arrays to load in another version, over local stores under `stores`, which + the loading process sees at the same path.""" + directory.mkdir(parents=True, exist_ok=True) + for zarr_format in (2, 3): + store = zarr.storage.LocalStore(stores / f"v{zarr_format}") + arr = zarr.create_array( + store, name="a", shape=(6,), chunks=(2,), dtype="float32", zarr_format=zarr_format, + attributes={"b": 1, "a": 2}, fill_value=1.5, + ) # fmt: skip + arr[...] = np.arange(6) + _dump(directory, f"v{zarr_format}.array", lambda a=arr: a) + _dump(directory, f"v{zarr_format}.async_array", lambda a=arr: a.async_array) + _dump(directory, f"v{zarr_format}.metadata", lambda a=arr: a.metadata) + arr.update_attributes({"c": 3}) + _dump(directory, f"v{zarr_format}.array.after_attrs", lambda a=arr: a) + for name in SUBCLASSES: + _dump( + directory, + f"v{zarr_format}.sub.{name}", + lambda n=name, a=arr: make_subclass_instance(n, a), + ) + store = zarr.storage.LocalStore(stores / "sharded") + arr = zarr.create_array(store, name="a", shape=(8,), chunks=(2,), shards=(4,), dtype="int16") + arr[...] = np.arange(8) + _dump(directory, "v3.sharded", lambda a=arr: a) + for doc in ("v2-zero-grown-axis", "v3-zero-grown-axis", "v3-true"): + store = zarr.storage.LocalStore(stores / f"doc-{doc}") + key = "a/zarr.json" if DOCUMENTS[doc]["zarr_format"] == 3 else "a/.zarray" + put_document(store, key, DOCUMENTS[doc]) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + _dump(directory, f"doc.{doc}", lambda s=store: zarr.open_array(s, path="a", mode="r+")) + store = zarr.storage.LocalStore(stores / f"group-{doc}") + put_consolidated_group(store, "", DOCUMENTS[doc]) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + _dump(directory, f"group.{doc}", lambda s=store: zarr.open_group(s, mode="r+")) + + +def load_pickles(rec: Recorder, directory: Path) -> None: + for path in sorted(directory.glob("*.pkl")): + rec.scenario = f"pickle:{path.stem}" + ok, obj = rec.step("load", lambda p=path: pickle.loads(p.read_bytes())) + if ok and not isinstance(obj, dict): + _observe_loaded(rec, obj) + + +def _observe_loaded(rec: Recorder, obj: Any) -> None: + """Record what a caller sees of an object loaded from a pickle, and use it.""" + rec.step("type", lambda: type(obj).__qualname__) + if isinstance(obj, zarr.Group): + rec.step("metadata", lambda: obj.metadata.to_dict()) + rec.step("attrs.set", lambda: _set_group_attribute(obj)) + rec.step("store", lambda: snapshot(obj.store)) + ok, member = rec.step("member", lambda: obj["a"]) + if ok and all(n > 0 for n in member.shape): + rec.step("member.write", lambda: member.__setitem__(..., 1)) + rec.step("store.after_write", lambda: snapshot(obj.store)) + return + if not isinstance(obj, zarr.Array | AsyncArray): + rec.step("to_dict", lambda: obj.to_dict()) + return + arr = obj if isinstance(obj, zarr.Array) else zarr.Array(obj) + rec.step("state", lambda: [getattr(obj, k, None) for k in ("tag", "note", "built", "kind")]) + rec.step("metadata", lambda: arr.metadata.to_dict()) + rec.step("attrs", lambda: arr.attrs.asdict()) + rec.step("config", lambda: arr.async_array.config) + rec.step("read", lambda: arr[...]) + rec.step("write", lambda: arr.__setitem__((0,) * arr.ndim, 7)) + rec.step("read.after", lambda: arr[...]) + rec.step("resize", lambda: arr.resize(tuple(n + 1 for n in arr.shape))) + rec.step("attrs.update", lambda: arr.update_attributes({"loaded": True})) + rec.step("metadata.after", lambda: arr.metadata.to_dict()) + rec.step("repickle", lambda: pickle.loads(pickle.dumps(obj)).metadata.to_dict()) + + +# Entry point ------------------------------------------------------------------------------- + + +def run_all(rec: Recorder, tmp: Path, seeds: range) -> None: + for name in DOCUMENTS: + rec.scenario = f"document:{name}" + _guard(rec, lambda n=name: run_document(rec, n, tmp)) + for name in DOCUMENTS: + for prefix in GROUP_PREFIXES: + for flow in GROUP_FLOWS: + rec.scenario = f"group:{name}:{prefix or 'root'}:{flow}" + _guard(rec, lambda n=name, p=prefix, f=flow: run_group(rec, n, p, f, tmp)) + for name in SUBCLASSES: + for zarr_format in (2, 3): + rec.scenario = f"subclass:{name}:v{zarr_format}" + _guard(rec, lambda n=name, z=zarr_format: run_subclass(rec, n, z, tmp)) + for seed in seeds: + rec.scenario = f"program:{seed}" + _guard(rec, lambda s=seed: run_program(rec, s, tmp)) + shutil.rmtree(tmp / f"program-{seed}", ignore_errors=True) + + +def _guard(rec: Recorder, fn: Any) -> None: + rec.step("scenario", fn) + + +__all__ = ["Recorder", "dump_pickles", "load_pickles", "run_all"] diff --git a/tools/compat/diff.py b/tools/compat/diff.py new file mode 100644 index 0000000000..d4d53b2056 --- /dev/null +++ b/tools/compat/diff.py @@ -0,0 +1,123 @@ +""" +Compare two runs of the compatibility scenarios. + + python diff.py OLD.json NEW.json [--out DETAILS.json] [--examples N] + +Each difference is classed: + +- `value`: a step returned something else, or raised where it returned (or the reverse, + unless it is an `added` one); +- `added`: a step raised `AttributeError` or `TypeError` in the old run and returned in the + new one, as a call of something the old version lacks does; +- `message`: a step raised the same exception with another message; +- `warnings`: a step behaved the same but warned differently; +- `internal`: a step that looks at private state (its label holds `internal:`); +- `steps`: a scenario ran other steps (the first one that differs is reported). +""" + +from __future__ import annotations + +import argparse +import json +import re +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +_KIND = re.compile(r"\d+|\(.*|\[.*|\{.*") + + +def classify(old: dict[str, Any], new: dict[str, Any]) -> str | None: + if "internal:" in old["label"]: + same = {k: v for k, v in old.items() if k != "warnings"} == { + k: v for k, v in new.items() if k != "warnings" + } + return None if same else "internal" + if "raises" in old and "raises" in new: + if old["raises"] != new["raises"]: + return "value" + if old["message"] != new["message"]: + return "message" + elif "raises" in old: + added = old["raises"].rsplit(".", 1)[-1] in ("AttributeError", "TypeError") + return "added" if added else "value" + elif "raises" in new or old["value"] != new["value"]: + return "value" + if old.get("warnings") != new.get("warnings"): + return "warnings" + return None + + +def kind_of(label: str) -> str: + return ":".join(p for p in _KIND.sub("", label).split(":") if p and p != "h") + + +def compare( + old_events: list[dict[str, Any]], new_events: list[dict[str, Any]] +) -> list[dict[str, Any]]: + by_scenario: dict[str, list[list[dict[str, Any]]]] = defaultdict(lambda: [[], []]) + for side, events in enumerate((old_events, new_events)): + for event in events: + by_scenario[event["scenario"]][side].append(event) + found = [] + for scenario, (old, new) in by_scenario.items(): + for i in range(max(len(old), len(new))): + if i >= len(old) or i >= len(new) or old[i]["label"] != new[i]["label"]: + found.append( + { + "class": "steps", + "scenario": scenario, + "kind": "steps", + "old": old[i] if i < len(old) else None, + "new": new[i] if i < len(new) else None, + } + ) + break + cls = classify(old[i], new[i]) + if cls is not None: + found.append( + { + "class": cls, + "scenario": scenario, + "kind": f"{scenario.split(':', 1)[0]}:{kind_of(old[i]['label'])}", + "old": old[i], + "new": new[i], + } + ) + return found + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("old", type=Path) + parser.add_argument("new", type=Path) + parser.add_argument("--out", type=Path) + parser.add_argument("--examples", type=int, default=1) + args = parser.parse_args() + old = json.loads(args.old.read_text()) + new = json.loads(args.new.read_text()) + found = compare(old["events"], new["events"]) + print(f"{old['zarr']} -> {new['zarr']}: {len(old['events'])} steps, {len(found)} differ") + for cls, n in Counter(f["class"] for f in found).most_common(): + print(f" {cls}: {n}") + groups: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) + for f in found: + groups[f["class"], f["kind"]].append(f) + for (cls, kind), items in sorted(groups.items(), key=lambda kv: (kv[0][0], -len(kv[1]))): + print(f"\n[{cls}] {kind} x{len(items)} in {len({f['scenario'] for f in items})} scenarios") + for f in items[: args.examples]: + print(f" {f['scenario']}") + for side in ("old", "new"): + event = f[side] + text = ( + "-" + if event is None + else json.dumps({k: v for k, v in event.items() if k != "scenario"}) + ) + print(f" {side}: {text[:600]}") + if args.out is not None: + args.out.write_text(json.dumps(found, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/tools/compat/run.py b/tools/compat/run.py new file mode 100644 index 0000000000..449175eb3b --- /dev/null +++ b/tools/compat/run.py @@ -0,0 +1,51 @@ +""" +Run the compatibility scenarios under one zarr source tree. + + PYTHONPATH=SRC python run.py SRC OUT.json --tmp DIR [--seeds N] [--dump-pickles DIR --stores DIR] + PYTHONPATH=SRC python run.py SRC OUT.json --tmp DIR --load-pickles DIR + +`SRC` is the directory that holds the `zarr` package. Put it on `PYTHONPATH`, which +comes before an installed zarr; the run stops unless zarr was imported from `SRC`. +`--tmp` is wiped first; give both runs the same path, so the paths they record agree. +""" + +from __future__ import annotations + +import argparse +import json +import shutil +from pathlib import Path + +import compat_scenarios as scenarios + +import zarr + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("src", type=Path) + parser.add_argument("out", type=Path) + parser.add_argument("--tmp", type=Path, required=True) + parser.add_argument("--seeds", type=int, default=200) + parser.add_argument("--dump-pickles", type=Path) + parser.add_argument("--stores", type=Path) + parser.add_argument("--load-pickles", type=Path) + args = parser.parse_args() + + if not Path(zarr.__file__).resolve().is_relative_to(args.src.resolve()): + raise SystemExit(f"imported {zarr.__file__}, not zarr from {args.src}") + + shutil.rmtree(args.tmp, ignore_errors=True) + args.tmp.mkdir(parents=True) + rec = scenarios.Recorder(args.tmp) + if args.dump_pickles is not None: + scenarios.dump_pickles(args.dump_pickles, args.stores) + elif args.load_pickles is not None: + scenarios.load_pickles(rec, args.load_pickles) + else: + scenarios.run_all(rec, args.tmp, range(args.seeds)) + args.out.write_text(json.dumps({"zarr": zarr.__version__, "events": rec.events}, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/uv.lock b/uv.lock index 7efabdf939..19c44d745e 100644 --- a/uv.lock +++ b/uv.lock @@ -3862,6 +3862,7 @@ dev = [ { name = "towncrier" }, { name = "universal-pathlib" }, { name = "uv" }, + { name = "zarrista", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, ] docs = [ { name = "astroid" }, @@ -3914,6 +3915,9 @@ test = [ { name = "pytest-xdist" }, { name = "uv" }, ] +zarrista-tests = [ + { name = "zarrista", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, +] [package.metadata] requires-dist = [ @@ -3966,6 +3970,7 @@ dev = [ { name = "towncrier", specifier = "==26.9.0" }, { name = "universal-pathlib" }, { name = "uv", specifier = "==0.13.7" }, + { name = "zarrista", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'x86_64'", specifier = "==0.1.0" }, ] docs = [ { name = "astroid", specifier = "==4.3.4" }, @@ -4016,3 +4021,43 @@ test = [ { name = "pytest-xdist", specifier = "==3.8.0" }, { name = "uv", specifier = "==0.13.7" }, ] +zarrista-tests = [{ name = "zarrista", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'x86_64'", specifier = "==0.1.0" }] + +[[package]] +name = "zarr-metadata" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7f/5d/5f1778697e0022d5cf7b215554a96827949a1d065b51913059b83b770ab3/zarr_metadata-0.9.0.tar.gz", hash = "sha256:7c7612ccb0177f2d1abb05cc38cdb89a54f31558edccf78d848a1c68d95415f7", size = 616077, upload-time = "2026-11-16T13:12:44.238Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/35/26/c1eb0a10cbbe9cc7d759ee66261f2461f09e964359dd4d3e6a0c74824bba/zarr_metadata-0.9.0-py3-none-any.whl", hash = "sha256:61714b08a7eacd4bef4e1ccc485e331de2ac5b7afda624094a711e474641338a", size = 339074, upload-time = "2026-11-16T13:12:42.616Z" }, +] + +[[package]] +name = "zarrista" +version = "0.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "zarr-metadata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d7/c8/0f2c439bf922685b7febd3add98093e778d9f00f53bc03a1d9fdcc906ce3/zarrista-0.1.0.tar.gz", hash = "sha256:6b2a7a05a4abb062824cee8fad023c6b34041b73b600733ea4c1404fd243a669", size = 375969, upload-time = "2026-08-13T14:44:45.517Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/8a/d2d3a23d19168d8d034cdda5b512344558e8c667bcce1b75473effa1f550/zarrista-0.1.0-cp311-abi3-macosx_10_12_x86_64.whl", hash = "sha256:13791ea7aa09e6b928b735c098c6e233e722543c9e60393ffc9d9db2992d093b", size = 17062569, upload-time = "2026-08-13T14:44:03.419Z" }, + { url = "https://files.pythonhosted.org/packages/41/d8/f37480ebc669af91ebab0b01ab649413446bd5cce365f3f50b71d05be2af/zarrista-0.1.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:28ea1359ec791e84e1438e38e3047a964a3e7d59f56f122255a44ec2b368f33f", size = 15493396, upload-time = "2026-08-13T14:44:06.36Z" }, + { url = "https://files.pythonhosted.org/packages/03/99/3ab5bb73c926b00a11369786ff064c4976c8b31c696c072f9a7c8a585eab/zarrista-0.1.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:68f8a795ddb58a8ce1a19b401ce1bfae8acd3925edcd68f29e1a355ba495dced", size = 16911884, upload-time = "2026-08-13T14:44:08.875Z" }, + { url = "https://files.pythonhosted.org/packages/f0/48/3d07340e3256b2cdf441b883da4fd2f7ab89d4894da94a4c627ba8b2f9eb/zarrista-0.1.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:a2840000a75fc8367bf44e751c0ef2200138c31c6d859ad03a1dc27059293153", size = 17647323, upload-time = "2026-08-13T14:44:11.705Z" }, + { url = "https://files.pythonhosted.org/packages/ce/0f/54ac44214733a8a1f566466506da006941f53aff0dd6ba53f0e09b6173ce/zarrista-0.1.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b4962e0b3ff39021be8ca6d49ca53e1cffc72e116bf5769d8930c9206341c2c0", size = 23404364, upload-time = "2026-08-13T14:44:14.684Z" }, + { url = "https://files.pythonhosted.org/packages/b9/3c/b362387ddf18e5adbce335f0ad1c9ec5935a66cf2e92d032e58e6e0327b7/zarrista-0.1.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85a5a4f719e0ba5c093a7a427748bd2eaf89bbe1e3e1146f2017d41baff7a2d2", size = 24328123, upload-time = "2026-08-13T14:44:17.651Z" }, + { url = "https://files.pythonhosted.org/packages/af/2e/59f3ab896f5a8c76a3d009c40015a32660b1b05b0ff055efcee3aa977caa/zarrista-0.1.0-cp311-abi3-win_amd64.whl", hash = "sha256:5723fc1a4960392ba220ae17dcf8830805c653f86e9f1933396175062af0cb3d", size = 17155852, upload-time = "2026-08-13T14:44:20.224Z" }, + { url = "https://files.pythonhosted.org/packages/0f/fd/4cd858a7095e43e8fd8cefe4850b6caab3573ea5ad46a101c2dc4f331365/zarrista-0.1.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:73ea2e4944d4c5e02159d49ac1bf0d5c35d42022d3a274435e9059cec4d42105", size = 3394236, upload-time = "2026-08-13T14:44:22.67Z" }, + { url = "https://files.pythonhosted.org/packages/af/85/932c0802c4074f1aa3853f446232130324cab20f1ef2b561ecc45c897e1b/zarrista-0.1.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:2f6d47e268c8a4b0bdbed408b90634ecaa46a4f17b101eb41f8502f4a681e682", size = 17105288, upload-time = "2026-08-13T14:44:24.621Z" }, + { url = "https://files.pythonhosted.org/packages/8c/56/c0a18f2958572391eaee9334ae1f613aef61779ac1cfd8f91b962f295bf0/zarrista-0.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e4d86ad3c3f25179ed9187522d529fe41c78baef9d3d714526a4f8f737c37e64", size = 15452920, upload-time = "2026-08-13T14:44:28.012Z" }, + { url = "https://files.pythonhosted.org/packages/c8/86/0e4621fc185475de7fece084e3288733bfcc9d50a2e6690b189be739b3b3/zarrista-0.1.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:c60d98070920173e239bdd4ac2c21cb53807e8672b16e97674b6b843b48af0bc", size = 16894574, upload-time = "2026-08-13T14:44:31.03Z" }, + { url = "https://files.pythonhosted.org/packages/af/29/fbd4773a316cc6e3a222f0a549c5cae563a6cc72c2a67b492592c2eb3836/zarrista-0.1.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:2d4e8ed028a016b88a680e37476436d89bc044a65cc6052b7a3847ea360dd676", size = 17634738, upload-time = "2026-08-13T14:44:33.816Z" }, + { url = "https://files.pythonhosted.org/packages/47/3f/4202f4b11d2629c100ca5801dcf806826779db4eb925ff9e4d05658529a2/zarrista-0.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:96706a3acb1c1e623c85f08cc325ab74ade02a9bf6397a644040d50e1033d414", size = 23388185, upload-time = "2026-08-13T14:44:36.867Z" }, + { url = "https://files.pythonhosted.org/packages/e8/96/f2eb1d63d32efa2d11237e9ba3ca7b1b93f87c987bc6dce90d75657a7d55/zarrista-0.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5c2c29591f49ace61e54721a921ee957ba463a6d22848df32c901cd45df1bc70", size = 24315851, upload-time = "2026-08-13T14:44:40.01Z" }, + { url = "https://files.pythonhosted.org/packages/a2/b2/f8029969d8db3ffc886cc4fbda5eca01dec7b78a6cc8e44af3103c3c30c1/zarrista-0.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:58b15682404c61bb53e10c8a17202762b43702c3fe99c9b6ea05be256113bfdd", size = 17122744, upload-time = "2026-08-13T14:44:43.036Z" }, +]