Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -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 "$@"
Expand Down
16 changes: 16 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
295 changes: 295 additions & 0 deletions tests/test_codecs/buffer_kinds.py
Original file line number Diff line number Diff line change
@@ -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)
Loading