From 8e07eb35c46c74fd0b2e5370912643600756924f Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 12:36:01 +0100 Subject: [PATCH 1/6] test(codecs): run codecs from other packages with a prototype zarr.config does not name Add tests/test_codecs/test_third_party_codecs.py, which runs imagecodecs' zarr 3 and numcodecs codecs, numcodecs' pcodec and zfpy codecs, and the zarrs codec pipeline through reads and writes whose prototype differs from the buffer kind zarr.config names, over v3, sharded, nested-sharded and v2 layouts. kvikio's GDSStore gets a case that runs only where kvikio installs. Move the fake device buffer kind, the prototype/config directions, the recording store and the round trip into tests/test_codecs/buffer_kinds.py so both suites share them; test_buffer_prototype.py checks what it did. The packages stay out of the default test environments: a `third-party-codecs` hatch environment, `just third-party-codecs`, and a CI job install and run them. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 33 ++ Justfile | 4 + pyproject.toml | 16 + tests/test_codecs/buffer_kinds.py | 295 ++++++++++++++++ tests/test_codecs/test_buffer_prototype.py | 287 ++-------------- tests/test_codecs/test_third_party_codecs.py | 344 +++++++++++++++++++ 6 files changed, 713 insertions(+), 266 deletions(-) create mode 100644 tests/test_codecs/buffer_kinds.py create mode 100644 tests/test_codecs/test_third_party_codecs.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 5690fe7d87..0d07aae32d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -173,6 +173,39 @@ 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. + - name: Check the packages import + run: | + hatch run third-party-codecs:python -c "import imagecodecs, pcodec, zfpy, zarrs" + - 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..c6612d13b9 --- /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, DeviceBuffer): + # 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, DeviceBuffer): + # 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..0b61d2891b --- /dev/null +++ b/tests/test_codecs/test_third_party_codecs.py @@ -0,0 +1,344 @@ +"""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 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, GzipCodec, ShardingCodec, TransposeCodec, ZstdCodec +from zarr.core.config import config +from zarr.registry import get_pipeline_class +from zarr.storage import LocalStore + +from .buffer_kinds import ( + DIRECTIONS, + PIPELINES, + Direction, + RecordingStore, + host, + install_fake_device_kind, + round_trip, +) + +if TYPE_CHECKING: + from collections.abc import Callable + 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. + """ + + name: str + requires: tuple[str, ...] + dtype: str + v3: Callable[[], V3Chain] | None + v2: Callable[[], V2Codecs] | None + pipelines: tuple[str, ...] = PIPELINES + + 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, + _imagecodecs_numcodecs, + ), + 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("numcodecs-pcodec", ("pcodec",), "int32", _pcodec_v3, _pcodec_v2), + Case("numcodecs-zfpy", ("zfpy",), "float64", _zfpy_v3, _zfpy_v2), + Case("zarrs", ("zarrs",), "int32", _zarrs_v3, _zarrs_v2, pipelines=(ZARRS_PIPELINE,)), +) +CASE_LAYOUT_PIPELINES = [ + pytest.param(case, layout, pipeline, id=f"{case.name}-{layout}-{pipeline.rsplit('.', 1)[-1]}") + for case in CASES + for layout in case.layouts() + for pipeline in case.pipelines +] + + +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() + + +@pytest.mark.parametrize("direction", DIRECTIONS, ids=lambda d: d.name) +@pytest.mark.parametrize(("case", "layout", "pipeline"), CASE_LAYOUT_PIPELINES) +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. + + The read results must be the given prototype's array kind and hold the + written values; the values a `RecordingStore` receives must be the given + prototype's 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. + with config.set( + {**direction.buffer_config, "codec_pipeline.path": pipeline, "codec_pipeline.strict": True} + ): + 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() + 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("direction", DIRECTIONS, ids=lambda d: d.name) +@pytest.mark.parametrize("pipeline", PIPELINES) +def test_kvikio_gds_store_uses_the_given_prototype( + pipeline: str, direction: Direction, tmp_path: Path +) -> None: + """kvikio's `GDSStore` reads into the given prototype's buffer kind. + + kvikio needs CUDA, so this runs only where kvikio installs. + """ + kvikio_zarr = pytest.importorskip("kvikio.zarr") + store = kvikio_zarr.GDSStore(tmp_path) + codecs: list[Codec] = [BytesCodec(), GzipCodec(), Crc32cCodec()] + with config.set({**direction.buffer_config, "codec_pipeline.path": pipeline}): + array = zarr.create_array( + store, + shape=(8, 8), + dtype="int32", + fill_value=0, + chunks=(4, 4), + serializer=ShardingCodec(chunk_shape=(2, 2), codecs=codecs), + compressors=None, + ) + 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) From 648002eb78980f7b2c2af613f8fa954315ac9419 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 12:46:03 +0100 Subject: [PATCH 2/6] test(codecs): check third-party codecs build no buffer from zarr.config Add a round trip under a zarr.config buffer kind that cannot be built, which catches zarr building a buffer from zarr.config and converting it afterwards (V2Codec, the shard index, an empty shard reader). Document that the fake device array is host memory to C and Rust code, so the device directions do not show a package works on a GPU. Drop the kvikio case: no environment installs kvikio, and its zarr 3 integration is a store run with the fake kind, not CUDA. In CI, derive the import check from the cases, and fail if zarr does not come from the checkout (zarrs requires zarr, so a broken version lookup would install zarr from PyPI). Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 12 +++- tests/test_codecs/test_third_party_codecs.py | 68 ++++++++++++-------- 2 files changed, 50 insertions(+), 30 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0d07aae32d..390a83f965 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -198,10 +198,18 @@ jobs: - 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. + # 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 imagecodecs, pcodec, zfpy, zarrs" + hatch run third-party-codecs:python -c " + import importlib, os, zarr + from tests.test_codecs.test_third_party_codecs import CASES + assert zarr.__file__.startswith(os.environ['GITHUB_WORKSPACE']), zarr.__file__ + for case in CASES: + for module in case.requires: + importlib.import_module(module) + " - name: Run Tests run: | just third-party-codecs -n auto -rs diff --git a/tests/test_codecs/test_third_party_codecs.py b/tests/test_codecs/test_third_party_codecs.py index 0b61d2891b..e3e7fcb3aa 100644 --- a/tests/test_codecs/test_third_party_codecs.py +++ b/tests/test_codecs/test_third_party_codecs.py @@ -6,6 +6,14 @@ 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 (numcodecs codecs, zarrs) takes it as host memory. With +CuPy those codecs, and zarrs, fail: a passing device direction here does not +mean the package works on a GPU, only that zarr hands it the kinds it should. +For zarrs, which never sees the prototype, the 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. """ @@ -20,14 +28,17 @@ import pytest import zarr -from zarr.codecs import BytesCodec, Crc32cCodec, GzipCodec, ShardingCodec, TransposeCodec, ZstdCodec +from zarr.codecs import BytesCodec, Crc32cCodec, ShardingCodec, TransposeCodec, ZstdCodec +from zarr.core.buffer import BufferPrototype, cpu from zarr.core.config import config from zarr.registry import get_pipeline_class from zarr.storage import LocalStore from .buffer_kinds import ( + DEVICE_PROTOTYPE, DIRECTIONS, PIPELINES, + UNUSABLE_CONFIG, Direction, RecordingStore, host, @@ -287,6 +298,16 @@ def _store(pipeline: str, tmp_path: Path) -> Store: return RecordingStore() +def _require(case: Case) -> None: + for module in case.requires: + pytest.importorskip(module) + + +def _pipeline_config(pipeline: str) -> dict[str, Any]: + # zarrs falls back to zarr's own pipeline for arrays it cannot handle, unless strict. + return {"codec_pipeline.path": pipeline, "codec_pipeline.strict": True} + + @pytest.mark.parametrize("direction", DIRECTIONS, ids=lambda d: d.name) @pytest.mark.parametrize(("case", "layout", "pipeline"), CASE_LAYOUT_PIPELINES) def test_third_party_codecs_use_the_given_prototype( @@ -298,13 +319,9 @@ def test_third_party_codecs_use_the_given_prototype( written values; the values a `RecordingStore` receives must be the given prototype's buffer kind. """ - for module in case.requires: - pytest.importorskip(module) + _require(case) store = _store(pipeline, tmp_path) - # zarrs falls back to zarr's own pipeline for arrays it cannot handle, unless strict. - with config.set( - {**direction.buffer_config, "codec_pipeline.path": pipeline, "codec_pipeline.strict": True} - ): + with config.set({**direction.buffer_config, **_pipeline_config(pipeline)}): 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() @@ -316,29 +333,24 @@ def test_third_party_codecs_use_the_given_prototype( assert store.chunk_value_types == {direction.prototype.buffer} -@pytest.mark.parametrize("direction", DIRECTIONS, ids=lambda d: d.name) -@pytest.mark.parametrize("pipeline", PIPELINES) -def test_kvikio_gds_store_uses_the_given_prototype( - pipeline: str, direction: Direction, tmp_path: Path +@pytest.mark.parametrize( + "prototype", [cpu.buffer_prototype, DEVICE_PROTOTYPE], ids=["host", "device"] +) +@pytest.mark.parametrize(("case", "layout", "pipeline"), CASE_LAYOUT_PIPELINES) +def test_third_party_codecs_read_no_buffer_config( + case: Case, layout: Layout, pipeline: str, prototype: BufferPrototype, tmp_path: Path ) -> None: - """kvikio's `GDSStore` reads into the given prototype's buffer kind. + """With a prototype given, no buffer is built from `zarr.config`. - kvikio needs CUDA, so this runs only where kvikio installs. + `zarr.config` names a buffer kind that cannot be built; reads and writes + still work. The other test cannot see a buffer zarr builds from + `zarr.config` when the pipeline converts it to the given kind afterwards. """ - kvikio_zarr = pytest.importorskip("kvikio.zarr") - store = kvikio_zarr.GDSStore(tmp_path) - codecs: list[Codec] = [BytesCodec(), GzipCodec(), Crc32cCodec()] - with config.set({**direction.buffer_config, "codec_pipeline.path": pipeline}): - array = zarr.create_array( - store, - shape=(8, 8), - dtype="int32", - fill_value=0, - chunks=(4, 4), - serializer=ShardingCodec(chunk_shape=(2, 2), codecs=codecs), - compressors=None, - ) - results = asyncio.run(round_trip(array, direction.prototype)) + _require(case) + store = _store(pipeline, tmp_path) + with config.set(_pipeline_config(pipeline)): + array = _create(store, layout, case) + with config.set({**UNUSABLE_CONFIG, **_pipeline_config(pipeline)}): + results = asyncio.run(round_trip(array, prototype)) for got, expected in results: - assert type(got) is direction.array_type np.testing.assert_array_equal(host(got), expected) From e6755b1b1977878823a85148031dc21a51cab87a Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 12:49:44 +0100 Subject: [PATCH 3/6] ci(codecs): compare resolved paths in the third-party codec import check Check zarr comes from the checkout's src/ by resolved path rather than by string prefix, and before importing the tests. Narrow the suite's note on which packages read device arrays directly. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 5 +++-- tests/test_codecs/test_third_party_codecs.py | 10 +++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 390a83f965..f6162d2819 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -203,9 +203,10 @@ jobs: - name: Check the packages import run: | hatch run third-party-codecs:python -c " - import importlib, os, zarr + 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 - assert zarr.__file__.startswith(os.environ['GITHUB_WORKSPACE']), zarr.__file__ for case in CASES: for module in case.requires: importlib.import_module(module) diff --git a/tests/test_codecs/test_third_party_codecs.py b/tests/test_codecs/test_third_party_codecs.py index e3e7fcb3aa..4d3ef9fb4c 100644 --- a/tests/test_codecs/test_third_party_codecs.py +++ b/tests/test_codecs/test_third_party_codecs.py @@ -8,11 +8,11 @@ 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 (numcodecs codecs, zarrs) takes it as host memory. With -CuPy those codecs, and zarrs, fail: a passing device direction here does not -mean the package works on a GPU, only that zarr hands it the kinds it should. -For zarrs, which never sees the prototype, the cases check that it stays -compatible with zarr's `CodecPipeline` interface. +reads its buffer takes it as host memory. With CuPy, numcodecs codecs and +zarrs fail where they read a device array directly: a passing device +direction here does not mean the package works on a GPU, only that zarr hands +it the kinds it should. 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 737c10ddced5c0e3e499777dca14d1a1e91b5176 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 13:00:59 +0100 Subject: [PATCH 4/6] test(codecs): run host-only third-party codecs with the host prototype only numcodecs codecs and zarrs read device arrays directly, which fails on CuPy whatever zarr does, and the fake device array would let them pass. Run those cases, and imagecodecs' numcodecs codecs, with a host prototype only, as test_buffer_prototype.py now does for numcodecs. Share the unusable-config directions through buffer_kinds.py, and check the array and store buffer kinds in the no-config test too. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- tests/test_codecs/test_third_party_codecs.py | 117 ++++++++++++------- 1 file changed, 75 insertions(+), 42 deletions(-) diff --git a/tests/test_codecs/test_third_party_codecs.py b/tests/test_codecs/test_third_party_codecs.py index 4d3ef9fb4c..e297dd3291 100644 --- a/tests/test_codecs/test_third_party_codecs.py +++ b/tests/test_codecs/test_third_party_codecs.py @@ -9,10 +9,10 @@ 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: a passing device -direction here does not mean the package works on a GPU, only that zarr hands -it the kinds it should. zarrs ignores the prototype, so its cases check that -it stays compatible with zarr's `CodecPipeline` interface. +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. @@ -29,16 +29,15 @@ import zarr from zarr.codecs import BytesCodec, Crc32cCodec, ShardingCodec, TransposeCodec, ZstdCodec -from zarr.core.buffer import BufferPrototype, cpu +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 ( - DEVICE_PROTOTYPE, DIRECTIONS, PIPELINES, - UNUSABLE_CONFIG, + UNUSABLE_CONFIG_DIRECTIONS, Direction, RecordingStore, host, @@ -47,7 +46,7 @@ ) if TYPE_CHECKING: - from collections.abc import Callable + from collections.abc import Callable, Iterable from pathlib import Path from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec, Codec @@ -91,7 +90,10 @@ class Case: `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. + 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 @@ -100,6 +102,7 @@ class Case: 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 ())) @@ -237,21 +240,49 @@ def _zarrs_v2() -> V2Codecs: ("imagecodecs",), "int32", _imagecodecs_filters_and_compressors, - _imagecodecs_numcodecs, + 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("numcodecs-pcodec", ("pcodec",), "int32", _pcodec_v3, _pcodec_v2), - Case("numcodecs-zfpy", ("zfpy",), "float64", _zfpy_v3, _zfpy_v2), - Case("zarrs", ("zarrs",), "int32", _zarrs_v3, _zarrs_v2, pipelines=(ZARRS_PIPELINE,)), + 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, + ), ) -CASE_LAYOUT_PIPELINES = [ - pytest.param(case, layout, pipeline, id=f"{case.name}-{layout}-{pipeline.rsplit('.', 1)[-1]}") - for case in CASES - for layout in case.layouts() - for pipeline in case.pipelines -] + + +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]: @@ -308,23 +339,25 @@ def _pipeline_config(pipeline: str) -> dict[str, Any]: return {"codec_pipeline.path": pipeline, "codec_pipeline.strict": True} -@pytest.mark.parametrize("direction", DIRECTIONS, ids=lambda d: d.name) -@pytest.mark.parametrize(("case", "layout", "pipeline"), CASE_LAYOUT_PIPELINES) -def test_third_party_codecs_use_the_given_prototype( +def _round_trip_case( 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. + """Create the case's array, then run the round trip in `direction` and check what it returns. - The read results must be the given prototype's array kind and hold the - written values; the values a `RecordingStore` receives must be the given - prototype's buffer kind. + 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. """ - _require(case) + for module in case.requires: + pytest.importorskip(module) store = _store(pipeline, tmp_path) - with config.set({**direction.buffer_config, **_pipeline_config(pipeline)}): + # 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 @@ -333,24 +366,24 @@ def test_third_party_codecs_use_the_given_prototype( 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( - "prototype", [cpu.buffer_prototype, DEVICE_PROTOTYPE], ids=["host", "device"] + ("case", "layout", "pipeline", "direction"), _cases(UNUSABLE_CONFIG_DIRECTIONS) ) -@pytest.mark.parametrize(("case", "layout", "pipeline"), CASE_LAYOUT_PIPELINES) def test_third_party_codecs_read_no_buffer_config( - case: Case, layout: Layout, pipeline: str, prototype: BufferPrototype, tmp_path: Path + 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; reads and writes - still work. The other test cannot see a buffer zarr builds from - `zarr.config` when the pipeline converts it to the given kind afterwards. + `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. """ - _require(case) - store = _store(pipeline, tmp_path) - with config.set(_pipeline_config(pipeline)): - array = _create(store, layout, case) - with config.set({**UNUSABLE_CONFIG, **_pipeline_config(pipeline)}): - results = asyncio.run(round_trip(array, prototype)) - for got, expected in results: - np.testing.assert_array_equal(host(got), expected) + _round_trip_case(case, layout, pipeline, direction, tmp_path) From 6bb96d531846eea695a1ff3291ff2e00665e9757 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 13:04:58 +0100 Subject: [PATCH 5/6] test(codecs): drop helpers the third-party suite no longer calls Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- tests/test_codecs/test_third_party_codecs.py | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/tests/test_codecs/test_third_party_codecs.py b/tests/test_codecs/test_third_party_codecs.py index e297dd3291..5eef880900 100644 --- a/tests/test_codecs/test_third_party_codecs.py +++ b/tests/test_codecs/test_third_party_codecs.py @@ -329,16 +329,6 @@ def _store(pipeline: str, tmp_path: Path) -> Store: return RecordingStore() -def _require(case: Case) -> None: - for module in case.requires: - pytest.importorskip(module) - - -def _pipeline_config(pipeline: str) -> dict[str, Any]: - # zarrs falls back to zarr's own pipeline for arrays it cannot handle, unless strict. - return {"codec_pipeline.path": pipeline, "codec_pipeline.strict": True} - - def _round_trip_case( case: Case, layout: Layout, pipeline: str, direction: Direction, tmp_path: Path ) -> None: From 5066305659b7da667970cddb667ec6687935b149 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 13:28:13 +0100 Subject: [PATCH 6/6] test(codecs): warn on host arrays in the shared fake device kind, as #474 now does DeviceBuffer.from_buffer and combine check the source array, not the buffer class, matching test_buffer_prototype.py on #474. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- tests/test_codecs/buffer_kinds.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_codecs/buffer_kinds.py b/tests/test_codecs/buffer_kinds.py index c6612d13b9..eac753a5a0 100644 --- a/tests/test_codecs/buffer_kinds.py +++ b/tests/test_codecs/buffer_kinds.py @@ -84,7 +84,7 @@ def create_zero_length(cls) -> Self: @classmethod def from_buffer(cls, buffer: core.Buffer) -> Self: - if not isinstance(buffer, DeviceBuffer): + 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 @@ -101,7 +101,7 @@ def as_numpy_array(self) -> npt.NDArray[Any]: def combine(self, others: Iterable[core.Buffer]) -> Self: data: list[Any] = [self._data] for other in others: - if not isinstance(other, DeviceBuffer): + 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