diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 5690fe7d87..f6162d2819 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -173,6 +173,48 @@ jobs: run: | just doctest + third-party-codecs: + name: Codecs from other packages + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 # required for hatch version discovery + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: '3.13' + cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + - name: Install Hatch + run: python -m pip install hatch==1.16.5 + - name: Install just + uses: extractions/setup-crate@7577c1bdf2d95e6d65d532788f35ed79d4b1dda2 # v2.0.1 + with: + repo: casey/just + version: 1.58.0 + - name: Set Up Hatch Env + run: | + HATCH_ENV=third-party-codecs just setup + # The tests skip a package that is missing; here a missing package fails the job, + # as does a zarr from PyPI in place of this checkout (zarrs requires zarr). + - name: Check the packages import + run: | + hatch run third-party-codecs:python -c " + import importlib, os, pathlib, zarr + src = pathlib.Path(os.environ['GITHUB_WORKSPACE'], 'src').resolve() + assert pathlib.Path(zarr.__file__).resolve().is_relative_to(src), zarr.__file__ + from tests.test_codecs.test_third_party_codecs import CASES + for case in CASES: + for module in case.requires: + importlib.import_module(module) + " + - name: Run Tests + run: | + just third-party-codecs -n auto -rs + benchmarks: name: Benchmark smoke test runs-on: ubuntu-latest diff --git a/Justfile b/Justfile index df96003eef..88c2200a44 100644 --- a/Justfile +++ b/Justfile @@ -60,6 +60,10 @@ hypothesis *args: hatch run {{ quote(hatch_env) }}:coverage run --source=src -m pytest -nauto --run-slow-hypothesis tests/test_properties.py tests/test_store/test_stateful* tests/test_array_stateful.py "$@" hatch run {{ quote(hatch_env) }}:coverage xml +# Run codecs and codec pipelines from other packages through zarr, in their own environment +third-party-codecs *args: + hatch run third-party-codecs:pytest tests/test_codecs/test_third_party_codecs.py "$@" + # Validate executable documentation code blocks doctest *args: hatch run doctest:pytest tests/test_docs.py -v "$@" diff --git a/pyproject.toml b/pyproject.toml index 20685f9bc0..d127068a09 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -221,6 +221,22 @@ features = ["gpu"] [[tool.hatch.envs.gputest.matrix]] python = ["3.12", "3.13"] +[tool.hatch.envs.third-party-codecs] +description = """Codecs and codec pipelines from other packages, for tests/test_codecs/test_third_party_codecs.py + +Not in the default test environments, so zarr's own tests gain no dependencies. +""" +template = "test" +# zarrs publishes no wheels for Python 3.14. +python = "3.13" +extra-dependencies = [ + "imagecodecs", + "pcodec", + # zfpy 1.0.1.post0 breaks `import numcodecs`: zarr-developers/numcodecs#893. + "zfpy!=1.0.1.post0", + "zarrs", +] + [tool.hatch.envs.upstream] template = 'test' python = "3.14" diff --git a/tests/test_codecs/buffer_kinds.py b/tests/test_codecs/buffer_kinds.py new file mode 100644 index 0000000000..eac753a5a0 --- /dev/null +++ b/tests/test_codecs/buffer_kinds.py @@ -0,0 +1,295 @@ +"""A fake device buffer kind, and round trips that run with a prototype `zarr.config` does not name. + +A read or write takes a `BufferPrototype`; `zarr.config` names another +(`buffer` / `ndbuffer`). The tests that use this module set the two to +different buffer kinds and check that only the given prototype's kind appears. + +The second buffer kind is a fake device kind that, like CuPy, refuses to be +mixed with host memory: host buffers refuse to hold its arrays, and its arrays +refuse to be combined with host arrays. So a buffer of the wrong kind fails +as it would on a GPU, instead of passing silently on the CPU. A test module +that uses the kind calls `install_fake_device_kind` from an autouse fixture. +""" + +from __future__ import annotations + +import warnings +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal, Self + +import numpy as np +import numpy.typing as npt + +from zarr.core.buffer import Buffer, BufferPrototype, core, cpu +from zarr.errors import ZarrUserWarning +from zarr.registry import fully_qualified_name, register_buffer, register_ndbuffer +from zarr.storage import MemoryStore + +if TYPE_CHECKING: + from collections.abc import Iterable + + import pytest + + import zarr + + +# --- a fake device buffer kind ---------------------------------------------------- + + +def _is_host_array(value: object) -> bool: + return isinstance(value, np.ndarray) and not isinstance(value, DeviceArray) and value.ndim > 0 + + +class DeviceArray(np.ndarray[Any, np.dtype[Any]]): + """An array in fake device memory: combining it with a host array raises, as in CuPy.""" + + def __array_ufunc__(self, ufunc: Any, method: str, *inputs: Any, **kwargs: Any) -> Any: + if any(_is_host_array(x) for x in inputs): + raise TypeError(f"{ufunc} mixes host and device arrays") + args = [x.view(np.ndarray) if isinstance(x, DeviceArray) else x for x in inputs] + if "out" in kwargs: + kwargs["out"] = tuple( + o.view(np.ndarray) if isinstance(o, DeviceArray) else o for o in kwargs["out"] + ) + result = getattr(ufunc, method)(*args, **kwargs) + return result.view(DeviceArray) if isinstance(result, np.ndarray) else result + + def __array_function__(self, func: Any, types: Any, args: Any, kwargs: Any) -> Any: + flat = [a for arg in args for a in (arg if isinstance(arg, list | tuple) else [arg])] + if any(_is_host_array(a) for a in flat): + raise TypeError(f"{func.__name__} mixes host and device arrays") + return super().__array_function__(func, types, args, kwargs) + + +def _to_device(array: npt.ArrayLike) -> Any: + """Copy `array` to fake device memory, as `cupy.asarray` copies a host array.""" + return np.array(array, copy=True).view(DeviceArray) + + +def to_host(array: Any) -> npt.NDArray[Any]: + """Copy a fake device array to host memory, as `cupy.asnumpy` does.""" + return np.array(array.view(np.ndarray), copy=True) + + +class DeviceBuffer(core.Buffer): + """A `Buffer` in fake device memory, modeled on `zarr.core.buffer.gpu.Buffer`.""" + + def __init__(self, array_like: Any) -> None: + data: Any = array_like if isinstance(array_like, DeviceArray) else _to_device(array_like) + super().__init__(data) + + @classmethod + def create_zero_length(cls) -> Self: + return cls(_to_device(np.array([], dtype="B"))) + + @classmethod + def from_buffer(cls, buffer: core.Buffer) -> Self: + if not isinstance(buffer.as_array_like(), DeviceArray): + # As `zarr.core.buffer.gpu.Buffer.from_buffer` does, by way of its constructor. + warnings.warn( + "a buffer from host memory takes the slow path", ZarrUserWarning, stacklevel=2 + ) + return cls(buffer.as_array_like()) + + @classmethod + def from_bytes(cls, bytes_like: Any) -> Self: + return cls(_to_device(np.frombuffer(bytes_like, dtype="B"))) + + def as_numpy_array(self) -> npt.NDArray[Any]: + return to_host(self._data) + + def combine(self, others: Iterable[core.Buffer]) -> Self: + data: list[Any] = [self._data] + for other in others: + if not isinstance(other.as_array_like(), DeviceArray): + # As `zarr.core.buffer.gpu.Buffer.combine` does, by way of its constructor. + warnings.warn( + "combining host memory takes the slow path", ZarrUserWarning, stacklevel=2 + ) + data.append(DeviceBuffer(other.as_array_like())._data) + return self.__class__(np.concatenate(data)) + + +class DeviceNDBuffer(core.NDBuffer): + """An `NDBuffer` in fake device memory, modeled on `zarr.core.buffer.gpu.NDBuffer`.""" + + def __init__(self, array: Any) -> None: + data: Any = array if isinstance(array, DeviceArray) else _to_device(array) + super().__init__(data) + + @classmethod + def create( + cls, + *, + shape: Iterable[int], + dtype: npt.DTypeLike, + order: Literal["C", "F"] = "C", + fill_value: Any | None = None, + ) -> Self: + ret = cls(_to_device(np.empty(tuple(shape), dtype=dtype, order=order))) + if fill_value is not None: + ret.fill(fill_value) + return ret + + @classmethod + def empty( + cls, shape: tuple[int, ...], dtype: npt.DTypeLike, order: Literal["C", "F"] = "C" + ) -> Self: + return cls(_to_device(np.empty(shape, dtype=dtype, order=order))) + + @classmethod + def from_numpy_array(cls, array_like: npt.ArrayLike) -> Self: + return cls(_to_device(array_like)) + + def as_numpy_array(self) -> npt.NDArray[Any]: + return to_host(self._data) + + def __getitem__(self, key: Any) -> Self: + return self.__class__(self._data.__getitem__(key)) + + def __setitem__(self, key: Any, value: Any) -> None: + if isinstance(value, core.NDBuffer): + value = value.as_ndarray_like() + # Like CuPy, assigning a host array copies it to the device. + self._data.__setitem__(key, value.view(DeviceArray) if _is_host_array(value) else value) + + +DEVICE_PROTOTYPE = BufferPrototype(buffer=DeviceBuffer, nd_buffer=DeviceNDBuffer) +DEVICE_CONFIG = { + "buffer": fully_qualified_name(DeviceBuffer), + "ndbuffer": fully_qualified_name(DeviceNDBuffer), +} + + +class UnusableBuffer(cpu.Buffer): + """A buffer kind that cannot be built, so a buffer made from `zarr.config` fails.""" + + def __init__(self, array_like: Any) -> None: + raise RuntimeError("a buffer was built from zarr.config") + + +class UnusableNDBuffer(cpu.NDBuffer): + """An array buffer kind that cannot be built, so a buffer made from `zarr.config` fails.""" + + def __init__(self, array: Any) -> None: + raise RuntimeError("an array buffer was built from zarr.config") + + +UNUSABLE_CONFIG = { + "buffer": fully_qualified_name(UnusableBuffer), + "ndbuffer": fully_qualified_name(UnusableNDBuffer), +} + + +def install_fake_device_kind(monkeypatch: pytest.MonkeyPatch) -> None: + """Make host buffers refuse device arrays, as NumPy refuses CuPy arrays. + + Also registers this module's buffer kinds so `zarr.config` can name them. + """ + register_buffer(DeviceBuffer) + register_ndbuffer(DeviceNDBuffer) + register_buffer(UnusableBuffer) + register_ndbuffer(UnusableNDBuffer) + + def refuse(value: object) -> None: + if isinstance(value, DeviceArray | DeviceBuffer | DeviceNDBuffer): + raise TypeError("a host buffer was given device memory") + + buffer_init = cpu.Buffer.__init__ + nd_buffer_init = cpu.NDBuffer.__init__ + nd_buffer_setitem = cpu.NDBuffer.__setitem__ + + def host_buffer_init(self: cpu.Buffer, array_like: Any) -> None: + refuse(array_like) + buffer_init(self, array_like) + + def host_nd_buffer_init(self: cpu.NDBuffer, array: Any) -> None: + refuse(array) + nd_buffer_init(self, array) + + def host_nd_buffer_setitem(self: cpu.NDBuffer, key: Any, value: Any) -> None: + refuse(value._data if isinstance(value, core.NDBuffer) else value) + nd_buffer_setitem(self, key, value) + + monkeypatch.setattr(cpu.Buffer, "__init__", host_buffer_init) + monkeypatch.setattr(cpu.NDBuffer, "__init__", host_nd_buffer_init) + monkeypatch.setattr(cpu.NDBuffer, "__setitem__", host_nd_buffer_setitem) + + +# --- the prototype / config directions, and a round trip through each -------------- + + +@dataclass(frozen=True) +class Direction: + """A prototype to call with, and the buffer kind `zarr.config` names.""" + + name: str + prototype: BufferPrototype + buffer_config: dict[str, str] + array_type: type[np.ndarray[Any, Any]] + + +DIRECTIONS = ( + Direction("config-device-call-host", cpu.buffer_prototype, DEVICE_CONFIG, np.ndarray), + Direction("config-host-call-device", DEVICE_PROTOTYPE, {}, DeviceArray), + # The configured prototype, as in GPU mode before this change: nothing to convert. + Direction("config-device-call-device", DEVICE_PROTOTYPE, DEVICE_CONFIG, DeviceArray), +) +# `zarr.config` names a buffer kind that cannot be built. +UNUSABLE_CONFIG_DIRECTIONS = ( + Direction("config-unusable-call-host", cpu.buffer_prototype, UNUSABLE_CONFIG, np.ndarray), + Direction("config-unusable-call-device", DEVICE_PROTOTYPE, UNUSABLE_CONFIG, DeviceArray), +) +PIPELINES = ( + "zarr.core.codec_pipeline.BatchedCodecPipeline", + "zarr.core.codec_pipeline.FusedCodecPipeline", +) + + +class RecordingStore(MemoryStore): + """A `MemoryStore` that records the type of every chunk value written to it.""" + + def __init__(self) -> None: + super().__init__() + self.chunk_value_types: set[type[Buffer]] = set() + + def _record(self, key: str, value: Buffer) -> None: + if not key.endswith((".json", ".zarray", ".zattrs", ".zgroup")): + self.chunk_value_types.add(type(value)) + + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: + self._record(key, value) + await super().set(key, value, byte_range) + + def set_sync(self, key: str, value: Buffer) -> None: + self._record(key, value) + super().set_sync(key, value) + + +async def round_trip( + array: zarr.Array[Any], prototype: BufferPrototype +) -> list[tuple[Any, npt.NDArray[Any]]]: + """Write part of the empty (8, 8) `array`, then all of it, then part again; read all and part back. + + Returns each read result with its expected value. The partial writes and read + each cross chunk boundaries, and, with 2x2 chunks in 4x4 shards, shard + boundaries; the first lands in absent chunks or shards. The values are + `arange(64)` and a patch of -7, cast to the array's data type. + """ + async_array = array._async_array + dtype = array.dtype + region = (slice(1, 5), slice(3, 6)) + patch = np.full((4, 3), -7, dtype="int32").astype(dtype) + expected = np.arange(64, dtype="int32").reshape(8, 8).astype(dtype) + await async_array.setitem(region, patch, prototype=prototype) + await async_array.setitem((slice(None), slice(None)), expected, prototype=prototype) + await async_array.setitem(region, patch, prototype=prototype) + expected[1:5, 3:6] = patch + full = await async_array.getitem((slice(None), slice(None)), prototype=prototype) + part = await async_array.getitem((slice(1, 6), slice(2, 7)), prototype=prototype) + return [(full, expected), (part, expected[1:6, 2:7])] + + +def host(array: Any) -> npt.NDArray[Any]: + """`array` in host memory, copied there if it is a fake device array.""" + return to_host(array) if isinstance(array, DeviceArray) else np.asarray(array) diff --git a/tests/test_codecs/test_buffer_prototype.py b/tests/test_codecs/test_buffer_prototype.py index 234e0a0d10..6a76cc3bc2 100644 --- a/tests/test_codecs/test_buffer_prototype.py +++ b/tests/test_codecs/test_buffer_prototype.py @@ -5,22 +5,18 @@ check that only the given prototype's kind appears: in the array a read returns, in the values the store receives, and in the arrays each codec sees. -The second buffer kind is a fake device kind that, like CuPy, refuses to be -mixed with host memory: host buffers refuse to hold its arrays, and its arrays -refuse to be combined with host arrays. So a buffer of the wrong kind fails -here as it would on a GPU, instead of passing silently on the CPU. +The second buffer kind is the fake device kind in `tests.test_codecs.buffer_kinds`, +which, like CuPy, refuses to be mixed with host memory. """ from __future__ import annotations import asyncio -import warnings from dataclasses import dataclass, field, replace -from typing import TYPE_CHECKING, Any, Literal, Self +from typing import TYPE_CHECKING, Any, Literal import numcodecs import numpy as np -import numpy.typing as npt import pytest import zarr @@ -35,250 +31,39 @@ from zarr.codecs import numcodecs as zarr_numcodecs from zarr.codecs._v2 import V2Codec from zarr.core.array_spec import ArrayConfig, ArraySpec -from zarr.core.buffer import Buffer, BufferPrototype, NDBuffer, core, cpu, default_buffer_prototype +from zarr.core.buffer import Buffer, BufferPrototype, NDBuffer, cpu, default_buffer_prototype from zarr.core.chunk_utils import ChunkTransform, scatter_chunk from zarr.core.codec_pipeline import AsyncChunkTransform, BatchedCodecPipeline from zarr.core.config import config from zarr.core.dtype import get_data_type_from_native_dtype -from zarr.errors import ZarrUserWarning -from zarr.registry import fully_qualified_name, register_buffer, register_ndbuffer from zarr.storage import MemoryStore +from .buffer_kinds import ( + DEVICE_PROTOTYPE, + DIRECTIONS, + PIPELINES, + UNUSABLE_CONFIG_DIRECTIONS, + Direction, + RecordingStore, + host, + install_fake_device_kind, + round_trip, +) + if TYPE_CHECKING: from collections.abc import Iterable from zarr.abc.codec import Codec -# --- a fake device buffer kind ---------------------------------------------------- - - -def _is_host_array(value: object) -> bool: - return isinstance(value, np.ndarray) and not isinstance(value, DeviceArray) and value.ndim > 0 - - -class DeviceArray(np.ndarray[Any, np.dtype[Any]]): - """An array in fake device memory: combining it with a host array raises, as in CuPy.""" - - def __array_ufunc__(self, ufunc: Any, method: str, *inputs: Any, **kwargs: Any) -> Any: - if any(_is_host_array(x) for x in inputs): - raise TypeError(f"{ufunc} mixes host and device arrays") - args = [x.view(np.ndarray) if isinstance(x, DeviceArray) else x for x in inputs] - if "out" in kwargs: - kwargs["out"] = tuple( - o.view(np.ndarray) if isinstance(o, DeviceArray) else o for o in kwargs["out"] - ) - result = getattr(ufunc, method)(*args, **kwargs) - return result.view(DeviceArray) if isinstance(result, np.ndarray) else result - - def __array_function__(self, func: Any, types: Any, args: Any, kwargs: Any) -> Any: - flat = [a for arg in args for a in (arg if isinstance(arg, list | tuple) else [arg])] - if any(_is_host_array(a) for a in flat): - raise TypeError(f"{func.__name__} mixes host and device arrays") - return super().__array_function__(func, types, args, kwargs) - - -def _to_device(array: npt.ArrayLike) -> Any: - """Copy `array` to fake device memory, as `cupy.asarray` copies a host array.""" - return np.array(array, copy=True).view(DeviceArray) - - -def _to_host(array: Any) -> npt.NDArray[Any]: - """Copy a fake device array to host memory, as `cupy.asnumpy` does.""" - return np.array(array.view(np.ndarray), copy=True) - - -class DeviceBuffer(core.Buffer): - """A `Buffer` in fake device memory, modeled on `zarr.core.buffer.gpu.Buffer`.""" - - def __init__(self, array_like: Any) -> None: - data: Any = array_like if isinstance(array_like, DeviceArray) else _to_device(array_like) - super().__init__(data) - - @classmethod - def create_zero_length(cls) -> Self: - return cls(_to_device(np.array([], dtype="B"))) - - @classmethod - def from_buffer(cls, buffer: core.Buffer) -> Self: - if not isinstance(buffer.as_array_like(), DeviceArray): - # As `zarr.core.buffer.gpu.Buffer.from_buffer` does, by way of its constructor. - warnings.warn( - "a buffer from host memory takes the slow path", ZarrUserWarning, stacklevel=2 - ) - return cls(buffer.as_array_like()) - - @classmethod - def from_bytes(cls, bytes_like: Any) -> Self: - return cls(_to_device(np.frombuffer(bytes_like, dtype="B"))) - - def as_numpy_array(self) -> npt.NDArray[Any]: - return _to_host(self._data) - - def combine(self, others: Iterable[core.Buffer]) -> Self: - data: list[Any] = [self._data] - for other in others: - if not isinstance(other.as_array_like(), DeviceArray): - # As `zarr.core.buffer.gpu.Buffer.combine` does, by way of its constructor. - warnings.warn( - "combining host memory takes the slow path", ZarrUserWarning, stacklevel=2 - ) - data.append(DeviceBuffer(other.as_array_like())._data) - return self.__class__(np.concatenate(data)) - - -class DeviceNDBuffer(core.NDBuffer): - """An `NDBuffer` in fake device memory, modeled on `zarr.core.buffer.gpu.NDBuffer`.""" - - def __init__(self, array: Any) -> None: - data: Any = array if isinstance(array, DeviceArray) else _to_device(array) - super().__init__(data) - - @classmethod - def create( - cls, - *, - shape: Iterable[int], - dtype: npt.DTypeLike, - order: Literal["C", "F"] = "C", - fill_value: Any | None = None, - ) -> Self: - ret = cls(_to_device(np.empty(tuple(shape), dtype=dtype, order=order))) - if fill_value is not None: - ret.fill(fill_value) - return ret - - @classmethod - def empty( - cls, shape: tuple[int, ...], dtype: npt.DTypeLike, order: Literal["C", "F"] = "C" - ) -> Self: - return cls(_to_device(np.empty(shape, dtype=dtype, order=order))) - - @classmethod - def from_numpy_array(cls, array_like: npt.ArrayLike) -> Self: - return cls(_to_device(array_like)) - - def as_numpy_array(self) -> npt.NDArray[Any]: - return _to_host(self._data) - - def __getitem__(self, key: Any) -> Self: - return self.__class__(self._data.__getitem__(key)) - - def __setitem__(self, key: Any, value: Any) -> None: - if isinstance(value, core.NDBuffer): - value = value.as_ndarray_like() - # Like CuPy, assigning a host array copies it to the device. - self._data.__setitem__(key, value.view(DeviceArray) if _is_host_array(value) else value) - - -DEVICE_PROTOTYPE = BufferPrototype(buffer=DeviceBuffer, nd_buffer=DeviceNDBuffer) -DEVICE_CONFIG = { - "buffer": fully_qualified_name(DeviceBuffer), - "ndbuffer": fully_qualified_name(DeviceNDBuffer), -} - - -class UnusableBuffer(cpu.Buffer): - """A buffer kind that cannot be built, so a buffer made from `zarr.config` fails.""" - - def __init__(self, array_like: Any) -> None: - raise RuntimeError("a buffer was built from zarr.config") - - -class UnusableNDBuffer(cpu.NDBuffer): - """An array buffer kind that cannot be built, so a buffer made from `zarr.config` fails.""" - - def __init__(self, array: Any) -> None: - raise RuntimeError("an array buffer was built from zarr.config") - - -UNUSABLE_CONFIG = { - "buffer": fully_qualified_name(UnusableBuffer), - "ndbuffer": fully_qualified_name(UnusableNDBuffer), -} - - @pytest.fixture(autouse=True) def _host_refuses_device_arrays(monkeypatch: pytest.MonkeyPatch) -> None: - """Make host buffers refuse device arrays, as NumPy refuses CuPy arrays. - - Also registers this module's buffer kinds so `zarr.config` can name them. - """ - register_buffer(DeviceBuffer) - register_ndbuffer(DeviceNDBuffer) - register_buffer(UnusableBuffer) - register_ndbuffer(UnusableNDBuffer) - - def refuse(value: object) -> None: - if isinstance(value, DeviceArray | DeviceBuffer | DeviceNDBuffer): - raise TypeError("a host buffer was given device memory") - - buffer_init = cpu.Buffer.__init__ - nd_buffer_init = cpu.NDBuffer.__init__ - nd_buffer_setitem = cpu.NDBuffer.__setitem__ - - def host_buffer_init(self: cpu.Buffer, array_like: Any) -> None: - refuse(array_like) - buffer_init(self, array_like) - - def host_nd_buffer_init(self: cpu.NDBuffer, array: Any) -> None: - refuse(array) - nd_buffer_init(self, array) - - def host_nd_buffer_setitem(self: cpu.NDBuffer, key: Any, value: Any) -> None: - refuse(value._data if isinstance(value, core.NDBuffer) else value) - nd_buffer_setitem(self, key, value) - - monkeypatch.setattr(cpu.Buffer, "__init__", host_buffer_init) - monkeypatch.setattr(cpu.NDBuffer, "__init__", host_nd_buffer_init) - monkeypatch.setattr(cpu.NDBuffer, "__setitem__", host_nd_buffer_setitem) - - -@dataclass(frozen=True) -class Direction: - """A prototype to call with, and the buffer kind `zarr.config` names.""" - - name: str - prototype: BufferPrototype - buffer_config: dict[str, str] - array_type: type[np.ndarray[Any, Any]] - - -DIRECTIONS = ( - Direction("config-device-call-host", cpu.buffer_prototype, DEVICE_CONFIG, np.ndarray), - Direction("config-host-call-device", DEVICE_PROTOTYPE, {}, DeviceArray), - # The configured prototype, as in GPU mode before this change: nothing to convert. - Direction("config-device-call-device", DEVICE_PROTOTYPE, DEVICE_CONFIG, DeviceArray), -) -PIPELINES = ( - "zarr.core.codec_pipeline.BatchedCodecPipeline", - "zarr.core.codec_pipeline.FusedCodecPipeline", -) + install_fake_device_kind(monkeypatch) # --- codecs of the shapes codecs from other packages take -------------------------- -class RecordingStore(MemoryStore): - """A `MemoryStore` that records the type of every chunk value written to it.""" - - def __init__(self) -> None: - super().__init__() - self.chunk_value_types: set[type[Buffer]] = set() - - def _record(self, key: str, value: Buffer) -> None: - if not key.endswith((".json", ".zarray", ".zattrs", ".zgroup")): - self.chunk_value_types.add(type(value)) - - async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: - self._record(key, value) - await super().set(key, value, byte_range) - - def set_sync(self, key: str, value: Buffer) -> None: - self._record(key, value) - super().set_sync(key, value) - - @dataclass(frozen=True) class RecordingCodec: """Records each direction it runs in, so a test can tell the codec was not skipped.""" @@ -538,31 +323,6 @@ def _create(store: MemoryStore, layout: Layout, chain: list[Codec]) -> zarr.Arra ) -async def _round_trip( - array: zarr.Array[Any], prototype: BufferPrototype -) -> list[tuple[Any, npt.NDArray[Any]]]: - """Write part of the empty `array`, then all of it, then part again; read all and part back. - - Returns each read result with its expected value. The partial writes and read - each cross inner-chunk and shard boundaries; the first lands in absent shards. - """ - async_array = array._async_array - region = (slice(1, 5), slice(3, 6)) - patch = np.full((4, 3), -7, dtype="int32") - expected = np.arange(64, dtype="int32").reshape(8, 8) - await async_array.setitem(region, patch, prototype=prototype) - await async_array.setitem((slice(None), slice(None)), expected, prototype=prototype) - await async_array.setitem(region, patch, prototype=prototype) - expected[1:5, 3:6] = -7 - full = await async_array.getitem((slice(None), slice(None)), prototype=prototype) - part = await async_array.getitem((slice(1, 6), slice(2, 7)), prototype=prototype) - return [(full, expected), (part, expected[1:6, 2:7])] - - -def _host(array: Any) -> npt.NDArray[Any]: - return _to_host(array) if isinstance(array, DeviceArray) else np.asarray(array) - - @pytest.mark.parametrize("pipeline", PIPELINES) @pytest.mark.parametrize(("direction", "layout", "chain"), _cases(DIRECTIONS, LAYOUT_CHAINS)) def test_codecs_use_the_given_prototype( @@ -578,10 +338,10 @@ def test_codecs_use_the_given_prototype( store = RecordingStore() with config.set({**direction.buffer_config, "codec_pipeline.path": pipeline}): array = _create(store, layout, codecs) - results = asyncio.run(_round_trip(array, direction.prototype)) + results = asyncio.run(round_trip(array, direction.prototype)) for got, expected in results: assert type(got) is direction.array_type - np.testing.assert_array_equal(_host(got), expected) + np.testing.assert_array_equal(host(got), expected) assert store.chunk_value_types == {direction.prototype.buffer} for codec in codecs: if isinstance(codec, RecordingCodec): @@ -616,11 +376,6 @@ def test_v2_codec_decodes_into_the_given_prototype(direction: Direction) -> None np.testing.assert_array_equal(decoded.as_numpy_array(), data) -# `zarr.config` names a buffer kind that cannot be built. -UNUSABLE_CONFIG_DIRECTIONS = ( - Direction("config-unusable-call-host", cpu.buffer_prototype, UNUSABLE_CONFIG, np.ndarray), - Direction("config-unusable-call-device", DEVICE_PROTOTYPE, UNUSABLE_CONFIG, DeviceArray), -) # Chains whose codecs all follow the prototype; the others read `zarr.config` by design. PROTOTYPE_LAYOUT_CHAINS = [ (layout, chain) @@ -643,10 +398,10 @@ def test_codecs_read_no_buffer_config( with config.set({"codec_pipeline.path": pipeline}): array = _create(store, layout, codecs) with config.set({**direction.buffer_config, "codec_pipeline.path": pipeline}): - results = asyncio.run(_round_trip(array, direction.prototype)) + results = asyncio.run(round_trip(array, direction.prototype)) for got, expected in results: assert type(got) is direction.array_type - np.testing.assert_array_equal(_host(got), expected) + np.testing.assert_array_equal(host(got), expected) assert store.chunk_value_types == {direction.prototype.buffer} diff --git a/tests/test_codecs/test_third_party_codecs.py b/tests/test_codecs/test_third_party_codecs.py new file mode 100644 index 0000000000..5eef880900 --- /dev/null +++ b/tests/test_codecs/test_third_party_codecs.py @@ -0,0 +1,379 @@ +"""Codecs and codec pipelines from other packages, given a prototype `zarr.config` does not name. + +Each case runs codecs or a codec pipeline from a package outside zarr through +the round trip in `tests.test_codecs.buffer_kinds`, with the fake device +buffer kind on one side of the call's prototype and `zarr.config`'s buffer +kind, or on both. The aim is to catch zarr changes that break those packages, +so the codecs are the packages' own, not stand-ins. + +The fake device array is an `np.ndarray` subclass in host memory, so it +refuses to be mixed with host arrays in NumPy calls, but C or Rust code that +reads its buffer takes it as host memory. With CuPy, numcodecs codecs and +zarrs fail where they read a device array directly, so those cases run with a +host prototype only (`Case.host_only`); imagecodecs' zarr 3 codecs copy to the +host themselves and run in every direction. zarrs ignores the prototype, so +its cases check that it stays compatible with zarr's `CodecPipeline` interface. + +The packages are optional: a case is skipped when its package is not +installed. The `third-party-codecs` hatch environment installs them. +""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal + +import numpy as np +import pytest + +import zarr +from zarr.codecs import BytesCodec, Crc32cCodec, ShardingCodec, TransposeCodec, ZstdCodec +from zarr.core.buffer import cpu +from zarr.core.config import config +from zarr.registry import get_pipeline_class +from zarr.storage import LocalStore + +from .buffer_kinds import ( + DIRECTIONS, + PIPELINES, + UNUSABLE_CONFIG_DIRECTIONS, + Direction, + RecordingStore, + host, + install_fake_device_kind, + round_trip, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + from pathlib import Path + + from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec, Codec + from zarr.abc.store import Store + + +@pytest.fixture(autouse=True) +def _host_refuses_device_arrays(monkeypatch: pytest.MonkeyPatch) -> None: + install_fake_device_kind(monkeypatch) + + +Layout = Literal["v3", "v3-sharded", "v3-nested-sharded", "v2"] +V3_LAYOUTS: tuple[Layout, ...] = ("v3", "v3-sharded", "v3-nested-sharded") +ZARRS_PIPELINE = "zarrs.ZarrsCodecPipeline" + + +@dataclass(frozen=True) +class V3Chain: + """A v3 codec chain, split as `create_array` takes it.""" + + filters: tuple[ArrayArrayCodec, ...] + serializer: ArrayBytesCodec + compressors: tuple[BytesBytesCodec, ...] + + def codecs(self) -> list[Codec]: + return [*self.filters, self.serializer, *self.compressors] + + +@dataclass(frozen=True) +class V2Codecs: + """A v2 array's numcodecs filters and compressor.""" + + filters: tuple[Any, ...] + compressor: Any + + +@dataclass(frozen=True) +class Case: + """Codecs from another package, or another package's codec pipeline, to run a round trip through. + + `requires` names the modules the case imports; it is skipped if one is + missing. `v3` and `v2` build the codecs for each format; `None` means the + case has no codecs of that format. `pipelines` are the codec pipelines to + run it under. A `host_only` case reads device arrays directly (numcodecs + codecs, zarrs' Rust code), which fails on CuPy whatever zarr does; the fake + device array is host memory underneath and would let it pass, so it runs + with a host prototype only. + """ + + name: str + requires: tuple[str, ...] + dtype: str + v3: Callable[[], V3Chain] | None + v2: Callable[[], V2Codecs] | None + pipelines: tuple[str, ...] = PIPELINES + host_only: bool = False + + def layouts(self) -> tuple[Layout, ...]: + return (*(V3_LAYOUTS if self.v3 else ()), *(("v2",) if self.v2 else ())) + + +# --- imagecodecs ------------------------------------------------------------------ +# `imagecodecs.zarr` holds zarr 3 codecs, registered with `zarr.registry.register_codec` +# by `imagecodecs.zarr.register_codecs`; `imagecodecs.numcodecs` holds numcodecs codecs, +# registered with numcodecs by `imagecodecs.numcodecs.register_codecs`. + +IMAGECODECS_ZARR_CODECS = ( + "delta", + "xor", + "byteshuffle", + "zstd", + "lz4", + "checksum", + "pcodec", + "zfp", + "blosc2", + "png", +) + + +def _register_imagecodecs() -> None: + import imagecodecs.numcodecs + import imagecodecs.zarr + + imagecodecs.zarr.register_codecs(IMAGECODECS_ZARR_CODECS, verbose=False) + imagecodecs.numcodecs.register_codecs(verbose=False) + + +def _imagecodecs_filters_and_compressors() -> V3Chain: + """Array-to-array and bytes-to-bytes codecs, around imagecodecs' byte shuffle.""" + from imagecodecs import zarr as icz + + _register_imagecodecs() + return V3Chain( + filters=(icz.Delta(), icz.Xor()), + serializer=icz.Byteshuffle(), + compressors=(icz.Zstd(), icz.Lz4(), icz.Checksum()), + ) + + +def _imagecodecs_pcodec() -> V3Chain: + from imagecodecs import zarr as icz + + _register_imagecodecs() + return V3Chain(filters=(), serializer=icz.Pcodec(), compressors=()) + + +def _imagecodecs_zfp() -> V3Chain: + from imagecodecs import zarr as icz + + _register_imagecodecs() + return V3Chain(filters=(), serializer=icz.Zfp(mode="reversible"), compressors=(icz.Blosc2(),)) + + +def _imagecodecs_png() -> V3Chain: + """An image codec, which encodes each 2-D chunk as an image.""" + from imagecodecs import zarr as icz + + _register_imagecodecs() + return V3Chain(filters=(), serializer=icz.Png(), compressors=()) + + +def _imagecodecs_numcodecs() -> V2Codecs: + """An imagecodecs numcodecs filter, for the 2x2 int32 chunks of a v2 array. + + It decodes a flat buffer, so it needs the chunk's data type and shape. One + filter only: imagecodecs' numcodecs filters encode to `bytes`, which a second + filter with a shape refuses. + """ + from imagecodecs import numcodecs as icn + + _register_imagecodecs() + return V2Codecs(filters=(icn.Delta(dtype=" V3Chain: + from zarr.codecs.numcodecs import PCodec + + return V3Chain(filters=(), serializer=PCodec(), compressors=()) + + +def _pcodec_v2() -> V2Codecs: + import numcodecs + + return V2Codecs(filters=(), compressor=numcodecs.PCodec()) + + +def _zfpy_config() -> dict[str, Any]: + """zfpy at full precision: lossless for the small integers in the round trip.""" + import zfpy + + return {"mode": zfpy.mode_fixed_precision, "precision": 64} + + +def _zfpy_v3() -> V3Chain: + from zarr.codecs.numcodecs import ZFPY + + return V3Chain(filters=(), serializer=ZFPY(**_zfpy_config()), compressors=()) + + +def _zfpy_v2() -> V2Codecs: + import numcodecs + + return V2Codecs(filters=(), compressor=numcodecs.ZFPY(**_zfpy_config())) + + +# --- zarrs, a codec pipeline ------------------------------------------------------- + + +def _zarrs_v3() -> V3Chain: + """zarr's codecs, which zarrs implements itself.""" + return V3Chain( + filters=(TransposeCodec(order=(1, 0)),), + serializer=BytesCodec(), + compressors=(ZstdCodec(), Crc32cCodec()), + ) + + +def _zarrs_v2() -> V2Codecs: + import numcodecs + + return V2Codecs(filters=(), compressor=numcodecs.Zlib()) + + +CASES = ( + Case( + "imagecodecs-filters-compressors", + ("imagecodecs",), + "int32", + _imagecodecs_filters_and_compressors, + None, + ), + Case("imagecodecs-pcodec", ("imagecodecs",), "int32", _imagecodecs_pcodec, None), + Case("imagecodecs-zfp", ("imagecodecs",), "float32", _imagecodecs_zfp, None), + Case("imagecodecs-png", ("imagecodecs",), "uint8", _imagecodecs_png, None), + Case( + "imagecodecs-numcodecs", + ("imagecodecs",), + "int32", + None, + _imagecodecs_numcodecs, + host_only=True, + ), + Case("numcodecs-pcodec", ("pcodec",), "int32", _pcodec_v3, _pcodec_v2, host_only=True), + Case("numcodecs-zfpy", ("zfpy",), "float64", _zfpy_v3, _zfpy_v2, host_only=True), + Case( + "zarrs", + ("zarrs",), + "int32", + _zarrs_v3, + _zarrs_v2, + pipelines=(ZARRS_PIPELINE,), + host_only=True, + ), +) + + +def _cases(directions: Iterable[Direction]) -> list[Any]: + """The (case, layout, pipeline, direction) combinations each case can run in.""" + return [ + pytest.param( + case, + layout, + pipeline, + direction, + id=f"{case.name}-{layout}-{pipeline.rsplit('.', 1)[-1]}-{direction.name}", + ) + for case in CASES + for layout in case.layouts() + for pipeline in case.pipelines + for direction in directions + if not case.host_only or direction.prototype is cpu.buffer_prototype + ] + + +def _create(store: Store, layout: Layout, case: Case) -> zarr.Array[Any]: + """An (8, 8) array of the given layout, with 2x2 chunks inside 4x4 shards.""" + common: dict[str, Any] = {"shape": (8, 8), "dtype": case.dtype, "fill_value": 0} + if layout == "v2": + assert case.v2 is not None + v2 = case.v2() + return zarr.create_array( + store, + zarr_format=2, + chunks=(2, 2), + filters=list(v2.filters) or None, + compressors=v2.compressor, + **common, + ) + assert case.v3 is not None + chain = case.v3() + if layout == "v3": + return zarr.create_array( + store, + chunks=(2, 2), + filters=list(chain.filters), + serializer=chain.serializer, + compressors=list(chain.compressors), + **common, + ) + inner = chain.codecs() + if layout == "v3-nested-sharded": + inner = [ShardingCodec(chunk_shape=(1, 1), codecs=inner)] + return zarr.create_array( + store, + chunks=(4, 4), + serializer=ShardingCodec(chunk_shape=(2, 2), codecs=inner), + compressors=None, + **common, + ) + + +def _store(pipeline: str, tmp_path: Path) -> Store: + """A store the pipeline reads and writes itself: zarrs takes a local directory.""" + if pipeline == ZARRS_PIPELINE: + return LocalStore(tmp_path) + return RecordingStore() + + +def _round_trip_case( + case: Case, layout: Layout, pipeline: str, direction: Direction, tmp_path: Path +) -> None: + """Create the case's array, then run the round trip in `direction` and check what it returns. + + The read results must be the direction's array kind and hold the written + values; the values a `RecordingStore` receives must be its buffer kind. + """ + for module in case.requires: + pytest.importorskip(module) + store = _store(pipeline, tmp_path) + # zarrs falls back to zarr's own pipeline for arrays it cannot handle, unless strict. + pipeline_config = {"codec_pipeline.path": pipeline, "codec_pipeline.strict": True} + # The array's metadata is written with the configured kind, so create it first. + with config.set(pipeline_config): + array = _create(store, layout, case) + # A misspelled path would leave zarr's default pipeline in place. + assert type(array._async_array.codec_pipeline) is get_pipeline_class() + with config.set({**direction.buffer_config, **pipeline_config}): + results = asyncio.run(round_trip(array, direction.prototype)) + for got, expected in results: + assert type(got) is direction.array_type + np.testing.assert_array_equal(host(got), expected) + if isinstance(store, RecordingStore): + assert store.chunk_value_types == {direction.prototype.buffer} + + +@pytest.mark.parametrize(("case", "layout", "pipeline", "direction"), _cases(DIRECTIONS)) +def test_third_party_codecs_use_the_given_prototype( + case: Case, layout: Layout, pipeline: str, direction: Direction, tmp_path: Path +) -> None: + """Reads and writes through another package's codecs produce the given prototype's kind.""" + _round_trip_case(case, layout, pipeline, direction, tmp_path) + + +@pytest.mark.parametrize( + ("case", "layout", "pipeline", "direction"), _cases(UNUSABLE_CONFIG_DIRECTIONS) +) +def test_third_party_codecs_read_no_buffer_config( + case: Case, layout: Layout, pipeline: str, direction: Direction, tmp_path: Path +) -> None: + """With a prototype given, no buffer is built from `zarr.config`. + + `zarr.config` names a buffer kind that cannot be built. The other test + cannot see a buffer zarr builds from `zarr.config` when the pipeline + converts it to the given kind afterwards. + """ + _round_trip_case(case, layout, pipeline, direction, tmp_path)