From f4a3d5b9b596723894ee0be62f849bac8dc074b5 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 15:34:12 +0100 Subject: [PATCH 01/31] chore(tools): add a compatibility differential against a baseline zarr tools/compat runs seeded existing-API scenarios under this checkout and under a baseline commit or release, and reports every observable difference. Assisted-by: ClaudeCode:claude-opus-5-5 --- tools/compat/README.md | 29 + tools/compat/compat.py | 137 +++++ tools/compat/compat_scenarios.py | 959 +++++++++++++++++++++++++++++++ tools/compat/diff.py | 123 ++++ tools/compat/run.py | 51 ++ 5 files changed, 1299 insertions(+) create mode 100644 tools/compat/README.md create mode 100644 tools/compat/compat.py create mode 100644 tools/compat/compat_scenarios.py create mode 100644 tools/compat/diff.py create mode 100644 tools/compat/run.py diff --git a/tools/compat/README.md b/tools/compat/README.md new file mode 100644 index 0000000000..50dd09c967 --- /dev/null +++ b/tools/compat/README.md @@ -0,0 +1,29 @@ +# Compatibility differential + +Checks that this checkout behaves as a baseline zarr does wherever existing code can +look: the synchronous `Array` API, `AsyncArray` used as a dataclass (fields, `replace`, +`asdict`, equality, `object.__setattr__`), copies, pickles carried between the two +versions in both directions, `AsyncArray` subclasses of several shapes (one overrides +`_set_selection`), arrays whose metadata documents another writer stored (chunk sizes +zarr reads only by repairing them), and writes through groups whose consolidated +metadata holds copies of such documents, at the root and in a subgroup. + +```bash +hatch run test.py3.12-optional:python tools/compat/compat.py --baseline "$(git merge-base HEAD upstream/main)" --seeds 2000 +``` + +`--baseline` takes any commit, branch or tag: the `main` a branch holds, as above, or a +release such as `v3.4.2`. The run takes about half a minute for 2000 seeds, prints the differences by class +(see `diff.py`) and leaves every run's steps in its work directory (`--work`). + +- `compat_scenarios.py` holds the scenarios. Random programs (one per seed) create or open + an array, then apply a seeded sequence of writes, reads, resizes, appends, attribute + updates, reopens and copies through several handles, recording what each step returns, + raises and warns, and the store's contents. The sequence depends only on the seed, so + both versions perform the same operations. +- `run.py` runs them under one source tree; `diff.py` compares two runs. + +A difference is a change a caller can observe, which is not always a break: read it, and +say in the change's notes why each one is intended. Steps labeled `internal:` look at +private state and are reported apart. The scenarios cover existing surfaces only: a new +API has no baseline to differ from, so its tests are the regular suite. diff --git a/tools/compat/compat.py b/tools/compat/compat.py new file mode 100644 index 0000000000..1159594b9c --- /dev/null +++ b/tools/compat/compat.py @@ -0,0 +1,137 @@ +""" +Check that this checkout behaves as a baseline zarr does, wherever code today can look. + + python tools/compat/compat.py --baseline REF [--seeds N] [--work DIR] + +Exports `src` at `REF` (a commit, branch or tag), runs the scenarios in +`compat_scenarios.py` under it and under this checkout's `src`, carries pickles each way +between the two, and prints the differences (see `diff.py` for how they are classed). +Run it with an interpreter that has this checkout's dependencies, such as the test +environment's. +""" + +from __future__ import annotations + +import argparse +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent + + +def export(ref: str, into: Path) -> Path: + """The `src` directory of `ref`, with the version file the build would write.""" + shutil.rmtree(into, ignore_errors=True) + into.mkdir(parents=True) + archive = subprocess.run( + ["git", "-C", str(ROOT), "archive", ref, "src"], check=True, capture_output=True + ).stdout + subprocess.run(["tar", "-x", "-C", str(into)], input=archive, check=True) + described = subprocess.run( + ["git", "-C", str(ROOT), "describe", "--tags", "--match", "v[0-9]*", ref], + capture_output=True, + text=True, + check=True, + ).stdout.strip() + # zarr refuses to import as version 0.0.0, so name the baseline after its tag. + tag, _, rest = described.removeprefix("v").partition("-") + distance, _, commit = rest.partition("-") + version = f"{tag}.post{distance}+{commit}" if rest else (tag or "999.0.0") + (into / "src" / "zarr" / "_version.py").write_text( + f"__version__ = version = {version!r}\n" + f"__version_tuple__ = version_tuple = (0, 0, 0, {version!r})\n" + "__commit_id__ = commit_id = None\n" + ) + return into / "src" + + +def run(src: Path, out: Path, work: Path, *args: str) -> None: + # `src` goes on PYTHONPATH, ahead of any installed zarr, so `run.py` imports it. + pythonpath = os.pathsep.join([str(src), os.environ.get("PYTHONPATH", "")]).rstrip(os.pathsep) + subprocess.run( + [ + sys.executable, + str(HERE / "run.py"), + str(src), + str(out), + "--tmp", + str(work / "tmp"), + *args, + ], + check=True, + env={**os.environ, "PYTHONPATH": pythonpath}, + ) + + +def diff(old: Path, new: Path, out: Path, title: str) -> None: + print(f"\n=== {title} ===", flush=True) + subprocess.run( + [sys.executable, str(HERE / "diff.py"), str(old), str(new), "--out", str(out)], check=True + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--baseline", required=True) + parser.add_argument("--seeds", type=int, default=200) + parser.add_argument("--work", type=Path) + args = parser.parse_args() + work = args.work or Path(tempfile.mkdtemp(prefix="zarr-compat-")) + work.mkdir(parents=True, exist_ok=True) + sources = {"base": export(args.baseline, work / "base"), "head": ROOT / "src"} + + for name, src in sources.items(): + run(src, work / f"scenarios-{name}.json", work, "--seeds", str(args.seeds)) + diff( + work / "scenarios-base.json", + work / "scenarios-head.json", + work / "diff-scenarios.json", + "scenarios", + ) + + # Pickles: each version dumps over its own stores, kept pristine, and each version loads + # every dump over a fresh copy of the stores it was made over. + for name, src in sources.items(): + stores = work / f"stores-{name}" + shutil.rmtree(stores, ignore_errors=True) + run( + src, + work / "unused.json", + work, + "--dump-pickles", + str(work / f"pickles-{name}"), + "--stores", + str(stores), + ) + shutil.rmtree(work / f"pristine-{name}", ignore_errors=True) + shutil.copytree(stores, work / f"pristine-{name}") + for dumped in sources: + for loader, src in sources.items(): + stores = work / f"stores-{dumped}" + shutil.rmtree(stores) + shutil.copytree(work / f"pristine-{dumped}", stores) + run( + src, + work / f"pickles-{dumped}-in-{loader}.json", + work, + "--load-pickles", + str(work / f"pickles-{dumped}"), + ) + reference = work / "pickles-base-in-base.json" + for dumped, loader in (("base", "head"), ("head", "base"), ("head", "head")): + diff( + reference, + work / f"pickles-{dumped}-in-{loader}.json", + work / f"diff-pickles-{dumped}-in-{loader}.json", + f"pickles dumped by {dumped}, loaded by {loader} (vs base in base)", + ) + print(f"\nwork directory: {work}") + + +if __name__ == "__main__": + main() diff --git a/tools/compat/compat_scenarios.py b/tools/compat/compat_scenarios.py new file mode 100644 index 0000000000..b34762b405 --- /dev/null +++ b/tools/compat/compat_scenarios.py @@ -0,0 +1,959 @@ +""" +Scenarios for the zarr compatibility differential (see `README.md`). + +Each scenario drives zarr the way existing code does (the synchronous `Array` API, +`AsyncArray` used as a dataclass, pickle, copy, subclasses, and stored documents written +by other software) and records what a caller can observe. `run.py` runs the scenarios +under one zarr source tree, and `diff.py` compares two runs. + +This module must import under every zarr version it runs against, so it uses only names +each of them has. It is imported as `compat_scenarios` in every process, so a pickle of +one of its subclasses loads in either version. +""" + +from __future__ import annotations + +import copy +import dataclasses +import hashlib +import json +import math +import pickle +import random +import re +import shutil +import warnings +from pathlib import Path +from typing import Any + +import numpy as np + +import zarr +import zarr.core.sync +import zarr.storage +from zarr.core.array import AsyncArray +from zarr.core.buffer import default_buffer_prototype + +_ADDRESS = re.compile(r"0x[0-9a-fA-F]+") +_MEMORY_STORE = re.compile(r"memory://\d+") +_METADATA_KEYS = (".zarray", ".zattrs", ".zgroup", ".zmetadata", "zarr.json") +_MAX_ELEMENTS = 512 + + +class Recorder: + """Records what each step of a scenario returned, raised, and warned.""" + + def __init__(self, tmp: Path) -> None: + self.events: list[dict[str, Any]] = [] + self.tmp = str(tmp) + self.scenario = "" + + def norm(self, text: str) -> str: + text = _MEMORY_STORE.sub("memory://?", _ADDRESS.sub("0x?", text)) + return text.replace(self.tmp, "") + + def step(self, label: str, fn: Any) -> tuple[bool, Any]: + """Run `fn`, record its outcome under `label`, and return whether it returned + and what.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + try: + value = fn() + except Exception as e: # noqa: BLE001 (any exception is an outcome to compare) + outcome: dict[str, Any] = { + "raises": f"{type(e).__module__}.{type(e).__qualname__}", + "message": self.norm(str(e)), + } + ok = False + value = None + else: + outcome = {"value": self.summarize(value)} + ok = True + if caught: + outcome["warnings"] = [[w.category.__name__, self.norm(str(w.message))] for w in caught] + self.events.append({"scenario": self.scenario, "label": label, **outcome}) + return ok, value + + def summarize(self, value: Any) -> Any: + """A JSON value that compares equal across processes exactly when what a caller + sees of `value` does.""" + if isinstance(value, str): + return self.norm(value) + if value is None or isinstance(value, bool): + return value + if isinstance(value, int): + return value + if isinstance(value, float): + return value if math.isfinite(value) else repr(value) + if isinstance(value, complex): + return {"complex": [self.summarize(value.real), self.summarize(value.imag)]} + if isinstance(value, np.ndarray): + flat = value.reshape(-1)[:_MAX_ELEMENTS] + return { + "ndarray": value.dtype.str, + "shape": list(value.shape), + "data": [self.summarize(v) for v in flat.tolist()], + } + if isinstance(value, np.generic): + return {"scalar": value.dtype.str, "value": self.summarize(value.item())} + if isinstance(value, bytes | bytearray | memoryview): + raw = bytes(value) + return {"bytes": hashlib.sha1(raw).hexdigest()[:16], "len": len(raw)} + if isinstance(value, tuple): + return {"tuple": [self.summarize(v) for v in value]} + if isinstance(value, list): + return [self.summarize(v) for v in value] + if isinstance(value, dict): + return {"dict": [[self.summarize(k), self.summarize(v)] for k, v in value.items()]} + if isinstance(value, zarr.Array): + return {"Array": type(value).__qualname__, "shape": list(value.shape)} + if isinstance(value, AsyncArray): + return {"AsyncArray": type(value).__qualname__, "shape": list(value.shape)} + if isinstance(value, zarr.Group): + return {"Group": type(value).__qualname__, "path": value.path} + return {"type": type(value).__qualname__, "repr": self.norm(repr(value))} + + +# Stores --------------------------------------------------------------------------------- + + +def snapshot(store: Any) -> dict[str, Any]: + """Every key of `store`: the text of a metadata document, or the digest of a chunk.""" + if isinstance(store, zarr.storage.LocalStore): + root = Path(store.root) + items = { + p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file() + } + else: + items = {k: v.to_bytes() for k, v in store._store_dict.items()} + out: dict[str, Any] = {} + for key in sorted(items): + raw = items[key] + if key.rsplit("/", 1)[-1] in _METADATA_KEYS: + out[key] = raw.decode() + else: + out[key] = hashlib.sha1(raw).hexdigest()[:16] + return out + + +def new_store(kind: str, tmp: Path, name: str) -> Any: + if kind == "memory": + return zarr.storage.MemoryStore() + path = tmp / name + shutil.rmtree(path, ignore_errors=True) + return zarr.storage.LocalStore(path) + + +def put_document(store: Any, key: str, document: dict[str, Any]) -> None: + """Write `document` at `key` as other software would: compact JSON, bytes as given.""" + text = json.dumps(document).encode() + if isinstance(store, zarr.storage.LocalStore): + path = Path(store.root) / key + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(text) + else: + store._store_dict[key] = default_buffer_prototype().buffer.from_bytes(text) + + +# Observations --------------------------------------------------------------------------- + + +def observe(rec: Recorder, name: str, arr: Any, store: Any) -> None: + """Record what a caller sees of `arr` and its store.""" + if arr is None: + rec.step(f"{name}:missing", lambda: None) + return + rec.step(f"{name}:shape", lambda: arr.shape) + rec.step(f"{name}:chunks", lambda: arr.chunks) + rec.step(f"{name}:shards", lambda: arr.shards) + rec.step(f"{name}:dtype", lambda: str(arr.dtype)) + rec.step(f"{name}:fill_value", lambda: arr.fill_value) + rec.step(f"{name}:order", lambda: arr.order) + rec.step(f"{name}:attrs", lambda: arr.attrs.asdict()) + rec.step(f"{name}:metadata", lambda: arr.metadata.to_dict()) + rec.step(f"{name}:metadata.type", lambda: type(arr.metadata).__qualname__) + rec.step(f"{name}:read", lambda: arr[...]) + rec.step(f"{name}:nchunks_initialized", lambda: arr.nchunks_initialized) + rec.step(f"{name}:read_only", lambda: arr.read_only) + rec.step(f"{name}:path", lambda: (arr.path, arr.name, arr.basename)) + rec.step(f"{name}:store", lambda: snapshot(store)) + + +def observe_surface(rec: Recorder, name: str, arr: Any, other: Any) -> None: + """Record `arr` as a dataclass and an object: what code that treats it as one sees.""" + aa = arr.async_array + rec.step(f"{name}:fields", lambda: [f.name for f in dataclasses.fields(aa)]) + rec.step( + f"{name}:fields.init", + lambda: [(f.name, f.init, f.compare, f.repr) for f in dataclasses.fields(type(aa))], + ) + rec.step(f"{name}:Array.fields", lambda: [f.name for f in dataclasses.fields(arr)]) + rec.step(f"{name}:eq.self", lambda: (aa == aa, arr == arr)) # noqa: PLR0124 + rec.step(f"{name}:eq.copy", lambda: aa == copy.copy(aa)) + rec.step(f"{name}:eq.other", lambda: (aa == other.async_array, arr == other)) + rec.step(f"{name}:hash", lambda: hash(aa) == hash(copy.copy(aa))) + rec.step(f"{name}:Array.hash", lambda: hash(arr) == hash(arr)) + rec.step(f"{name}:repr", lambda: (repr(arr), str(arr))) + rec.step(f"{name}:AsyncArray.repr", lambda: repr(aa)) + rec.step(f"{name}:asdict.keys", lambda: list(dataclasses.asdict(aa))) + rec.step(f"{name}:astuple.len", lambda: len(dataclasses.astuple(aa))) + rec.step(f"{name}:codec_pipeline.type", lambda: type(aa.codec_pipeline).__qualname__) + rec.step(f"{name}:config", lambda: aa.config) + rec.step(f"{name}:store_path", lambda: str(aa.store_path)) + rec.step(f"{name}:metadata.is", lambda: aa.metadata is arr.metadata) + rec.step(f"{name}:internal:vars", lambda: sorted(vars(aa))) + rec.step(f"{name}:internal:chunk_grid.type", lambda: type(aa._chunk_grid).__qualname__) + rec.step(f"{name}:frozen", lambda: setattr(aa, "metadata", aa.metadata)) + + +# Random programs ------------------------------------------------------------------------- + +_DTYPES = ["int8", "uint16", "int32", "float32", "float64", "bool", "complex64"] +_ATTRIBUTES: list[dict[str, Any] | None] = [ + None, + {}, + {"a": 1, "b": [1, 2]}, + {"z": 1, "a": {"n": None}}, +] + + +def _selection(rng: random.Random, shape: list[int]) -> tuple[str, Any]: + """A selection into an array of `shape`: its kind and the selection.""" + if not shape: + return "basic", rng.choice([(), Ellipsis]) + if all(n > 0 for n in shape) and rng.random() < 0.3: + kind = rng.choice(["oindex", "vindex"]) + if kind == "oindex": + return kind, tuple(sorted(rng.sample(range(n), rng.randint(1, n))) for n in shape) + k = rng.randint(1, 4) + return kind, tuple([rng.randrange(n) for _ in range(k)] for n in shape) + sel: list[Any] = [] + for n in shape: + r = rng.random() + if n > 0 and r < 0.25: + sel.append(rng.randrange(n)) + else: + start = rng.randint(0, n) + stop = rng.randint(start, n + 2) + sel.append(slice(start, stop, rng.choice([1, 1, 2]))) + return "basic", tuple(sel) + + +def _selected_shape(kind: str, sel: Any, shape: list[int]) -> tuple[int, ...]: + dummy = np.empty(shape, dtype="u1") + if kind == "oindex": + return dummy[np.ix_(*sel)].shape + if kind == "vindex": + return dummy[tuple(np.asarray(s) for s in sel)].shape + return dummy[sel].shape + + +def _values(rng: random.Random, dtype: str, shape: tuple[int, ...]) -> Any: + if rng.random() < 0.2: + return np.array(rng.randint(0, 5)).astype(dtype)[()] + size = int(np.prod(shape)) + return (np.arange(size) % 7 + rng.randint(0, 3)).reshape(shape).astype(dtype) + + +def _index(arr: Any, kind: str) -> Any: + return {"basic": arr, "oindex": arr.oindex, "vindex": arr.vindex}[kind] + + +def _write(arr: Any, kind: str, sel: Any, values: Any) -> None: + _index(arr, kind)[sel] = values + + +def run_program(rec: Recorder, seed: int, tmp: Path) -> None: + """A random sequence of operations on one array through several handles. The + sequence depends only on `seed`, never on what zarr returns, so both runs of a + seed perform the same operations.""" + rng = random.Random(seed) + zarr_format = rng.choice([2, 3]) + ndim = rng.choice([0, 1, 1, 2, 2, 3]) + shape = [rng.choice([0, 1, 3, 4, 7]) for _ in range(ndim)] + chunks = [rng.choice([1, 2, 3, 5, 8]) for _ in range(ndim)] + shards = None + if zarr_format == 3 and ndim > 0 and rng.random() < 0.4: + shards = [c * rng.choice([1, 2]) for c in chunks] + dtype = rng.choice(_DTYPES) + fill_value = rng.choice([None, 0, 1]) + if dtype == "bool" and fill_value is not None: + fill_value = bool(fill_value) + kwargs: dict[str, Any] = { + "shape": shape, + "chunks": chunks if ndim else "auto", + "dtype": dtype, + "zarr_format": zarr_format, + "attributes": rng.choice(_ATTRIBUTES), + "compressors": rng.choice(["auto", None]), + } + if fill_value is not None: + kwargs["fill_value"] = fill_value + if shards is not None: + kwargs["shards"] = shards + if zarr_format == 3 and ndim and rng.random() < 0.3: + kwargs["dimension_names"] = [f"d{i}" for i in range(ndim)] + if zarr_format == 2 and rng.random() < 0.3: + kwargs["order"] = "F" + if rng.random() < 0.3: + kwargs["chunk_key_encoding"] = ( + {"name": "v2", "separator": rng.choice([".", "/"])} + if zarr_format == 2 or rng.random() < 0.5 + else {"name": "default", "separator": "."} + ) + if rng.random() < 0.3: + kwargs["config"] = {"write_empty_chunks": rng.choice([True, False])} + store_kind = rng.choice(["memory", "local"]) + store = new_store(store_kind, tmp, f"program-{seed}") + path = rng.choice(["", "a", "g/a"]) + rec.step("create.kwargs", lambda: {k: str(v) for k, v in kwargs.items()}) + + legacy = None + if ndim and rng.random() < 0.35: + # A document another writer stored, with chunk sizes zarr reads only by repairing + # them: 0 or JSON false (an empty axis's `chunks=-1`), or JSON true. + stored = [ + rng.choice([c, c, 0, True] + ([False] if zarr_format == 3 else [])) for c in chunks + ] + legacy = _legacy_document(zarr_format, shape, stored, dtype, kwargs.get("attributes")) + if legacy is None: + ok, arr = rec.step("create", lambda: zarr.create_array(store, name=path, **kwargs)) + else: + rec.step("legacy.document", lambda: legacy) + prefix = f"{path}/" if path else "" + for key, document in legacy.items(): + put_document(store, prefix + key, document) + ok, arr = rec.step("create", lambda: zarr.open_array(store, path=path, mode="r+")) + handles: list[Any] = [arr if ok else None] + observe(rec, "h0", arr if ok else None, store) + + for step in range(rng.randint(6, 14)): + op = rng.choice( + [ + "write", "write", "read", "resize", "append", "attrs", "reopen", "reopen_ro", + "pickle", "copy", "deepcopy", "replace", "setattr", "with_config", "observe", + "surface", "replace_metadata", "from_dict", "async_read", "attrs_in_place", + ] + ) # fmt: skip + h = rng.randrange(len(handles)) + arr = handles[h] + tag = f"{step}:{op}:h{h}" + if op in ("write", "read"): + kind, sel = _selection(rng, shape) + values = _values(rng, dtype, _selected_shape(kind, sel, shape)) + if arr is None: + rec.step(f"{tag}:skipped", lambda: None) + continue + if op == "write": + rec.step( + f"{tag}:{kind}:{sel!r}", + lambda a=arr, k=kind, s=sel, v=values: _write(a, k, s, v), + ) + else: + rec.step(f"{tag}:{kind}:{sel!r}", lambda a=arr, k=kind, s=sel: _index(a, k)[s]) + elif op == "resize": + new = [rng.choice([0, 1, 2, 5, 9]) for _ in shape] + if arr is not None: + rec.step(f"{tag}:{new}", lambda a=arr, n=new: a.resize(n)) + shape = new + elif op == "append": + if not shape: + continue + axis = rng.randrange(len(shape)) + extra = [n if i != axis else rng.randint(1, 3) for i, n in enumerate(shape)] + data = (np.arange(int(np.prod(extra))) % 5).reshape(extra).astype(dtype) + if arr is not None: + rec.step(f"{tag}:{axis}", lambda a=arr, d=data, x=axis: a.append(d, axis=x)) + shape = [n + (extra[i] if i == axis else 0) for i, n in enumerate(shape)] + elif op == "attrs": + update = rng.choice([{}, {"a": 2}, {"new": [1, {"x": 1}]}, {"b": None, "a": 3}]) + if arr is not None: + rec.step(f"{tag}:{update}", lambda a=arr, u=update: a.update_attributes(u)) + elif op in ("reopen", "reopen_ro"): + mode = "r" if op == "reopen_ro" else "r+" + ok, new_arr = rec.step(tag, lambda m=mode: zarr.open_array(store, path=path, mode=m)) + handles.append(new_arr if ok else None) + elif op in ( + "pickle", + "copy", + "deepcopy", + "replace", + "setattr", + "replace_metadata", + "from_dict", + ): + if arr is None: + handles.append(None) + continue + make = { + "pickle": lambda a=arr: pickle.loads(pickle.dumps(a)), + "copy": lambda a=arr: copy.copy(a), + "deepcopy": lambda a=arr: copy.deepcopy(a), + "replace": lambda a=arr: zarr.Array(dataclasses.replace(a.async_array)), + "setattr": lambda a=arr: _setattr_copy(a), + "replace_metadata": lambda a=arr: _replace_metadata(a), + "from_dict": lambda a=arr: zarr.Array( + AsyncArray(a.metadata.to_dict(), a.async_array.store_path, a.async_array.config) + ), + }[op] + ok, new_arr = rec.step(tag, make) + handles.append(new_arr if ok else None) + elif op == "with_config": + if arr is None: + handles.append(None) + continue + cfg = {"write_empty_chunks": rng.choice([True, False])} + ok, new_arr = rec.step(tag, lambda a=arr, c=cfg: a.with_config(c)) + handles.append(new_arr if ok else None) + elif op == "observe": + observe(rec, tag, arr, store) + elif op == "attrs_in_place": + how = rng.choice(["set", "reorder", "nested"]) + if arr is not None: + rec.step(f"{tag}:{how}", lambda a=arr, w=how: _change_attributes_in_place(a, w)) + elif op == "async_read": + if arr is not None: + rec.step(tag, lambda a=arr: zarr.core.sync.sync(a.async_array.getitem(...))) + elif op == "surface": + if arr is not None and handles[0] is not None: + observe_surface(rec, tag, arr, handles[0]) + for i, arr in enumerate(handles): + if arr is not None: + rec.step(f"end:h{i}:read", lambda a=arr: a[...]) + rec.step(f"end:h{i}:attrs", lambda a=arr: a.attrs.asdict()) + rec.step(f"end:h{i}:shape", lambda a=arr: a.shape) + observe(rec, "end:fresh", zarr.open_array(store, path=path, mode="r"), store) + + +def _legacy_document( + zarr_format: int, shape: list[int], chunks: list[Any], dtype: str, attributes: Any +) -> dict[str, dict[str, Any]]: + """The documents, by key, of an array stored by another writer with chunk sizes + `chunks`.""" + fill: Any = False if dtype == "bool" else 0 + if zarr_format == 2: + out = { + ".zarray": { + "zarr_format": 2, "shape": shape, "chunks": chunks, "dtype": np.dtype(dtype).str, + "fill_value": fill, "order": "C", "filters": None, "compressor": None, + } + } # fmt: skip + if attributes: + out[".zattrs"] = attributes + return out + document = _v3_doc(shape, chunks) + document["data_type"] = dtype + document["fill_value"] = [0.0, 0.0] if dtype == "complex64" else fill + document["attributes"] = attributes or {} + if dtype in ("int8", "bool"): + document["codecs"] = [{"name": "bytes", "configuration": {}}] + return {"zarr.json": document} + + +def _change_attributes_in_place(arr: Any, how: str) -> Any: + """Change `arr`'s attributes in the metadata's own dict, as code that holds it does.""" + attributes = arr.metadata.attributes + if how == "set": + attributes["in_place"] = [1, 2] + elif how == "reorder": + for key in list(attributes): + attributes[key] = attributes.pop(key) + attributes["last"] = 0 + else: + attributes.setdefault("nested", {"n": []})["n"].append(len(attributes)) + return dict(attributes) + + +def _replace_metadata(arr: Any) -> Any: + """A copy of `arr` made by `dataclasses.replace` with metadata of other attributes.""" + metadata = dataclasses.replace(arr.metadata, attributes={"replaced": True}) + return zarr.Array(dataclasses.replace(arr.async_array, metadata=metadata)) + + +def _setattr_copy(arr: Any) -> Any: + """A copy of `arr` whose metadata is replaced the way frozen-dataclass code does it.""" + aa = copy.copy(arr.async_array) + metadata = dataclasses.replace(arr.metadata, attributes={"set": "by setattr"}) + object.__setattr__(aa, "metadata", metadata) + return zarr.Array(aa) + + +# Documents other software stored --------------------------------------------------------- + + +def _v2_doc(shape: list[int], chunks: list[Any]) -> dict[str, Any]: + return { + "zarr_format": 2, + "shape": shape, + "chunks": chunks, + "dtype": " dict[str, Any]: + bytes_codec: dict[str, Any] = {"name": "bytes", "configuration": {"endian": "little"}} + codecs: list[Any] = [bytes_codec] + if inner is not None: + codecs = [ + { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": inner, + "codecs": [bytes_codec], + "index_codecs": [bytes_codec, {"name": "crc32c"}], + "index_location": "end", + }, + } + ] + return { + "zarr_format": 3, + "node_type": "array", + "shape": shape, + "data_type": "int16", + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": chunk_shape}}, + "chunk_key_encoding": {"name": "default", "configuration": {"separator": "/"}}, + "fill_value": 0, + "codecs": codecs, + "attributes": {"z": 1, "a": 2}, + } + + +DOCUMENTS: dict[str, dict[str, Any]] = { + "v2-valid": _v2_doc([10, 10], [4, 5]), + "v3-valid-empty-axes": _v3_doc([0, 0], [1, 1]), + "v3-valid-sharded": _v3_doc([10], [4], inner=[2]), + "v2-zero-empty-axis": _v2_doc([0, 4], [0, 4]), + "v3-false-empty-axis": _v3_doc([0], [False]), + "v2-true": _v2_doc([5], [True]), + "v3-true": _v3_doc([5, 4], [True, 4]), + "v2-zero-grown-axis": _v2_doc([3], [0]), + "v3-zero-grown-axis": _v3_doc([4, 3], [4, 0]), + "v2-zero-empty-and-grown-axes": _v2_doc([0, 3], [0, 0]), + "v3-sharded-zero-empty-axis": _v3_doc([0], [0], inner=[4]), + "v3-sharded-zero-grown-axis": _v3_doc([10], [0], inner=[4]), + "v3-sharded-zero-2d": _v3_doc([0, 3], [0, 3], inner=[2, 3]), + "v3-sharded-true": _v3_doc([5], [True], inner=[True]), + "v2-float-chunk": _v2_doc([4], [2.0]), + "v3-float-chunk": _v3_doc([4], [2.0]), + "v2-negative-chunk": _v2_doc([4], [-1]), + "v3-edge-list-in-regular": _v3_doc([5], [[2, 3]]), + "v2-fill-nan-int": {**_v2_doc([4], [2]), "fill_value": "NaN"}, + "v2-zattrs-fields": {**_v2_doc([4], [2]), "dimension_separator": "/"}, + "v3-extra-field": {**_v3_doc([4], [2]), "extra": {"must_understand": False}}, +} + + +def run_document(rec: Recorder, name: str, tmp: Path) -> None: + """Open an array whose document other software stored, through two handles, and + write through one of them.""" + document = DOCUMENTS[name] + zarr_format = document["zarr_format"] + store = new_store("local", tmp, f"doc-{name}") + if zarr_format == 2: + put_document(store, ".zgroup", {"zarr_format": 2}) + put_document(store, "a/.zarray", document) + put_document(store, "a/.zattrs", {"z": 1, "a": 2}) + else: + put_document(store, "zarr.json", {"zarr_format": 3, "node_type": "group", "attributes": {}}) + put_document(store, "a/zarr.json", document) + + ok, first = rec.step("open", lambda: zarr.open_array(store, path="a", mode="r+")) + observe(rec, "first", first if ok else None, store) + ok2, second = rec.step("open.second", lambda: zarr.open_array(store, path="a", mode="r+")) + if not ok: + return + rec.step("pickle.first", lambda: pickle.loads(pickle.dumps(first)).metadata.to_dict()) + shape = first.shape + if all(n > 0 for n in shape): + rec.step( + "write.first", + lambda: first.__setitem__(..., np.arange(int(np.prod(shape))).reshape(shape)), + ) + rec.step("store.after_write", lambda: snapshot(store)) + if ok2: + rec.step("second.read", lambda: second[...]) + rec.step("second.resize", lambda: second.resize([n + 2 for n in shape])) + rec.step("second.write", lambda: second.__setitem__(..., 3)) + observe(rec, "second", second, store) + rec.step("first.read_after_second", lambda: first[...]) + rec.step("first.update_attributes", lambda: first.update_attributes({})) + rec.step("store.after_attrs", lambda: snapshot(store)) + _ = rec.step("consolidate", lambda: zarr.consolidate_metadata(store)) + rec.step("store.after_consolidate", lambda: snapshot(store)) + ok4, cgroup = rec.step("open_consolidated", lambda: zarr.open_consolidated(store, mode="r+")) + if ok4: + rec.step("consolidated.members", lambda: [k for k, _ in cgroup.members()]) + ok5, member = rec.step("consolidated.member", lambda: cgroup["a"]) + if ok5: + observe(rec, "member", member, store) + rec.step("member.write", lambda: member.__setitem__(..., 1)) + rec.step("group.to_dict", lambda: cgroup.metadata.to_dict()) + rec.step("store.end", lambda: snapshot(store)) + + +# Groups ------------------------------------------------------------------------------------- + + +def put_consolidated_group(store: Any, prefix: str, document: dict[str, Any]) -> None: + """Store, as other software would, a group at `prefix` holding the array `a` with + `document`, and consolidated metadata holding a copy of it.""" + at = f"{prefix}/" if prefix else "" + if document["zarr_format"] == 2: + attributes = {"z": 1, "a": 2} + zgroup = {"zarr_format": 2} + put_document(store, f"{at}.zgroup", zgroup) + put_document(store, f"{at}a/.zarray", document) + put_document(store, f"{at}a/.zattrs", attributes) + members = {".zgroup": zgroup, "a/.zarray": document, "a/.zattrs": attributes} + put_document(store, f"{at}.zmetadata", {"zarr_consolidated_format": 1, "metadata": members}) + else: + consolidated = {"kind": "inline", "must_understand": False, "metadata": {"a": document}} + put_document(store, f"{at}a/zarr.json", document) + put_document( + store, + f"{at}zarr.json", + { + "zarr_format": 3, + "node_type": "group", + "attributes": {}, + "consolidated_metadata": consolidated, + }, + ) + + +def _open_group_at(store: Any, prefix: str) -> Any: + """The group at `prefix`, reached through the root group when it is not the root.""" + root = zarr.open_group(store, mode="r+") + return root[prefix] if prefix else root + + +def _set_group_attribute(group: Any) -> None: + group.attrs["x"] = 1 + + +GROUP_FLOWS = ( + "attrs", + "array_then_attrs", + "attrs_then_array", + "members_then_attrs", + "member_write", + "create_array", + "reconsolidate", + "resaved_elsewhere", +) +GROUP_PREFIXES = ("", "g") + + +def run_group(rec: Recorder, name: str, prefix: str, flow: str, tmp: Path) -> None: + """Write through a group whose consolidated metadata other software stored: at the + root, or (`prefix`) in a subgroup of a root group that holds none.""" + document = DOCUMENTS[name] + zarr_format = document["zarr_format"] + store = new_store("local", tmp, f"group-{name}-{prefix or 'root'}-{flow}") + if prefix: + if zarr_format == 2: + put_document(store, ".zgroup", {"zarr_format": 2}) + else: + root = {"zarr_format": 3, "node_type": "group", "attributes": {}} + put_document(store, "zarr.json", root) + put_consolidated_group(store, prefix, document) + array_path = f"{prefix}/a" if prefix else "a" + + if flow in ("array_then_attrs", "resaved_elsewhere"): + rec.step("open_array", lambda: zarr.open_array(store, path=array_path, mode="r+").shape) + if flow == "resaved_elsewhere": + # Another store object over the same directory re-saves the array and consolidates. + other = zarr.storage.LocalStore(store.root) + rec.step( + "elsewhere.resave", + lambda: zarr.open_array(other, path=array_path, mode="r+").update_attributes({}).shape, + ) + rec.step( + "elsewhere.consolidate", + lambda: zarr.consolidate_metadata(other, path=prefix or None).metadata.to_dict(), + ) + ok, group = rec.step("open", lambda: _open_group_at(store, prefix)) + if ok: + if flow == "attrs_then_array": + rec.step("open_array", lambda: zarr.open_array(store, path=array_path, mode="r+").shape) + if flow == "members_then_attrs": + rec.step("members", lambda: sorted(k for k, _ in group.members())) + if flow == "member_write": + ok_member, member = rec.step("member", lambda: group["a"]) + if ok_member and all(n > 0 for n in member.shape): + rec.step("member.write", lambda: member.__setitem__(..., 1)) + rec.step("member.read", lambda: member[...]) + elif flow == "create_array": + rec.step( + "create_array", lambda: group.create_array("b", shape=(2,), dtype="int8").shape + ) + elif flow == "reconsolidate": + rec.step( + "consolidate", + lambda: zarr.consolidate_metadata(store, path=prefix or None).metadata.to_dict(), + ) + else: + rec.step("attrs", lambda: _set_group_attribute(group)) + rec.step("store.end", lambda: snapshot(store)) + + +# Subclasses -------------------------------------------------------------------------------- + + +@dataclasses.dataclass(frozen=True) +class TaggedAsyncArray(AsyncArray): # type: ignore[type-arg] + """A dataclass subclass with a field of its own.""" + + tag: str = "untagged" + + +class PlainAsyncArray(AsyncArray): # type: ignore[type-arg] + """A subclass that adds a method and nothing else.""" + + def describe(self) -> str: + return f"{type(self).__name__}{self.shape}" + + +class SlottedAsyncArray(AsyncArray): # type: ignore[type-arg] + """A subclass with a slot of its own.""" + + __slots__ = ("note",) + + +class ReducingAsyncArray(AsyncArray): # type: ignore[type-arg] + """A subclass that pickles through a reduction of its own.""" + + def __reduce__(self) -> Any: + return (_rebuild_reducing, (self.metadata, self.store_path, self.config)) + + +def _rebuild_reducing(metadata: Any, store_path: Any, config: Any) -> ReducingAsyncArray: + return ReducingAsyncArray(metadata, store_path, config) + + +class InitAsyncArray(AsyncArray): # type: ignore[type-arg] + """A subclass whose `__init__` builds state of its own.""" + + def __init__(self, metadata: Any, store_path: Any, config: Any = None) -> None: + super().__init__(metadata, store_path, config) + object.__setattr__(self, "built", tuple(self.shape)) + + +class ClassAttrAsyncArray(AsyncArray): # type: ignore[type-arg] + """A subclass with class attributes, one of them named like an internal.""" + + kind = "class-attr" + _io = "subclass-owned" + + +class OverridingAsyncArray(AsyncArray): # type: ignore[type-arg] + """A subclass that stores one more than each write gives it.""" + + async def _set_selection( + self, indexer: Any, value: Any, *, prototype: Any, fields: Any = None + ) -> None: + await super()._set_selection( + indexer, np.asarray(value) + 1, prototype=prototype, fields=fields + ) + + +SUBCLASSES = { + "tagged": TaggedAsyncArray, + "plain": PlainAsyncArray, + "slotted": SlottedAsyncArray, + "reducing": ReducingAsyncArray, + "init": InitAsyncArray, + "classattr": ClassAttrAsyncArray, + "overriding": OverridingAsyncArray, +} + + +def make_subclass_instance(name: str, base: Any) -> Any: + cls = SUBCLASSES[name] + aa = base.async_array + if cls is TaggedAsyncArray: + return cls(aa.metadata, aa.store_path, aa.config, tag="t") + obj = cls(aa.metadata, aa.store_path, aa.config) + if cls is SlottedAsyncArray: + object.__setattr__(obj, "note", "noted") + return obj + + +def run_subclass(rec: Recorder, name: str, zarr_format: int, tmp: Path) -> None: + store = new_store("local", tmp, f"sub-{name}-{zarr_format}") + base = zarr.create_array( + store, name="a", shape=(4, 3), chunks=(2, 2), dtype="int32", zarr_format=zarr_format, + attributes={"b": 1, "a": 2}, + ) # fmt: skip + base[...] = np.arange(12).reshape(4, 3) + ok, sub = rec.step("construct", lambda: make_subclass_instance(name, base)) + if not ok: + return + rec.step("type", lambda: type(sub).__qualname__) + rec.step("fields", lambda: [f.name for f in dataclasses.fields(sub)]) + rec.step( + "internal:vars.public", + lambda: ( + sorted(k for k in vars(sub) if not k.startswith("_")) + if hasattr(sub, "__dict__") + else None + ), + ) + rec.step("tag", lambda: getattr(sub, "tag", None)) + rec.step("note", lambda: getattr(sub, "note", None)) + rec.step("built", lambda: getattr(sub, "built", None)) + rec.step("kind", lambda: getattr(sub, "kind", None)) + rec.step("_io", lambda: type(sub).__dict__.get("_io")) + rec.step("describe", lambda: sub.describe() if hasattr(sub, "describe") else None) + rec.step("eq.copy", lambda: sub == copy.copy(sub)) + rec.step("read", lambda: zarr.Array(sub)[...]) + rec.step("async.setitem", lambda: zarr.core.sync.sync(sub.setitem((0, 0), 41))) + rec.step("async.getitem", lambda: zarr.core.sync.sync(sub.getitem((0, 0)))) + for how, make in { + "copy": lambda: copy.copy(sub), + "deepcopy": lambda: copy.deepcopy(sub), + "pickle": lambda: pickle.loads(pickle.dumps(sub)), + "replace": lambda: dataclasses.replace(sub), + "with_config": lambda: sub.with_config({"write_empty_chunks": True}), + }.items(): + ok, other = rec.step(f"{how}", make) + if not ok: + continue + rec.step(f"{how}.type", lambda o=other: type(o).__qualname__) + rec.step( + f"{how}.state", + lambda o=other: [getattr(o, k, None) for k in ("tag", "note", "built", "kind")], + ) + rec.step(f"{how}.metadata", lambda o=other: o.metadata.to_dict()) + rec.step(f"{how}.eq", lambda o=other: o == sub) + rec.step(f"{how}.read", lambda o=other: zarr.Array(o)[...]) + rec.step(f"{how}.write", lambda o=other: zarr.Array(o).__setitem__((0, 0), 99)) + rec.step(f"{how}.resize", lambda o=other: zarr.Array(o).resize((5, 3))) + rec.step(f"{how}.attrs", lambda o=other: zarr.Array(o).update_attributes({"c": 3})) + rec.step(f"{how}.after", lambda o=other: (o.shape, o.metadata.attributes)) + rec.step("sub.after", lambda: (sub.shape, sub.metadata.to_dict())) + rec.step("store.end", lambda: snapshot(store)) + + +# Pickles carried between versions ------------------------------------------------------------ + + +def _dump(directory: Path, name: str, make: Any) -> None: + """Pickle what `make` returns now, or a note of why it could not be made or pickled.""" + try: + data = pickle.dumps(make(), protocol=4) + except Exception as e: # noqa: BLE001 (recorded, for the loading run to compare) + data = pickle.dumps({"unpicklable": f"{type(e).__name__}: {e}"}) + (directory / f"{name}.pkl").write_bytes(data) + + +def dump_pickles(directory: Path, stores: Path) -> None: + """Pickle arrays to load in another version, over local stores under `stores`, which + the loading process sees at the same path.""" + directory.mkdir(parents=True, exist_ok=True) + for zarr_format in (2, 3): + store = zarr.storage.LocalStore(stores / f"v{zarr_format}") + arr = zarr.create_array( + store, name="a", shape=(6,), chunks=(2,), dtype="float32", zarr_format=zarr_format, + attributes={"b": 1, "a": 2}, fill_value=1.5, + ) # fmt: skip + arr[...] = np.arange(6) + _dump(directory, f"v{zarr_format}.array", lambda a=arr: a) + _dump(directory, f"v{zarr_format}.async_array", lambda a=arr: a.async_array) + _dump(directory, f"v{zarr_format}.metadata", lambda a=arr: a.metadata) + arr.update_attributes({"c": 3}) + _dump(directory, f"v{zarr_format}.array.after_attrs", lambda a=arr: a) + for name in SUBCLASSES: + _dump( + directory, + f"v{zarr_format}.sub.{name}", + lambda n=name, a=arr: make_subclass_instance(n, a), + ) + store = zarr.storage.LocalStore(stores / "sharded") + arr = zarr.create_array(store, name="a", shape=(8,), chunks=(2,), shards=(4,), dtype="int16") + arr[...] = np.arange(8) + _dump(directory, "v3.sharded", lambda a=arr: a) + for doc in ("v2-zero-grown-axis", "v3-zero-grown-axis", "v3-true"): + store = zarr.storage.LocalStore(stores / f"doc-{doc}") + key = "a/zarr.json" if DOCUMENTS[doc]["zarr_format"] == 3 else "a/.zarray" + put_document(store, key, DOCUMENTS[doc]) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + _dump(directory, f"doc.{doc}", lambda s=store: zarr.open_array(s, path="a", mode="r+")) + store = zarr.storage.LocalStore(stores / f"group-{doc}") + put_consolidated_group(store, "", DOCUMENTS[doc]) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + _dump(directory, f"group.{doc}", lambda s=store: zarr.open_group(s, mode="r+")) + + +def load_pickles(rec: Recorder, directory: Path) -> None: + for path in sorted(directory.glob("*.pkl")): + rec.scenario = f"pickle:{path.stem}" + ok, obj = rec.step("load", lambda p=path: pickle.loads(p.read_bytes())) + if ok and not isinstance(obj, dict): + _observe_loaded(rec, obj) + + +def _observe_loaded(rec: Recorder, obj: Any) -> None: + """Record what a caller sees of an object loaded from a pickle, and use it.""" + rec.step("type", lambda: type(obj).__qualname__) + if isinstance(obj, zarr.Group): + rec.step("metadata", lambda: obj.metadata.to_dict()) + rec.step("attrs.set", lambda: _set_group_attribute(obj)) + rec.step("store", lambda: snapshot(obj.store)) + ok, member = rec.step("member", lambda: obj["a"]) + if ok and all(n > 0 for n in member.shape): + rec.step("member.write", lambda: member.__setitem__(..., 1)) + rec.step("store.after_write", lambda: snapshot(obj.store)) + return + if not isinstance(obj, zarr.Array | AsyncArray): + rec.step("to_dict", lambda: obj.to_dict()) + return + arr = obj if isinstance(obj, zarr.Array) else zarr.Array(obj) + rec.step("state", lambda: [getattr(obj, k, None) for k in ("tag", "note", "built", "kind")]) + rec.step("metadata", lambda: arr.metadata.to_dict()) + rec.step("attrs", lambda: arr.attrs.asdict()) + rec.step("config", lambda: arr.async_array.config) + rec.step("read", lambda: arr[...]) + rec.step("write", lambda: arr.__setitem__((0,) * arr.ndim, 7)) + rec.step("read.after", lambda: arr[...]) + rec.step("resize", lambda: arr.resize(tuple(n + 1 for n in arr.shape))) + rec.step("attrs.update", lambda: arr.update_attributes({"loaded": True})) + rec.step("metadata.after", lambda: arr.metadata.to_dict()) + rec.step("repickle", lambda: pickle.loads(pickle.dumps(obj)).metadata.to_dict()) + + +# Entry point ------------------------------------------------------------------------------- + + +def run_all(rec: Recorder, tmp: Path, seeds: range) -> None: + for name in DOCUMENTS: + rec.scenario = f"document:{name}" + _guard(rec, lambda n=name: run_document(rec, n, tmp)) + for name in DOCUMENTS: + for prefix in GROUP_PREFIXES: + for flow in GROUP_FLOWS: + rec.scenario = f"group:{name}:{prefix or 'root'}:{flow}" + _guard(rec, lambda n=name, p=prefix, f=flow: run_group(rec, n, p, f, tmp)) + for name in SUBCLASSES: + for zarr_format in (2, 3): + rec.scenario = f"subclass:{name}:v{zarr_format}" + _guard(rec, lambda n=name, z=zarr_format: run_subclass(rec, n, z, tmp)) + for seed in seeds: + rec.scenario = f"program:{seed}" + _guard(rec, lambda s=seed: run_program(rec, s, tmp)) + shutil.rmtree(tmp / f"program-{seed}", ignore_errors=True) + + +def _guard(rec: Recorder, fn: Any) -> None: + rec.step("scenario", fn) + + +__all__ = ["Recorder", "dump_pickles", "load_pickles", "run_all"] diff --git a/tools/compat/diff.py b/tools/compat/diff.py new file mode 100644 index 0000000000..d4d53b2056 --- /dev/null +++ b/tools/compat/diff.py @@ -0,0 +1,123 @@ +""" +Compare two runs of the compatibility scenarios. + + python diff.py OLD.json NEW.json [--out DETAILS.json] [--examples N] + +Each difference is classed: + +- `value`: a step returned something else, or raised where it returned (or the reverse, + unless it is an `added` one); +- `added`: a step raised `AttributeError` or `TypeError` in the old run and returned in the + new one, as a call of something the old version lacks does; +- `message`: a step raised the same exception with another message; +- `warnings`: a step behaved the same but warned differently; +- `internal`: a step that looks at private state (its label holds `internal:`); +- `steps`: a scenario ran other steps (the first one that differs is reported). +""" + +from __future__ import annotations + +import argparse +import json +import re +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +_KIND = re.compile(r"\d+|\(.*|\[.*|\{.*") + + +def classify(old: dict[str, Any], new: dict[str, Any]) -> str | None: + if "internal:" in old["label"]: + same = {k: v for k, v in old.items() if k != "warnings"} == { + k: v for k, v in new.items() if k != "warnings" + } + return None if same else "internal" + if "raises" in old and "raises" in new: + if old["raises"] != new["raises"]: + return "value" + if old["message"] != new["message"]: + return "message" + elif "raises" in old: + added = old["raises"].rsplit(".", 1)[-1] in ("AttributeError", "TypeError") + return "added" if added else "value" + elif "raises" in new or old["value"] != new["value"]: + return "value" + if old.get("warnings") != new.get("warnings"): + return "warnings" + return None + + +def kind_of(label: str) -> str: + return ":".join(p for p in _KIND.sub("", label).split(":") if p and p != "h") + + +def compare( + old_events: list[dict[str, Any]], new_events: list[dict[str, Any]] +) -> list[dict[str, Any]]: + by_scenario: dict[str, list[list[dict[str, Any]]]] = defaultdict(lambda: [[], []]) + for side, events in enumerate((old_events, new_events)): + for event in events: + by_scenario[event["scenario"]][side].append(event) + found = [] + for scenario, (old, new) in by_scenario.items(): + for i in range(max(len(old), len(new))): + if i >= len(old) or i >= len(new) or old[i]["label"] != new[i]["label"]: + found.append( + { + "class": "steps", + "scenario": scenario, + "kind": "steps", + "old": old[i] if i < len(old) else None, + "new": new[i] if i < len(new) else None, + } + ) + break + cls = classify(old[i], new[i]) + if cls is not None: + found.append( + { + "class": cls, + "scenario": scenario, + "kind": f"{scenario.split(':', 1)[0]}:{kind_of(old[i]['label'])}", + "old": old[i], + "new": new[i], + } + ) + return found + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("old", type=Path) + parser.add_argument("new", type=Path) + parser.add_argument("--out", type=Path) + parser.add_argument("--examples", type=int, default=1) + args = parser.parse_args() + old = json.loads(args.old.read_text()) + new = json.loads(args.new.read_text()) + found = compare(old["events"], new["events"]) + print(f"{old['zarr']} -> {new['zarr']}: {len(old['events'])} steps, {len(found)} differ") + for cls, n in Counter(f["class"] for f in found).most_common(): + print(f" {cls}: {n}") + groups: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) + for f in found: + groups[f["class"], f["kind"]].append(f) + for (cls, kind), items in sorted(groups.items(), key=lambda kv: (kv[0][0], -len(kv[1]))): + print(f"\n[{cls}] {kind} x{len(items)} in {len({f['scenario'] for f in items})} scenarios") + for f in items[: args.examples]: + print(f" {f['scenario']}") + for side in ("old", "new"): + event = f[side] + text = ( + "-" + if event is None + else json.dumps({k: v for k, v in event.items() if k != "scenario"}) + ) + print(f" {side}: {text[:600]}") + if args.out is not None: + args.out.write_text(json.dumps(found, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/tools/compat/run.py b/tools/compat/run.py new file mode 100644 index 0000000000..449175eb3b --- /dev/null +++ b/tools/compat/run.py @@ -0,0 +1,51 @@ +""" +Run the compatibility scenarios under one zarr source tree. + + PYTHONPATH=SRC python run.py SRC OUT.json --tmp DIR [--seeds N] [--dump-pickles DIR --stores DIR] + PYTHONPATH=SRC python run.py SRC OUT.json --tmp DIR --load-pickles DIR + +`SRC` is the directory that holds the `zarr` package. Put it on `PYTHONPATH`, which +comes before an installed zarr; the run stops unless zarr was imported from `SRC`. +`--tmp` is wiped first; give both runs the same path, so the paths they record agree. +""" + +from __future__ import annotations + +import argparse +import json +import shutil +from pathlib import Path + +import compat_scenarios as scenarios + +import zarr + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("src", type=Path) + parser.add_argument("out", type=Path) + parser.add_argument("--tmp", type=Path, required=True) + parser.add_argument("--seeds", type=int, default=200) + parser.add_argument("--dump-pickles", type=Path) + parser.add_argument("--stores", type=Path) + parser.add_argument("--load-pickles", type=Path) + args = parser.parse_args() + + if not Path(zarr.__file__).resolve().is_relative_to(args.src.resolve()): + raise SystemExit(f"imported {zarr.__file__}, not zarr from {args.src}") + + shutil.rmtree(args.tmp, ignore_errors=True) + args.tmp.mkdir(parents=True) + rec = scenarios.Recorder(args.tmp) + if args.dump_pickles is not None: + scenarios.dump_pickles(args.dump_pickles, args.stores) + elif args.load_pickles is not None: + scenarios.load_pickles(rec, args.load_pickles) + else: + scenarios.run_all(rec, args.tmp, range(args.seeds)) + args.out.write_text(json.dumps({"zarr": zarr.__version__, "events": rec.events}, indent=1)) + + +if __name__ == "__main__": + main() From d6e1fb1f60d20befcde010dea3abca572b9108be Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 15:37:27 +0100 Subject: [PATCH 02/31] refactor(array): read and write Array through private _ArrayIO routines _ArrayIO is a value over an array's metadata, location, configuration, codec pipeline and chunk grid that holds the routines reading and writing it: selections, the repair of a stored document, resize and attribute updates. Array builds one from its AsyncArray for each operation and adopts a resize in place, so every holder of that AsyncArray sees it. An Array over a subclass of AsyncArray keeps going through the subclass. AsyncArray's leaf methods run on the same routines. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 436 ++++++++++++++++++++++++++++------------- tests/test_array_io.py | 80 ++++++++ 2 files changed, 383 insertions(+), 133 deletions(-) create mode 100644 tests/test_array_io.py diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 3735a4da18..983e04a6e9 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -161,7 +161,7 @@ from zarr.storage._utils import _relativize_path if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Coroutine, Iterator from typing import Self import numpy.typing as npt @@ -1474,16 +1474,8 @@ async def _get_selection( out: NDBuffer | None = None, fields: Fields | None = None, ) -> NDArrayLikeOrScalar: - return await _get_selection( - self.store_path, - self.metadata, - self.codec_pipeline, - self.config, - self._chunk_grid, - indexer, - prototype=prototype, - out=out, - fields=fields, + return await _ArrayIO.of(self).get_selection( + indexer, prototype=prototype, out=out, fields=fields ) async def getitem( @@ -1625,7 +1617,7 @@ def _stored_document_replaced(self) -> None: holds, which a consolidated group handle may share, then stops standing for the document it was read from (see `mark_repaired`), so no later write through either handle stores that document again.""" - object.__setattr__(self.metadata, "_stored_document", None) + _stored_document_replaced(self.metadata) async def _store_repaired_document(self) -> None: """Store the repair of this array's current stored document, if it needs one, @@ -1645,23 +1637,7 @@ async def _store_repaired_document(self) -> None: attribute update) is replaced by the repair of the document read before it, as with any two metadata writes that race. """ - if self.metadata._stored_document is None: - return - zarr_format = self.metadata.zarr_format - documents = await read_documents(self.store_path, ARRAY_DOCUMENTS[zarr_format]) - try: - current = parse_stored_array(documents, zarr_format, str(self.store_path)) - except ArrayNotFoundError: - pass - else: - if _chunk_layout(current) != _chunk_layout(self.metadata): - raise ValueError( - f"Array {str(self.store_path)!r}: the metadata stored has changed since " - "this array was opened; reopen the array to write to it. Nothing was stored." - ) - if current._stored_document is not None: - await upsert_metadata(self.store_path, current, documents) - self._stored_document_replaced() + await _ArrayIO.of(self).store_repair() async def _set_selection( self, @@ -1675,16 +1651,8 @@ async def _set_selection( # Chunks are about to be stored under the repaired metadata, so store it # first: every reader of the store then agrees with them. await self._store_repaired_document() - return await _set_selection( - self.store_path, - self.metadata, - self.codec_pipeline, - self.config, - self._chunk_grid, - indexer, - value, - prototype=prototype, - fields=fields, + return await _ArrayIO.of(self).set_selection( + indexer, value, prototype=prototype, fields=fields ) async def setitem( @@ -1920,6 +1888,220 @@ def _info( ) +def _stored_document_replaced(metadata: ArrayMetadata) -> None: + """Record that the store no longer holds a document of the array `metadata` was read + from that needs a repair: it holds the repair, a valid document, or none. `metadata`, + which several handles may share, then stops standing for that document (see + `mark_repaired`), so no later write through any of them stores it again.""" + object.__setattr__(metadata, "_stored_document", None) + + +def _appended( + shape: tuple[int, ...], data: npt.ArrayLike, axis: int +) -> tuple[Any, tuple[int, ...], tuple[slice, ...]]: + """For appending `data` along `axis` to an array of `shape`: `data` as an array, the + new shape, and the selection the data is written to.""" + # ensure data is array-like + if not hasattr(data, "shape"): + data = np.asanyarray(data) + + self_shape_preserved = tuple(s for i, s in enumerate(shape) if i != axis) + data_shape_preserved = tuple(s for i, s in enumerate(data.shape) if i != axis) + if self_shape_preserved != data_shape_preserved: + raise ValueError( + f"shape of data to append is not compatible with the array. " + f"The shape of the data is ({data_shape_preserved})" + f"and the shape of the array is ({self_shape_preserved})." + "All dimensions must match except for the dimension being " + "appended." + ) + new_shape = tuple( + shape[i] if i != axis else shape[i] + data.shape[i] for i in range(len(shape)) + ) + selection = tuple( + slice(None) if i != axis else slice(shape[i], new_shape[i]) for i in range(len(shape)) + ) + return data, new_shape, selection + + +async def _write_storing_repair( + io: _ArrayIO, + indexer: Indexer, + value: npt.ArrayLike, + *, + prototype: BufferPrototype, + fields: Fields | None = None, +) -> None: + """Write `value` through `io`, first storing the repair of the stored document if + chunks are about to be written, as `AsyncArray` writes.""" + if product(indexer.shape) > 0: + # Chunks are about to be stored under the repaired metadata, so store it + # first: every reader of the store then agrees with them. + await io.store_repair() + await io.set_selection(indexer, value, prototype=prototype, fields=fields) + + +@dataclass(frozen=True, slots=True) +class _ArrayIO: + """The routines that read and write an array, over its metadata, its location in a + store, its runtime configuration, and the codec pipeline and chunk grid derived from + them. + + A value with no state beyond these fields: `Array` and `AsyncArray` build one from + their own fields for each operation, so every routine that reads or writes an + array runs here. An operation that changes the stored metadata stores it and + returns the array as it then is; it leaves the arrays it was built from alone. + Nothing is repaired implicitly: `store_repair` stores the repair of a stored + document, and the callers decide when. + """ + + metadata: ArrayMetadata + store_path: StorePath + config: ArrayConfig + codec_pipeline: CodecPipeline + chunk_grid: ChunkGrid + + @classmethod + def of(cls, array: AsyncArray[Any]) -> _ArrayIO: + """The routines over the fields of `array`, as they are now.""" + return cls( + array.metadata, array.store_path, array.config, array.codec_pipeline, array._chunk_grid + ) + + async def get_selection( + self, + indexer: Indexer, + *, + prototype: BufferPrototype, + out: NDBuffer | None = None, + fields: Fields | None = None, + ) -> NDArrayLikeOrScalar: + return await _get_selection( + self.store_path, + self.metadata, + self.codec_pipeline, + self.config, + self.chunk_grid, + indexer, + prototype=prototype, + out=out, + fields=fields, + ) + + async def set_selection( + self, + indexer: Indexer, + value: npt.ArrayLike, + *, + prototype: BufferPrototype, + fields: Fields | None = None, + ) -> None: + await _set_selection( + self.store_path, + self.metadata, + self.codec_pipeline, + self.config, + self.chunk_grid, + indexer, + value, + prototype=prototype, + fields=fields, + ) + + async def store_repair(self) -> None: + """Store the repair of the array's current stored document, if it needs one, + before chunks are written under this metadata. + + Only for metadata read from a document whose repair moves chunks (see + `zarr.core.metadata.repair`). The document is read again, because the store may + hold a newer one than this metadata. If that one lays out chunks differently + (another writer stored a different chunk size since), chunks written under this + metadata would be found by no reader, so it raises and stores nothing. If it + needs no repair (the array was re-saved since, possibly by another + implementation), it is left as written; if there is none, there is nothing to + repair. + + Storing the same repair twice is harmless, so handles that write chunks + concurrently need no coordination. The read and the store are not one atomic + step, though: a metadata write by another handle between them (a resize, an + attribute update) is replaced by the repair of the document read before it, as + with any two metadata writes that race. + """ + if self.metadata._stored_document is None: + return + zarr_format = self.metadata.zarr_format + documents = await read_documents(self.store_path, ARRAY_DOCUMENTS[zarr_format]) + try: + current = parse_stored_array(documents, zarr_format, str(self.store_path)) + except ArrayNotFoundError: + pass + else: + if _chunk_layout(current) != _chunk_layout(self.metadata): + raise ValueError( + f"Array {str(self.store_path)!r}: the metadata stored has changed since " + "this array was opened; reopen the array to write to it. Nothing was stored." + ) + if current._stored_document is not None: + await upsert_metadata(self.store_path, current, documents) + _stored_document_replaced(self.metadata) + + async def resize(self, new_shape: ShapeLike, delete_outside_chunks: bool = True) -> _ArrayIO: + """Store the metadata of the array resized to `new_shape`, deleting the chunks + outside it if `delete_outside_chunks`, and return the array as resized. + + The new metadata is encoded before any chunk is deleted: metadata that cannot be + stored then fails with the store untouched.""" + new_shape = parse_shapelike(new_shape) + if len(new_shape) != len(self.metadata.shape): + raise ValueError( + f"The new shape must have the same number of dimensions as the array. " + f"Got {len(new_shape)} dimension(s), expected {len(self.metadata.shape)}." + ) + + new_metadata = self.metadata.update_shape(new_shape) + new_chunk_grid = ChunkGrid.from_metadata(new_metadata) + documents = encode_documents(self.store_path, new_metadata) + + if delete_outside_chunks: + old_grid_shape = self.chunk_grid.grid_shape + new_grid_shape = new_chunk_grid.grid_shape + # Chunks of the old grid outside the box it shares with the new grid. + # Zero whenever no axis loses a whole chunk, including pure growth. + n_delete = math.prod(old_grid_shape) - math.prod( + min(old, new) for old, new in zip(old_grid_shape, new_grid_shape, strict=True) + ) + if n_delete > 0: + # `None` lifts the I/O concurrency limit, but the worker pool still + # needs a bound; 1000 keeps the pool far smaller than the grid. + limit = zarr_config.get("async.concurrency") or 1000 + await concurrent_foreach( + ( + (self.store_path / self.metadata.encode_chunk_key(coords),) + for coords in _iter_chunk_coords_to_delete(old_grid_shape, new_grid_shape) + ), + _delete_chunk, + min(limit, n_delete), + ) + + await store_documents(self.store_path, documents) + _stored_document_replaced(self.metadata) + return replace(self, metadata=new_metadata, chunk_grid=new_chunk_grid) + + async def update_attributes(self, new_attributes: dict[str, JSON]) -> _ArrayIO: + """Merge `new_attributes` into the array's attributes and store its metadata. + + The attributes change in place, as they always have through an array: every + holder of this metadata sees them.""" + self.metadata.attributes.update(new_attributes) + await save_metadata(self.store_path, self.metadata) + _stored_document_replaced(self.metadata) + return self + + +async def _delete_chunk(key: StorePath) -> None: + await key.delete() + + # TODO: Array can be a frozen data class again once property setters (e.g. shape) are removed @dataclass(frozen=False) class Array[T_ArrayMetadata: (ArrayV2Metadata, ArrayV3Metadata)]: @@ -1939,6 +2121,51 @@ def async_array(self) -> AsyncArray[T_ArrayMetadata]: """ return self._async_array + def _arrayio(self) -> _ArrayIO | None: + """The routines this array reads and writes through, over its fields; `None` + when it wraps a subclass of `AsyncArray`, whose overrides it keeps going + through.""" + async_array = self.async_array + if type(async_array) is not AsyncArray: + return None + return _ArrayIO.of(async_array) + + def _adopt(self, resized: _ArrayIO) -> None: + """Make `resized` this array's metadata and chunk grid, as a resize through its + `AsyncArray` does: in place, so every holder of that `AsyncArray` sees it.""" + object.__setattr__(self.async_array, "metadata", resized.metadata) + object.__setattr__(self.async_array, "_chunk_grid", resized.chunk_grid) + + def _read_selection( + self, + indexer: Indexer, + *, + prototype: BufferPrototype, + out: NDBuffer | None = None, + fields: Fields | None = None, + ) -> Coroutine[Any, Any, NDArrayLikeOrScalar]: + io = self._arrayio() + if io is None: + return self.async_array._get_selection( + indexer, prototype=prototype, out=out, fields=fields + ) + return io.get_selection(indexer, prototype=prototype, out=out, fields=fields) + + def _write_selection( + self, + indexer: Indexer, + value: npt.ArrayLike, + *, + prototype: BufferPrototype, + fields: Fields | None = None, + ) -> Coroutine[Any, Any, None]: + io = self._arrayio() + if io is None: + return self.async_array._set_selection( + indexer, value, prototype=prototype, fields=fields + ) + return _write_storing_repair(io, indexer, value, prototype=prototype, fields=fields) + @property def config(self) -> ArrayConfig: """ @@ -2976,7 +3203,7 @@ def get_basic_selection( if prototype is None: prototype = default_buffer_prototype() return sync( - self.async_array._get_selection( + self._read_selection( BasicIndexer(selection, self.shape, self._chunk_grid), out=out, fields=fields, @@ -3085,7 +3312,7 @@ def set_basic_selection( if prototype is None: prototype = default_buffer_prototype() indexer = BasicIndexer(selection, self.shape, self._chunk_grid) - sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) + sync(self._write_selection(indexer, value, fields=fields, prototype=prototype)) def get_orthogonal_selection( self, @@ -3214,9 +3441,7 @@ def get_orthogonal_selection( prototype = default_buffer_prototype() indexer = OrthogonalIndexer(selection, self.shape, self._chunk_grid) return sync( - self.async_array._get_selection( - indexer=indexer, out=out, fields=fields, prototype=prototype - ) + self._read_selection(indexer=indexer, out=out, fields=fields, prototype=prototype) ) def set_orthogonal_selection( @@ -3331,9 +3556,7 @@ def set_orthogonal_selection( if prototype is None: prototype = default_buffer_prototype() indexer = OrthogonalIndexer(selection, self.shape, self._chunk_grid) - return sync( - self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype) - ) + return sync(self._write_selection(indexer, value, fields=fields, prototype=prototype)) def get_mask_selection( self, @@ -3420,9 +3643,7 @@ def get_mask_selection( prototype = default_buffer_prototype() indexer = MaskIndexer(mask, self.shape, self._chunk_grid) return sync( - self.async_array._get_selection( - indexer=indexer, out=out, fields=fields, prototype=prototype - ) + self._read_selection(indexer=indexer, out=out, fields=fields, prototype=prototype) ) def set_mask_selection( @@ -3508,7 +3729,7 @@ def set_mask_selection( if prototype is None: prototype = default_buffer_prototype() indexer = MaskIndexer(mask, self.shape, self._chunk_grid) - sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) + sync(self._write_selection(indexer, value, fields=fields, prototype=prototype)) def get_coordinate_selection( self, @@ -3597,9 +3818,7 @@ def get_coordinate_selection( prototype = default_buffer_prototype() indexer = CoordinateIndexer(selection, self.shape, self._chunk_grid) out_array = sync( - self.async_array._get_selection( - indexer=indexer, out=out, fields=fields, prototype=prototype - ) + self._read_selection(indexer=indexer, out=out, fields=fields, prototype=prototype) ) if hasattr(out_array, "shape"): @@ -3709,7 +3928,7 @@ def set_coordinate_selection( f"elements with an array of {value.shape[0]} elements." ) - sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) + sync(self._write_selection(indexer, value, fields=fields, prototype=prototype)) def get_block_selection( self, @@ -3810,9 +4029,7 @@ def get_block_selection( prototype = default_buffer_prototype() indexer = BlockIndexer(selection, self.shape, self._chunk_grid) return sync( - self.async_array._get_selection( - indexer=indexer, out=out, fields=fields, prototype=prototype - ) + self._read_selection(indexer=indexer, out=out, fields=fields, prototype=prototype) ) def set_block_selection( @@ -3909,7 +4126,7 @@ def set_block_selection( if prototype is None: prototype = default_buffer_prototype() indexer = BlockIndexer(selection, self.shape, self._chunk_grid) - sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) + sync(self._write_selection(indexer, value, fields=fields, prototype=prototype)) @property def vindex(self) -> VIndex: @@ -3973,7 +4190,11 @@ def resize(self, new_shape: ShapeLike) -> None: #>(50, 50) ``` """ - sync(self.async_array.resize(new_shape)) + io = self._arrayio() + if io is None: + sync(self.async_array.resize(new_shape)) + else: + self._adopt(sync(io.resize(new_shape))) def append(self, data: npt.ArrayLike, axis: int = 0) -> tuple[int, ...]: """Append `data` to `axis`. @@ -4009,7 +4230,18 @@ def append(self, data: npt.ArrayLike, axis: int = 0) -> tuple[int, ...]: >>> z.shape (20000, 2000) """ - return sync(self.async_array.append(data, axis=axis)) + io = self._arrayio() + if io is None: + return sync(self.async_array.append(data, axis=axis)) + data, new_shape, selection = _appended(io.metadata.shape, data, axis) + resized = sync(io.resize(new_shape)) + # Adopted before the data is written, as a resize through `AsyncArray` is. + self._adopt(resized) + indexer = BasicIndexer( + selection, shape=resized.metadata.shape, chunk_grid=resized.chunk_grid + ) + sync(_write_storing_repair(resized, indexer, data, prototype=default_buffer_prototype())) + return new_shape def update_attributes(self, new_attributes: dict[str, JSON]) -> Self: """ @@ -4036,8 +4268,12 @@ def update_attributes(self, new_attributes: dict[str, JSON]) -> Self: - The updated attributes will be merged with existing attributes, and any conflicts will be overwritten by the new values. """ - new_array = sync(self.async_array.update_attributes(new_attributes)) - return type(self)(new_array) + io = self._arrayio() + if io is None: + new_array = sync(self.async_array.update_attributes(new_attributes)) + return type(self)(new_array) + sync(io.update_attributes(new_attributes)) + return type(self)(self.async_array) def __repr__(self) -> str: return f"" @@ -5948,52 +6184,11 @@ async def _resize( If True (default), chunks that fall outside the new shape will be deleted. If False, the data in those chunks will be preserved. """ - new_shape = parse_shapelike(new_shape) - if len(new_shape) != len(array.metadata.shape): - raise ValueError( - f"The new shape must have the same number of dimensions as the array. " - f"Got {len(new_shape)} dimension(s), expected {len(array.metadata.shape)}." - ) - - new_metadata = array.metadata.update_shape(new_shape) - new_chunk_grid = ChunkGrid.from_metadata(new_metadata) - - # Encode the new metadata before deleting any chunk: metadata that cannot be stored - # then fails with the store untouched. - documents = encode_documents(array.store_path, new_metadata) - - if delete_outside_chunks: - old_grid_shape = array._chunk_grid.grid_shape - new_grid_shape = new_chunk_grid.grid_shape - # Chunks of the old grid outside the box it shares with the new grid. - # Zero whenever no axis loses a whole chunk, including pure growth. - n_delete = math.prod(old_grid_shape) - math.prod( - min(old, new) for old, new in zip(old_grid_shape, new_grid_shape, strict=True) - ) - if n_delete > 0: - - async def _delete_chunk(coords: tuple[int, ...]) -> None: - await (array.store_path / array.metadata.encode_chunk_key(coords)).delete() - - # `None` lifts the I/O concurrency limit, but the worker pool still - # needs a bound; 1000 keeps the pool far smaller than the grid. - limit = zarr_config.get("async.concurrency") or 1000 - await concurrent_foreach( - ( - (coords,) - for coords in _iter_chunk_coords_to_delete(old_grid_shape, new_grid_shape) - ), - _delete_chunk, - min(limit, n_delete), - ) - - # Write new metadata - await store_documents(array.store_path, documents) - array._stored_document_replaced() + resized = await _ArrayIO.of(array).resize(new_shape, delete_outside_chunks) # Update metadata and chunk_grid (in place) - object.__setattr__(array, "metadata", new_metadata) - object.__setattr__(array, "_chunk_grid", new_chunk_grid) + object.__setattr__(array, "metadata", resized.metadata) + object.__setattr__(array, "_chunk_grid", resized.chunk_grid) async def _append( @@ -6023,37 +6218,12 @@ async def _append( The size of all dimensions other than `axis` must match between the array and `data`. """ - # ensure data is array-like - if not hasattr(data, "shape"): - data = np.asanyarray(data) - - self_shape_preserved = tuple(s for i, s in enumerate(array.shape) if i != axis) - data_shape_preserved = tuple(s for i, s in enumerate(data.shape) if i != axis) - if self_shape_preserved != data_shape_preserved: - raise ValueError( - f"shape of data to append is not compatible with the array. " - f"The shape of the data is ({data_shape_preserved})" - f"and the shape of the array is ({self_shape_preserved})." - "All dimensions must match except for the dimension being " - "appended." - ) - # remember old shape - old_shape = array.shape - - # determine new shape - new_shape = tuple( - array.shape[i] if i != axis else array.shape[i] + data.shape[i] - for i in range(len(array.shape)) - ) + data, new_shape, append_selection = _appended(array.shape, data, axis) # resize await _resize(array, new_shape) # store data - append_selection = tuple( - slice(None) if i != axis else slice(old_shape[i], new_shape[i]) - for i in range(len(array.shape)) - ) await array.setitem(append_selection, data) return new_shape diff --git a/tests/test_array_io.py b/tests/test_array_io.py new file mode 100644 index 0000000000..545da85183 --- /dev/null +++ b/tests/test_array_io.py @@ -0,0 +1,80 @@ +"""`Array` reads and writes through the private `_ArrayIO` routines.""" + +from __future__ import annotations + +from typing import Any + +import numpy as np +import pytest + +import zarr +from zarr.core.array import Array, AsyncArray, _ArrayIO +from zarr.storage import MemoryStore + + +class _CountingAsyncArray(AsyncArray[Any]): + """An `AsyncArray` subclass that counts the reads and writes it is asked for.""" + + async def _get_selection(self, *args: Any, **kwargs: Any) -> Any: + vars(self).setdefault("_reads", []).append(1) + return await super()._get_selection(*args, **kwargs) + + async def _set_selection(self, *args: Any, **kwargs: Any) -> None: + vars(self).setdefault("_writes", []).append(1) + await super()._set_selection(*args, **kwargs) + + +def _operate(array: Array[Any]) -> None: + array[:] = np.arange(4) + array.oindex[np.array([0, 1])] = [7, 8] + array.resize((6,)) + array.append(np.array([4, 5])) + array.attrs["a"] = 1 + _ = array[:], array.oindex[np.array([0])], array.vindex[np.array([1])], array.blocks[0] + + +@pytest.mark.parametrize("subclass", [False, True]) +def test_array_reads_and_writes_through_array_io(subclass: bool) -> None: + """An `Array` over an `AsyncArray` reads and writes through `_ArrayIO`; over a + subclass of `AsyncArray`, through the subclass, so its overrides are called. Both + give the same array, and every holder of the wrapped `AsyncArray` sees its resizes.""" + created = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") + wrapped = created.async_array + if subclass: + wrapped = _CountingAsyncArray(wrapped.metadata, wrapped.store_path, wrapped.config) + array = Array(wrapped) + other = Array(wrapped) + assert (array._arrayio() is None) is subclass + + _operate(array) + + np.testing.assert_array_equal(array[:], [7, 8, 2, 3, 0, 0, 4, 5]) + assert other.shape == wrapped.shape == (8,) + assert dict(other.attrs) == {"a": 1} + counted = (len(vars(wrapped).get("_reads", [])), len(vars(wrapped).get("_writes", []))) + assert (counted != (0, 0)) is subclass + + +def test_a_resize_through_the_wrapped_async_array_shows_through_the_array() -> None: + array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") + zarr.core.sync.sync(array.async_array.resize((6,))) + array[4:] = [1, 2] + np.testing.assert_array_equal(array[:], [0, 0, 0, 0, 1, 2]) + + +def test_array_io_resize_returns_a_new_value() -> None: + """`_ArrayIO.resize` stores the resized metadata and returns the resized array; the + value it was called on, and the `AsyncArray` it was built from, are unchanged.""" + array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") + io = _ArrayIO.of(array.async_array) + + resized = zarr.core.sync.sync(io.resize((6,))) + + assert (io.metadata.shape, resized.metadata.shape, array.shape) == ((4,), (6,), (4,)) + assert zarr.open_array(array.store_path.store).shape == (6,) + + +def test_array_io_resize_rejects_another_number_of_dimensions() -> None: + array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") + with pytest.raises(ValueError, match="same number of dimensions"): + zarr.core.sync.sync(_ArrayIO.of(array.async_array).resize((4, 4))) From effcf45337bb98f836afad7e982764c50d3f0442 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 16:04:02 +0100 Subject: [PATCH 03/31] refactor(array): split the routines into AsyncArrayIO and a sync ArrayIO AsyncArrayIO holds the routines that read and write an array; it repairs nothing implicitly and refuses chunk writes under metadata whose stored document needs a repair that moves chunks until store_repair has stored it. ArrayIO runs each AsyncArrayIO operation on the event loop its SyncContext returns. AsyncArray builds an AsyncArrayIO from its fields for each operation, and Array goes through AsyncArray as before, so hooks on AsyncArray's methods still see Array's reads and writes. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 307 ++++++++++++++++++++++++++--------------- tests/test_array_io.py | 176 ++++++++++++++--------- 2 files changed, 300 insertions(+), 183 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 983e04a6e9..e6b5f0d88c 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -142,7 +142,7 @@ create_chunk_grid_metadata, parse_node_type_array, ) -from zarr.core.sync import sync +from zarr.core.sync import _get_loop, sync from zarr.errors import ( ArrayNotFoundError, ChunkNotFoundError, @@ -161,7 +161,8 @@ from zarr.storage._utils import _relativize_path if TYPE_CHECKING: - from collections.abc import Coroutine, Iterator + from asyncio import AbstractEventLoop + from collections.abc import Callable, Coroutine, Iterator from typing import Self import numpy.typing as npt @@ -1474,7 +1475,7 @@ async def _get_selection( out: NDBuffer | None = None, fields: Fields | None = None, ) -> NDArrayLikeOrScalar: - return await _ArrayIO.of(self).get_selection( + return await AsyncArrayIO._of(self).get_selection( indexer, prototype=prototype, out=out, fields=fields ) @@ -1637,7 +1638,7 @@ async def _store_repaired_document(self) -> None: attribute update) is replaced by the repair of the document read before it, as with any two metadata writes that race. """ - await _ArrayIO.of(self).store_repair() + await AsyncArrayIO._of(self).store_repair() async def _set_selection( self, @@ -1651,7 +1652,7 @@ async def _set_selection( # Chunks are about to be stored under the repaired metadata, so store it # first: every reader of the store then agrees with them. await self._store_repaired_document() - return await _ArrayIO.of(self).set_selection( + return await AsyncArrayIO._of(self).set_selection( indexer, value, prototype=prototype, fields=fields ) @@ -1924,35 +1925,23 @@ def _appended( return data, new_shape, selection -async def _write_storing_repair( - io: _ArrayIO, - indexer: Indexer, - value: npt.ArrayLike, - *, - prototype: BufferPrototype, - fields: Fields | None = None, -) -> None: - """Write `value` through `io`, first storing the repair of the stored document if - chunks are about to be written, as `AsyncArray` writes.""" - if product(indexer.shape) > 0: - # Chunks are about to be stored under the repaired metadata, so store it - # first: every reader of the store then agrees with them. - await io.store_repair() - await io.set_selection(indexer, value, prototype=prototype, fields=fields) +async def _delete_chunk(key: StorePath) -> None: + await key.delete() @dataclass(frozen=True, slots=True) -class _ArrayIO: - """The routines that read and write an array, over its metadata, its location in a - store, its runtime configuration, and the codec pipeline and chunk grid derived from - them. - - A value with no state beyond these fields: `Array` and `AsyncArray` build one from - their own fields for each operation, so every routine that reads or writes an - array runs here. An operation that changes the stored metadata stores it and - returns the array as it then is; it leaves the arrays it was built from alone. - Nothing is repaired implicitly: `store_repair` stores the repair of a stored - document, and the callers decide when. +class AsyncArrayIO: + """Reads and writes an array: its metadata, bound to a location in a store, with its + runtime configuration and the codec pipeline and chunk grid derived from them. + + A value. An operation that changes the stored metadata (`resize`, + `update_attributes`) stores it and returns the array as it then is; chunk reads and + writes leave the value as it is. Nothing is repaired implicitly: if the metadata was + read from a stored document that needs a repair that moves chunks, writing chunks + raises until `store_repair` has stored that repair. + + `AsyncArray` reads and writes through one of these, built from its fields for each + operation. """ metadata: ArrayMetadata @@ -1962,12 +1951,43 @@ class _ArrayIO: chunk_grid: ChunkGrid @classmethod - def of(cls, array: AsyncArray[Any]) -> _ArrayIO: - """The routines over the fields of `array`, as they are now.""" + def from_array(cls, array: AsyncArray[Any] | Array[Any]) -> AsyncArrayIO: + """The array `array` reads and writes, as it is now.""" + return cls._of(array.async_array if isinstance(array, Array) else array) + + @classmethod + def _of(cls, array: AsyncArray[Any]) -> AsyncArrayIO: return cls( array.metadata, array.store_path, array.config, array.codec_pipeline, array._chunk_grid ) + @property + def shape(self) -> tuple[int, ...]: + """The shape of the array.""" + return self.metadata.shape + + async def getitem( + self, selection: BasicSelection, *, prototype: BufferPrototype | None = None + ) -> NDArrayLikeOrScalar: + """The values at `selection`, by basic indexing.""" + indexer = BasicIndexer(selection, shape=self.metadata.shape, chunk_grid=self.chunk_grid) + return await self.get_selection( + indexer, prototype=default_buffer_prototype() if prototype is None else prototype + ) + + async def setitem( + self, + selection: BasicSelection, + value: npt.ArrayLike, + *, + prototype: BufferPrototype | None = None, + ) -> None: + """Write `value` at `selection`, by basic indexing.""" + indexer = BasicIndexer(selection, shape=self.metadata.shape, chunk_grid=self.chunk_grid) + await self.set_selection( + indexer, value, prototype=default_buffer_prototype() if prototype is None else prototype + ) + async def get_selection( self, indexer: Indexer, @@ -1976,6 +1996,7 @@ async def get_selection( out: NDBuffer | None = None, fields: Fields | None = None, ) -> NDArrayLikeOrScalar: + """The values `indexer` selects.""" return await _get_selection( self.store_path, self.metadata, @@ -1996,6 +2017,18 @@ async def set_selection( prototype: BufferPrototype, fields: Fields | None = None, ) -> None: + """Write `value` to what `indexer` selects. + + Raises `ValueError`, writing nothing, if chunks would be written under metadata + read from a stored document whose repair moves chunks and has not been stored: + no reader of that document would find them (see `store_repair`). + """ + if product(indexer.shape) > 0 and self.metadata._stored_document is not None: + raise ValueError( + f"Array {str(self.store_path)!r}: the stored metadata document needs a " + "repair that moves chunks; call `store_repair()` before writing chunks. " + "Nothing was written." + ) await _set_selection( self.store_path, self.metadata, @@ -2009,8 +2042,8 @@ async def set_selection( ) async def store_repair(self) -> None: - """Store the repair of the array's current stored document, if it needs one, - before chunks are written under this metadata. + """Store the repair of the array's current stored document, if it needs one + that moves chunks. Only for metadata read from a document whose repair moves chunks (see `zarr.core.metadata.repair`). The document is read again, because the store may @@ -2045,7 +2078,9 @@ async def store_repair(self) -> None: await upsert_metadata(self.store_path, current, documents) _stored_document_replaced(self.metadata) - async def resize(self, new_shape: ShapeLike, delete_outside_chunks: bool = True) -> _ArrayIO: + async def resize( + self, new_shape: ShapeLike, delete_outside_chunks: bool = True + ) -> AsyncArrayIO: """Store the metadata of the array resized to `new_shape`, deleting the chunks outside it if `delete_outside_chunks`, and return the array as resized. @@ -2087,7 +2122,7 @@ async def resize(self, new_shape: ShapeLike, delete_outside_chunks: bool = True) _stored_document_replaced(self.metadata) return replace(self, metadata=new_metadata, chunk_grid=new_chunk_grid) - async def update_attributes(self, new_attributes: dict[str, JSON]) -> _ArrayIO: + async def update_attributes(self, new_attributes: dict[str, JSON]) -> AsyncArrayIO: """Merge `new_attributes` into the array's attributes and store its metadata. The attributes change in place, as they always have through an array: every @@ -2098,73 +2133,124 @@ async def update_attributes(self, new_attributes: dict[str, JSON]) -> _ArrayIO: return self -async def _delete_chunk(key: StorePath) -> None: - await key.delete() +@dataclass(frozen=True, slots=True, kw_only=True) +class SyncContext: + """How a synchronous API runs the coroutines it is built on.""" + loop: Callable[[], AbstractEventLoop] = _get_loop + """Returns the event loop to run each coroutine on, from a thread other than the + loop's own. The default is zarr's own loop, on its IO thread.""" -# TODO: Array can be a frozen data class again once property setters (e.g. shape) are removed -@dataclass(frozen=False) -class Array[T_ArrayMetadata: (ArrayV2Metadata, ArrayV3Metadata)]: - """ - A Zarr array. + +@dataclass(frozen=True, slots=True) +class ArrayIO: + """Reads and writes an array synchronously: each operation runs the matching + `AsyncArrayIO` operation on the event loop its context returns. + + A value, as `AsyncArrayIO` is: `resize` and `update_attributes` return the array + as it then is. """ - _async_array: AsyncArray[T_ArrayMetadata] + async_io: AsyncArrayIO + context: SyncContext = field(default_factory=SyncContext) + + @classmethod + def from_array( + cls, array: AsyncArray[Any] | Array[Any], *, context: SyncContext | None = None + ) -> ArrayIO: + """The array `array` reads and writes, as it is now.""" + return cls(AsyncArrayIO.from_array(array), SyncContext() if context is None else context) + + def _run[T](self, coroutine: Coroutine[Any, Any, T]) -> T: + return sync(coroutine, loop=self.context.loop()) @property - def async_array(self) -> AsyncArray[T_ArrayMetadata]: - """An asynchronous version of the current array. Useful for batching requests. + def metadata(self) -> ArrayMetadata: + """The array's metadata.""" + return self.async_io.metadata - Returns - ------- - An asynchronous array whose metadata + store matches that of this synchronous array. - """ - return self._async_array + @property + def store_path(self) -> StorePath: + """Where in a store the array is.""" + return self.async_io.store_path - def _arrayio(self) -> _ArrayIO | None: - """The routines this array reads and writes through, over its fields; `None` - when it wraps a subclass of `AsyncArray`, whose overrides it keeps going - through.""" - async_array = self.async_array - if type(async_array) is not AsyncArray: - return None - return _ArrayIO.of(async_array) + @property + def shape(self) -> tuple[int, ...]: + """The shape of the array.""" + return self.async_io.shape - def _adopt(self, resized: _ArrayIO) -> None: - """Make `resized` this array's metadata and chunk grid, as a resize through its - `AsyncArray` does: in place, so every holder of that `AsyncArray` sees it.""" - object.__setattr__(self.async_array, "metadata", resized.metadata) - object.__setattr__(self.async_array, "_chunk_grid", resized.chunk_grid) + def getitem( + self, selection: BasicSelection, *, prototype: BufferPrototype | None = None + ) -> NDArrayLikeOrScalar: + """See `AsyncArrayIO.getitem`.""" + return self._run(self.async_io.getitem(selection, prototype=prototype)) + + def setitem( + self, + selection: BasicSelection, + value: npt.ArrayLike, + *, + prototype: BufferPrototype | None = None, + ) -> None: + """See `AsyncArrayIO.setitem`.""" + self._run(self.async_io.setitem(selection, value, prototype=prototype)) - def _read_selection( + def get_selection( self, indexer: Indexer, *, prototype: BufferPrototype, out: NDBuffer | None = None, fields: Fields | None = None, - ) -> Coroutine[Any, Any, NDArrayLikeOrScalar]: - io = self._arrayio() - if io is None: - return self.async_array._get_selection( - indexer, prototype=prototype, out=out, fields=fields - ) - return io.get_selection(indexer, prototype=prototype, out=out, fields=fields) + ) -> NDArrayLikeOrScalar: + """See `AsyncArrayIO.get_selection`.""" + return self._run( + self.async_io.get_selection(indexer, prototype=prototype, out=out, fields=fields) + ) - def _write_selection( + def set_selection( self, indexer: Indexer, value: npt.ArrayLike, *, prototype: BufferPrototype, fields: Fields | None = None, - ) -> Coroutine[Any, Any, None]: - io = self._arrayio() - if io is None: - return self.async_array._set_selection( - indexer, value, prototype=prototype, fields=fields - ) - return _write_storing_repair(io, indexer, value, prototype=prototype, fields=fields) + ) -> None: + """See `AsyncArrayIO.set_selection`.""" + self._run(self.async_io.set_selection(indexer, value, prototype=prototype, fields=fields)) + + def store_repair(self) -> None: + """See `AsyncArrayIO.store_repair`.""" + self._run(self.async_io.store_repair()) + + def resize(self, new_shape: ShapeLike, delete_outside_chunks: bool = True) -> ArrayIO: + """See `AsyncArrayIO.resize`.""" + resized = self._run(self.async_io.resize(new_shape, delete_outside_chunks)) + return replace(self, async_io=resized) + + def update_attributes(self, new_attributes: dict[str, JSON]) -> ArrayIO: + """See `AsyncArrayIO.update_attributes`.""" + return replace(self, async_io=self._run(self.async_io.update_attributes(new_attributes))) + + +# TODO: Array can be a frozen data class again once property setters (e.g. shape) are removed +@dataclass(frozen=False) +class Array[T_ArrayMetadata: (ArrayV2Metadata, ArrayV3Metadata)]: + """ + A Zarr array. + """ + + _async_array: AsyncArray[T_ArrayMetadata] + + @property + def async_array(self) -> AsyncArray[T_ArrayMetadata]: + """An asynchronous version of the current array. Useful for batching requests. + + Returns + ------- + An asynchronous array whose metadata + store matches that of this synchronous array. + """ + return self._async_array @property def config(self) -> ArrayConfig: @@ -3203,7 +3289,7 @@ def get_basic_selection( if prototype is None: prototype = default_buffer_prototype() return sync( - self._read_selection( + self.async_array._get_selection( BasicIndexer(selection, self.shape, self._chunk_grid), out=out, fields=fields, @@ -3312,7 +3398,7 @@ def set_basic_selection( if prototype is None: prototype = default_buffer_prototype() indexer = BasicIndexer(selection, self.shape, self._chunk_grid) - sync(self._write_selection(indexer, value, fields=fields, prototype=prototype)) + sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) def get_orthogonal_selection( self, @@ -3441,7 +3527,9 @@ def get_orthogonal_selection( prototype = default_buffer_prototype() indexer = OrthogonalIndexer(selection, self.shape, self._chunk_grid) return sync( - self._read_selection(indexer=indexer, out=out, fields=fields, prototype=prototype) + self.async_array._get_selection( + indexer=indexer, out=out, fields=fields, prototype=prototype + ) ) def set_orthogonal_selection( @@ -3556,7 +3644,9 @@ def set_orthogonal_selection( if prototype is None: prototype = default_buffer_prototype() indexer = OrthogonalIndexer(selection, self.shape, self._chunk_grid) - return sync(self._write_selection(indexer, value, fields=fields, prototype=prototype)) + return sync( + self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype) + ) def get_mask_selection( self, @@ -3643,7 +3733,9 @@ def get_mask_selection( prototype = default_buffer_prototype() indexer = MaskIndexer(mask, self.shape, self._chunk_grid) return sync( - self._read_selection(indexer=indexer, out=out, fields=fields, prototype=prototype) + self.async_array._get_selection( + indexer=indexer, out=out, fields=fields, prototype=prototype + ) ) def set_mask_selection( @@ -3729,7 +3821,7 @@ def set_mask_selection( if prototype is None: prototype = default_buffer_prototype() indexer = MaskIndexer(mask, self.shape, self._chunk_grid) - sync(self._write_selection(indexer, value, fields=fields, prototype=prototype)) + sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) def get_coordinate_selection( self, @@ -3818,7 +3910,9 @@ def get_coordinate_selection( prototype = default_buffer_prototype() indexer = CoordinateIndexer(selection, self.shape, self._chunk_grid) out_array = sync( - self._read_selection(indexer=indexer, out=out, fields=fields, prototype=prototype) + self.async_array._get_selection( + indexer=indexer, out=out, fields=fields, prototype=prototype + ) ) if hasattr(out_array, "shape"): @@ -3928,7 +4022,7 @@ def set_coordinate_selection( f"elements with an array of {value.shape[0]} elements." ) - sync(self._write_selection(indexer, value, fields=fields, prototype=prototype)) + sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) def get_block_selection( self, @@ -4029,7 +4123,9 @@ def get_block_selection( prototype = default_buffer_prototype() indexer = BlockIndexer(selection, self.shape, self._chunk_grid) return sync( - self._read_selection(indexer=indexer, out=out, fields=fields, prototype=prototype) + self.async_array._get_selection( + indexer=indexer, out=out, fields=fields, prototype=prototype + ) ) def set_block_selection( @@ -4126,7 +4222,7 @@ def set_block_selection( if prototype is None: prototype = default_buffer_prototype() indexer = BlockIndexer(selection, self.shape, self._chunk_grid) - sync(self._write_selection(indexer, value, fields=fields, prototype=prototype)) + sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) @property def vindex(self) -> VIndex: @@ -4190,11 +4286,7 @@ def resize(self, new_shape: ShapeLike) -> None: #>(50, 50) ``` """ - io = self._arrayio() - if io is None: - sync(self.async_array.resize(new_shape)) - else: - self._adopt(sync(io.resize(new_shape))) + sync(self.async_array.resize(new_shape)) def append(self, data: npt.ArrayLike, axis: int = 0) -> tuple[int, ...]: """Append `data` to `axis`. @@ -4230,18 +4322,7 @@ def append(self, data: npt.ArrayLike, axis: int = 0) -> tuple[int, ...]: >>> z.shape (20000, 2000) """ - io = self._arrayio() - if io is None: - return sync(self.async_array.append(data, axis=axis)) - data, new_shape, selection = _appended(io.metadata.shape, data, axis) - resized = sync(io.resize(new_shape)) - # Adopted before the data is written, as a resize through `AsyncArray` is. - self._adopt(resized) - indexer = BasicIndexer( - selection, shape=resized.metadata.shape, chunk_grid=resized.chunk_grid - ) - sync(_write_storing_repair(resized, indexer, data, prototype=default_buffer_prototype())) - return new_shape + return sync(self.async_array.append(data, axis=axis)) def update_attributes(self, new_attributes: dict[str, JSON]) -> Self: """ @@ -4268,12 +4349,8 @@ def update_attributes(self, new_attributes: dict[str, JSON]) -> Self: - The updated attributes will be merged with existing attributes, and any conflicts will be overwritten by the new values. """ - io = self._arrayio() - if io is None: - new_array = sync(self.async_array.update_attributes(new_attributes)) - return type(self)(new_array) - sync(io.update_attributes(new_attributes)) - return type(self)(self.async_array) + new_array = sync(self.async_array.update_attributes(new_attributes)) + return type(self)(new_array) def __repr__(self) -> str: return f"" @@ -6184,7 +6261,7 @@ async def _resize( If True (default), chunks that fall outside the new shape will be deleted. If False, the data in those chunks will be preserved. """ - resized = await _ArrayIO.of(array).resize(new_shape, delete_outside_chunks) + resized = await AsyncArrayIO._of(array).resize(new_shape, delete_outside_chunks) # Update metadata and chunk_grid (in place) object.__setattr__(array, "metadata", resized.metadata) diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 545da85183..877484d4c7 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -1,80 +1,120 @@ -"""`Array` reads and writes through the private `_ArrayIO` routines.""" +"""`AsyncArrayIO` reads and writes an array, and `ArrayIO` runs it synchronously.""" from __future__ import annotations -from typing import Any +import asyncio +import json +import threading +from typing import TYPE_CHECKING, Any, Literal import numpy as np import pytest import zarr -from zarr.core.array import Array, AsyncArray, _ArrayIO +from zarr.core.array import ArrayIO, AsyncArray, AsyncArrayIO, SyncContext +from zarr.core.sync import sync +from zarr.errors import ZarrUserWarning from zarr.storage import MemoryStore - -class _CountingAsyncArray(AsyncArray[Any]): - """An `AsyncArray` subclass that counts the reads and writes it is asked for.""" - - async def _get_selection(self, *args: Any, **kwargs: Any) -> Any: - vars(self).setdefault("_reads", []).append(1) - return await super()._get_selection(*args, **kwargs) - - async def _set_selection(self, *args: Any, **kwargs: Any) -> None: - vars(self).setdefault("_writes", []).append(1) - await super()._set_selection(*args, **kwargs) - - -def _operate(array: Array[Any]) -> None: - array[:] = np.arange(4) - array.oindex[np.array([0, 1])] = [7, 8] - array.resize((6,)) - array.append(np.array([4, 5])) - array.attrs["a"] = 1 - _ = array[:], array.oindex[np.array([0])], array.vindex[np.array([1])], array.blocks[0] - - -@pytest.mark.parametrize("subclass", [False, True]) -def test_array_reads_and_writes_through_array_io(subclass: bool) -> None: - """An `Array` over an `AsyncArray` reads and writes through `_ArrayIO`; over a - subclass of `AsyncArray`, through the subclass, so its overrides are called. Both - give the same array, and every holder of the wrapped `AsyncArray` sees its resizes.""" - created = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") - wrapped = created.async_array - if subclass: - wrapped = _CountingAsyncArray(wrapped.metadata, wrapped.store_path, wrapped.config) - array = Array(wrapped) - other = Array(wrapped) - assert (array._arrayio() is None) is subclass - - _operate(array) - - np.testing.assert_array_equal(array[:], [7, 8, 2, 3, 0, 0, 4, 5]) - assert other.shape == wrapped.shape == (8,) - assert dict(other.attrs) == {"a": 1} - counted = (len(vars(wrapped).get("_reads", [])), len(vars(wrapped).get("_writes", []))) - assert (counted != (0, 0)) is subclass - - -def test_a_resize_through_the_wrapped_async_array_shows_through_the_array() -> None: - array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") - zarr.core.sync.sync(array.async_array.resize((6,))) - array[4:] = [1, 2] - np.testing.assert_array_equal(array[:], [0, 0, 0, 0, 1, 2]) - - -def test_array_io_resize_returns_a_new_value() -> None: - """`_ArrayIO.resize` stores the resized metadata and returns the resized array; the - value it was called on, and the `AsyncArray` it was built from, are unchanged.""" - array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") - io = _ArrayIO.of(array.async_array) - - resized = zarr.core.sync.sync(io.resize((6,))) - - assert (io.metadata.shape, resized.metadata.shape, array.shape) == ((4,), (6,), (4,)) - assert zarr.open_array(array.store_path.store).shape == (6,) - - -def test_array_io_resize_rejects_another_number_of_dimensions() -> None: +if TYPE_CHECKING: + from collections.abc import Iterator + from pathlib import Path + + +@pytest.fixture +def own_loop() -> Iterator[asyncio.AbstractEventLoop]: + """An event loop of the test's own, running on a thread of its own.""" + loop = asyncio.new_event_loop() + thread = threading.Thread(target=loop.run_forever, daemon=True) + thread.start() + yield loop + loop.call_soon_threadsafe(loop.stop) + thread.join() + loop.close() + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("from_async", [False, True]) +def test_array_io_reads_writes_and_resizes( + zarr_format: Literal[2, 3], from_async: bool, own_loop: asyncio.AbstractEventLoop +) -> None: + """`ArrayIO` reads and writes an array through the event loop its context returns. + `resize` and `update_attributes` store the metadata and return the array as it then + is, leaving the value they were called on, and the array it was made from, as they + were.""" + array = zarr.create_array( + MemoryStore(), shape=(4,), chunks=(2,), dtype="int64", zarr_format=zarr_format + ) + loops: list[asyncio.AbstractEventLoop] = [] + + def loop() -> asyncio.AbstractEventLoop: + loops.append(own_loop) + return own_loop + + source: AsyncArray[Any] | zarr.Array[Any] = array.async_array if from_async else array + io = ArrayIO.from_array(source, context=SyncContext(loop=loop)) + + io.setitem(slice(None), np.arange(4)) + resized = io.resize((6,)) + resized.setitem(slice(4, 6), [7, 8]) + updated = resized.update_attributes({"a": 1}) + + np.testing.assert_array_equal(updated.getitem(slice(None)), [0, 1, 2, 3, 7, 8]) + assert (io.shape, resized.shape, array.shape) == ((4,), (6,), (4,)) + reopened = zarr.open_array(array.store_path.store) + assert (reopened.shape, dict(reopened.attrs)) == ((6,), {"a": 1}) + assert loops + assert set(loops) == {own_loop} + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_async_array_io_stores_a_repair_then_writes( + tmp_path: Path, zarr_format: Literal[2, 3] +) -> None: + """An array read from a stored document whose repair moves chunks writes chunks once + `store_repair` has stored the repair.""" + path = tmp_path / "legacy.zarr" + _legacy_array(path, zarr_format) + with pytest.warns(ZarrUserWarning, match="is read as"): + io = AsyncArrayIO.from_array(zarr.open_array(path, mode="r+")) + + sync(io.store_repair()) + sync(io.setitem(slice(None), [1, 2, 3])) + + np.testing.assert_array_equal(zarr.open_array(path)[:], [1, 2, 3]) + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_async_array_io_refuses_chunk_writes_before_a_repair( + tmp_path: Path, zarr_format: Literal[2, 3] +) -> None: + """Writing chunks under metadata read from a document whose repair moves chunks + raises, writing nothing, until the repair is stored.""" + path = tmp_path / "legacy.zarr" + _legacy_array(path, zarr_format) + with pytest.warns(ZarrUserWarning, match="is read as"): + io = AsyncArrayIO.from_array(zarr.open_array(path, mode="r+")) + before = {p: p.read_bytes() for p in path.rglob("*") if p.is_file()} + + with pytest.raises(ValueError, match=r"call `store_repair\(\)` before writing chunks"): + sync(io.setitem(slice(None), [1, 2, 3])) + + assert {p: p.read_bytes() for p in path.rglob("*") if p.is_file()} == before + + +def test_async_array_io_resize_rejects_another_number_of_dimensions() -> None: array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") with pytest.raises(ValueError, match="same number of dimensions"): - zarr.core.sync.sync(_ArrayIO.of(array.async_array).resize((4, 4))) + sync(AsyncArrayIO.from_array(array).resize((4, 4))) + + +def _legacy_array(path: Path, zarr_format: Literal[2, 3]) -> None: + """Store an array of shape (3,) whose stored chunk shape is `[0]`.""" + zarr.create_array(store=path, shape=(3,), chunks=(3,), dtype="int16", zarr_format=zarr_format) + document_path = path / (".zarray" if zarr_format == 2 else "zarr.json") + document = json.loads(document_path.read_text()) + if zarr_format == 2: + document["chunks"] = [0] + else: + document["chunk_grid"]["configuration"]["chunk_shape"] = [0] + document_path.write_text(json.dumps(document)) From a60dd4eebeea9ca4cc38cf1f5667f55c714ebdc4 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 16:21:26 +0100 Subject: [PATCH 04/31] fix(array): keep AsyncArray's repair hooks in charge of its writes AsyncArray again records a stored repair and a resize through its own _stored_document_replaced, and writes through an AsyncArrayIO method that does not check the repair a second time, so a subclass overriding _store_repaired_document decides as it did before. AsyncArrayIO and ArrayIO are unhashable on purpose, and SyncContext documents that its loop must be running. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 32 ++++++++++++++++++++++++++++++-- tests/test_array_io.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index e6b5f0d88c..8add044291 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -1638,7 +1638,11 @@ async def _store_repaired_document(self) -> None: attribute update) is replaced by the repair of the document read before it, as with any two metadata writes that race. """ + if self.metadata._stored_document is None: + return await AsyncArrayIO._of(self).store_repair() + # Through the method, as always, so a subclass that overrides it sees the repair. + self._stored_document_replaced() async def _set_selection( self, @@ -1652,7 +1656,9 @@ async def _set_selection( # Chunks are about to be stored under the repaired metadata, so store it # first: every reader of the store then agrees with them. await self._store_repaired_document() - return await AsyncArrayIO._of(self).set_selection( + # `_store_repaired_document` is this array's repair policy, which a subclass may + # override, so the write is not checked against the repair a second time. + return await AsyncArrayIO._of(self)._write_selection( indexer, value, prototype=prototype, fields=fields ) @@ -1950,6 +1956,9 @@ class AsyncArrayIO: codec_pipeline: CodecPipeline chunk_grid: ChunkGrid + # Not hashable, as `AsyncArray` is not: a store location is not. + __hash__ = None # type: ignore[assignment] + @classmethod def from_array(cls, array: AsyncArray[Any] | Array[Any]) -> AsyncArrayIO: """The array `array` reads and writes, as it is now.""" @@ -2029,6 +2038,18 @@ async def set_selection( "repair that moves chunks; call `store_repair()` before writing chunks. " "Nothing was written." ) + await self._write_selection(indexer, value, prototype=prototype, fields=fields) + + async def _write_selection( + self, + indexer: Indexer, + value: npt.ArrayLike, + *, + prototype: BufferPrototype, + fields: Fields | None = None, + ) -> None: + """`set_selection` without its check against a repair that has not been stored, + for a caller that applies its own repair policy first (`AsyncArray`).""" await _set_selection( self.store_path, self.metadata, @@ -2139,7 +2160,9 @@ class SyncContext: loop: Callable[[], AbstractEventLoop] = _get_loop """Returns the event loop to run each coroutine on, from a thread other than the - loop's own. The default is zarr's own loop, on its IO thread.""" + loop's own. The loop must be running on another thread, or about to be: a call + waits for its coroutine to finish, so a loop that nothing runs blocks it forever. + The default is zarr's own loop, on its IO thread.""" @dataclass(frozen=True, slots=True) @@ -2154,6 +2177,9 @@ class ArrayIO: async_io: AsyncArrayIO context: SyncContext = field(default_factory=SyncContext) + # Not hashable, as `AsyncArrayIO` is not. + __hash__ = None # type: ignore[assignment] + @classmethod def from_array( cls, array: AsyncArray[Any] | Array[Any], *, context: SyncContext | None = None @@ -6262,6 +6288,8 @@ async def _resize( If False, the data in those chunks will be preserved. """ resized = await AsyncArrayIO._of(array).resize(new_shape, delete_outside_chunks) + # Through the method, as always, so a subclass that overrides it sees the resize. + array._stored_document_replaced() # Update metadata and chunk_grid (in place) object.__setattr__(array, "metadata", resized.metadata) diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 877484d4c7..7f8755fc17 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -102,6 +102,37 @@ def test_async_array_io_refuses_chunk_writes_before_a_repair( assert {p: p.read_bytes() for p in path.rglob("*") if p.is_file()} == before +class _HookedAsyncArray(AsyncArray[Any]): + """An `AsyncArray` subclass that records its repair hooks and stores no repair.""" + + async def _store_repaired_document(self) -> None: + vars(self).setdefault("_calls", []).append("repair") + + def _stored_document_replaced(self) -> None: + vars(self).setdefault("_calls", []).append("replaced") + super()._stored_document_replaced() + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_async_array_goes_through_its_repair_hooks( + tmp_path: Path, zarr_format: Literal[2, 3] +) -> None: + """`AsyncArray` stores the repair and records it through its own methods, so a + subclass that overrides them decides: one that stores no repair writes its chunks, + and its resize goes through `_stored_document_replaced`.""" + path = tmp_path / "legacy.zarr" + _legacy_array(path, zarr_format) + with pytest.warns(ZarrUserWarning, match="is read as"): + opened = zarr.open_array(path, mode="r+").async_array + hooked = _HookedAsyncArray(opened.metadata, opened.store_path, opened.config) + + zarr.Array(hooked)[:] = [1, 2, 3] + zarr.Array(hooked).resize((4,)) + + assert vars(hooked)["_calls"] == ["repair", "replaced"] + assert hooked.shape == (4,) + + def test_async_array_io_resize_rejects_another_number_of_dimensions() -> None: array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") with pytest.raises(ValueError, match="same number of dimensions"): From 86305a1d4c2904b79bd2ebf7773c764725068fd7 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 16:26:04 +0100 Subject: [PATCH 05/31] refactor(array): run ArrayIO's coroutines through a runner in its context SyncContext.run is a Runner, a callable that runs a coroutine to completion and returns its result. The default is zarr.core.sync.sync, which runs it on zarr's own loop; asyncio.Runner().run runs it on the calling thread. A runner replaces the loop callable, whose contract could not be checked (a loop that nothing runs blocks forever). Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 24 +++++++++++------- tests/test_array_io.py | 55 +++++++++++++++++++++++------------------- 2 files changed, 45 insertions(+), 34 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 8add044291..4a92f06bdb 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -13,6 +13,7 @@ TYPE_CHECKING, Any, Literal, + Protocol, TypedDict, cast, overload, @@ -142,7 +143,7 @@ create_chunk_grid_metadata, parse_node_type_array, ) -from zarr.core.sync import _get_loop, sync +from zarr.core.sync import sync from zarr.errors import ( ArrayNotFoundError, ChunkNotFoundError, @@ -161,8 +162,7 @@ from zarr.storage._utils import _relativize_path if TYPE_CHECKING: - from asyncio import AbstractEventLoop - from collections.abc import Callable, Coroutine, Iterator + from collections.abc import Coroutine, Iterator from typing import Self import numpy.typing as npt @@ -2154,15 +2154,21 @@ async def update_attributes(self, new_attributes: dict[str, JSON]) -> AsyncArray return self +class Runner(Protocol): + """Runs a coroutine to completion and returns its result, as `asyncio.run` does.""" + + def __call__[T](self, coroutine: Coroutine[Any, Any, T], /) -> T: ... + + @dataclass(frozen=True, slots=True, kw_only=True) class SyncContext: """How a synchronous API runs the coroutines it is built on.""" - loop: Callable[[], AbstractEventLoop] = _get_loop - """Returns the event loop to run each coroutine on, from a thread other than the - loop's own. The loop must be running on another thread, or about to be: a call - waits for its coroutine to finish, so a loop that nothing runs blocks it forever. - The default is zarr's own loop, on its IO thread.""" + run: Runner = sync + """Runs each coroutine to completion and returns its result, or raises its + exception, in the thread that called the synchronous API. The default, + `zarr.core.sync.sync`, runs it on zarr's own event loop, on zarr's IO thread; + `asyncio.Runner().run` runs it on the calling thread instead.""" @dataclass(frozen=True, slots=True) @@ -2188,7 +2194,7 @@ def from_array( return cls(AsyncArrayIO.from_array(array), SyncContext() if context is None else context) def _run[T](self, coroutine: Coroutine[Any, Any, T]) -> T: - return sync(coroutine, loop=self.context.loop()) + return self.context.run(coroutine) @property def metadata(self) -> ArrayMetadata: diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 7f8755fc17..7c27aca308 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -4,7 +4,6 @@ import asyncio import json -import threading from typing import TYPE_CHECKING, Any, Literal import numpy as np @@ -17,42 +16,49 @@ from zarr.storage import MemoryStore if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Coroutine, Iterator from pathlib import Path +class _CountingRunner: + """A runner that counts the coroutines it runs, through `runner`, or zarr's + `sync` by default.""" + + def __init__(self, runner: asyncio.Runner | None = None) -> None: + self.runner = runner + self.runs = 0 + + def __call__[T](self, coroutine: Coroutine[Any, Any, T], /) -> T: + self.runs += 1 + return sync(coroutine) if self.runner is None else self.runner.run(coroutine) + + @pytest.fixture -def own_loop() -> Iterator[asyncio.AbstractEventLoop]: - """An event loop of the test's own, running on a thread of its own.""" - loop = asyncio.new_event_loop() - thread = threading.Thread(target=loop.run_forever, daemon=True) - thread.start() - yield loop - loop.call_soon_threadsafe(loop.stop) - thread.join() - loop.close() +def calling_thread_runner() -> Iterator[asyncio.Runner]: + """An `asyncio.Runner`, which runs coroutines on the calling thread.""" + with asyncio.Runner() as runner: + yield runner @pytest.mark.parametrize("zarr_format", [2, 3]) @pytest.mark.parametrize("from_async", [False, True]) +@pytest.mark.parametrize("on_calling_thread", [False, True]) def test_array_io_reads_writes_and_resizes( - zarr_format: Literal[2, 3], from_async: bool, own_loop: asyncio.AbstractEventLoop + zarr_format: Literal[2, 3], + from_async: bool, + on_calling_thread: bool, + calling_thread_runner: asyncio.Runner, ) -> None: - """`ArrayIO` reads and writes an array through the event loop its context returns. - `resize` and `update_attributes` store the metadata and return the array as it then - is, leaving the value they were called on, and the array it was made from, as they - were.""" + """`ArrayIO` reads and writes an array through the runner its context holds, on + zarr's loop or on the calling thread. `resize` and `update_attributes` store the + metadata and return the array as it then is, leaving the value they were called on, + and the array it was made from, as they were.""" array = zarr.create_array( MemoryStore(), shape=(4,), chunks=(2,), dtype="int64", zarr_format=zarr_format ) - loops: list[asyncio.AbstractEventLoop] = [] - - def loop() -> asyncio.AbstractEventLoop: - loops.append(own_loop) - return own_loop - + runner = _CountingRunner(calling_thread_runner if on_calling_thread else None) source: AsyncArray[Any] | zarr.Array[Any] = array.async_array if from_async else array - io = ArrayIO.from_array(source, context=SyncContext(loop=loop)) + io = ArrayIO.from_array(source, context=SyncContext(run=runner)) io.setitem(slice(None), np.arange(4)) resized = io.resize((6,)) @@ -63,8 +69,7 @@ def loop() -> asyncio.AbstractEventLoop: assert (io.shape, resized.shape, array.shape) == ((4,), (6,), (4,)) reopened = zarr.open_array(array.store_path.store) assert (reopened.shape, dict(reopened.attrs)) == ((6,), {"a": 1}) - assert loops - assert set(loops) == {own_loop} + assert runner.runs == 5 @pytest.mark.parametrize("zarr_format", [2, 3]) From ab1148e34691d027cc4e037b7f411298b6a7f229 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 16:34:55 +0100 Subject: [PATCH 06/31] fix(array): let AsyncArray's hook clear the repair mark AsyncArrayIO.store_repair and resize each compose a private storing step with clearing the mark. AsyncArray runs the storing step and clears the mark through its own _stored_document_replaced, so a subclass that overrides the hook decides whether the mark is cleared, as on main. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 31 +++++++++++++++++++++++-------- tests/test_array_io.py | 27 +++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 4a92f06bdb..6eebae0e73 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -1640,8 +1640,9 @@ async def _store_repaired_document(self) -> None: """ if self.metadata._stored_document is None: return - await AsyncArrayIO._of(self).store_repair() - # Through the method, as always, so a subclass that overrides it sees the repair. + await AsyncArrayIO._of(self)._store_repair_document() + # The mark is cleared through the method, as always, so a subclass that + # overrides it decides. self._stored_document_replaced() async def _set_selection( @@ -2083,6 +2084,12 @@ async def store_repair(self) -> None: """ if self.metadata._stored_document is None: return + await self._store_repair_document() + _stored_document_replaced(self.metadata) + + async def _store_repair_document(self) -> None: + """`store_repair`'s reading and storing, leaving the metadata's mark to its + caller: `AsyncArray` clears it through its own `_stored_document_replaced`.""" zarr_format = self.metadata.zarr_format documents = await read_documents(self.store_path, ARRAY_DOCUMENTS[zarr_format]) try: @@ -2097,7 +2104,6 @@ async def store_repair(self) -> None: ) if current._stored_document is not None: await upsert_metadata(self.store_path, current, documents) - _stored_document_replaced(self.metadata) async def resize( self, new_shape: ShapeLike, delete_outside_chunks: bool = True @@ -2107,6 +2113,13 @@ async def resize( The new metadata is encoded before any chunk is deleted: metadata that cannot be stored then fails with the store untouched.""" + resized = await self._resized(new_shape, delete_outside_chunks) + _stored_document_replaced(self.metadata) + return resized + + async def _resized(self, new_shape: ShapeLike, delete_outside_chunks: bool) -> AsyncArrayIO: + """`resize`'s storing, leaving the metadata's mark to its caller: `AsyncArray` + clears it through its own `_stored_document_replaced`.""" new_shape = parse_shapelike(new_shape) if len(new_shape) != len(self.metadata.shape): raise ValueError( @@ -2140,7 +2153,6 @@ async def resize( ) await store_documents(self.store_path, documents) - _stored_document_replaced(self.metadata) return replace(self, metadata=new_metadata, chunk_grid=new_chunk_grid) async def update_attributes(self, new_attributes: dict[str, JSON]) -> AsyncArrayIO: @@ -2168,13 +2180,15 @@ class SyncContext: """Runs each coroutine to completion and returns its result, or raises its exception, in the thread that called the synchronous API. The default, `zarr.core.sync.sync`, runs it on zarr's own event loop, on zarr's IO thread; - `asyncio.Runner().run` runs it on the calling thread instead.""" + `asyncio.Runner().run` runs it on the calling thread instead. A store whose async + clients belong to one event loop (as fsspec's async filesystems do) needs every + operation on it run on that loop.""" @dataclass(frozen=True, slots=True) class ArrayIO: """Reads and writes an array synchronously: each operation runs the matching - `AsyncArrayIO` operation on the event loop its context returns. + `AsyncArrayIO` operation with the runner its context holds. A value, as `AsyncArrayIO` is: `resize` and `update_attributes` return the array as it then is. @@ -6293,8 +6307,9 @@ async def _resize( If True (default), chunks that fall outside the new shape will be deleted. If False, the data in those chunks will be preserved. """ - resized = await AsyncArrayIO._of(array).resize(new_shape, delete_outside_chunks) - # Through the method, as always, so a subclass that overrides it sees the resize. + resized = await AsyncArrayIO._of(array)._resized(new_shape, delete_outside_chunks) + # The mark is cleared through the method, as always, so a subclass that overrides + # it decides. array._stored_document_replaced() # Update metadata and chunk_grid (in place) diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 7c27aca308..81f2d759cd 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -138,6 +138,33 @@ def test_async_array_goes_through_its_repair_hooks( assert hooked.shape == (4,) +class _KeepsMarkAsyncArray(AsyncArray[Any]): + """An `AsyncArray` subclass whose `_stored_document_replaced` keeps the mark.""" + + def _stored_document_replaced(self) -> None: + vars(self).setdefault("_calls", []).append("replaced") + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_async_array_clears_the_repair_mark_through_its_hook( + tmp_path: Path, zarr_format: Literal[2, 3] +) -> None: + """`AsyncArray` clears the mark of a stored repair only through its own + `_stored_document_replaced`: a subclass that keeps it stores the repair again + before its next chunk write.""" + path = tmp_path / "legacy.zarr" + _legacy_array(path, zarr_format) + with pytest.warns(ZarrUserWarning, match="is read as"): + opened = zarr.open_array(path, mode="r+").async_array + keeps = _KeepsMarkAsyncArray(opened.metadata, opened.store_path, opened.config) + + zarr.Array(keeps)[:] = [1, 2, 3] + zarr.Array(keeps)[:] = [4, 5, 6] + + assert vars(keeps)["_calls"] == ["replaced", "replaced"] + assert keeps.metadata._stored_document is not None + + def test_async_array_io_resize_rejects_another_number_of_dimensions() -> None: array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") with pytest.raises(ValueError, match="same number of dimensions"): From e901d025af69160731d34b617a0a19a235c1f13b Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 17:44:33 +0100 Subject: [PATCH 07/31] docs: add the changelog fragment for #470 Assisted-by: ClaudeCode:claude-opus-5-5 --- changes/470.misc.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changes/470.misc.md diff --git a/changes/470.misc.md b/changes/470.misc.md new file mode 100644 index 0000000000..210df0b3ae --- /dev/null +++ b/changes/470.misc.md @@ -0,0 +1 @@ +Arrays now read and write through `AsyncArrayIO`, which `AsyncArray` builds from its fields for each operation, with a synchronous `ArrayIO` built on it. `Array` and `AsyncArray` behave as before. From 49854fad90468e4bb2b571f7154deca94c3209d8 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 18:11:08 +0100 Subject: [PATCH 08/31] refactor(array): take AsyncArrayIO's parts by keyword and derive the rest AsyncArrayIO's constructor takes metadata, store_path and config by keyword and derives the codec pipeline and chunk grid, which are neither constructor parameters nor compared. Other changes from a design audit: - update_attributes returns a new value instead of changing the attributes of the value (and the array) it was called on; - get_selection and set_selection are private, since an indexer needs the chunk grid to build; getitem and setitem are the public reads and writes; - resize takes delete_outside_chunks by keyword; - ArrayIO takes its context by keyword and gains config and dtype; - both classes have a short repr, as AsyncArray does; - Runner and SyncContext move to zarr.core.sync, beside sync. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 239 +++++++++++++++++++++++++---------------- src/zarr/core/sync.py | 22 +++- tests/test_array_io.py | 31 +++++- 3 files changed, 193 insertions(+), 99 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 6eebae0e73..0b7e5c67d9 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -13,7 +13,6 @@ TYPE_CHECKING, Any, Literal, - Protocol, TypedDict, cast, overload, @@ -143,7 +142,7 @@ create_chunk_grid_metadata, parse_node_type_array, ) -from zarr.core.sync import sync +from zarr.core.sync import SyncContext, sync from zarr.errors import ( ArrayNotFoundError, ChunkNotFoundError, @@ -1475,7 +1474,7 @@ async def _get_selection( out: NDBuffer | None = None, fields: Fields | None = None, ) -> NDArrayLikeOrScalar: - return await AsyncArrayIO._of(self).get_selection( + return await AsyncArrayIO._of(self)._get_selection( indexer, prototype=prototype, out=out, fields=fields ) @@ -1936,52 +1935,121 @@ async def _delete_chunk(key: StorePath) -> None: await key.delete() -@dataclass(frozen=True, slots=True) +@dataclass(frozen=True, slots=True, init=False) class AsyncArrayIO: """Reads and writes an array: its metadata, bound to a location in a store, with its - runtime configuration and the codec pipeline and chunk grid derived from them. + runtime configuration. + + A value. Making one derives the codec pipeline and chunk grid from the metadata. An + operation that stores new metadata (`resize`, `update_attributes`) returns the + array as it then is, leaving this value and the array it was made from as they + were. Chunk reads and writes leave the value as it is. - A value. An operation that changes the stored metadata (`resize`, - `update_attributes`) stores it and returns the array as it then is; chunk reads and - writes leave the value as it is. Nothing is repaired implicitly: if the metadata was - read from a stored document that needs a repair that moves chunks, writing chunks - raises until `store_repair` has stored that repair. + Nothing is repaired implicitly. Metadata read from a stored document that needs a + repair that moves chunks carries a mark that says so; writing chunks raises while + it is set, and `store_repair` stores the repair and clears it. The mark is state of + the store, shared by every holder of that metadata object (an `AsyncArray`, a + consolidated group, another `AsyncArrayIO`), so one repair serves them all. `AsyncArray` reads and writes through one of these, built from its fields for each operation. + + Parameters + ---------- + metadata : ArrayV2Metadata, ArrayV3Metadata, or a metadata document as a dict + The array's metadata. A document is read as opening the array reads it. + store_path : StorePath + Where in a store the array is. + config : ArrayConfigLike, optional + The runtime configuration; defaults from the global configuration. """ metadata: ArrayMetadata store_path: StorePath config: ArrayConfig - codec_pipeline: CodecPipeline - chunk_grid: ChunkGrid + # Derived from the metadata, so neither taken by the constructor nor compared. + codec_pipeline: CodecPipeline = field(init=False, compare=False, repr=False) + chunk_grid: ChunkGrid = field(init=False, compare=False, repr=False) # Not hashable, as `AsyncArray` is not: a store location is not. __hash__ = None # type: ignore[assignment] + def __init__( + self, + *, + metadata: ArrayMetadata | ArrayMetadataDict, + store_path: StorePath, + config: ArrayConfigLike | None = None, + ) -> None: + metadata_parsed = parse_array_metadata(metadata, str(store_path)) + self._assign( + metadata_parsed, + store_path, + parse_array_config(config), + create_codec_pipeline(metadata=metadata_parsed, store=store_path.store), + ChunkGrid.from_metadata(metadata_parsed), + ) + + def _assign( + self, + metadata: ArrayMetadata, + store_path: StorePath, + config: ArrayConfig, + codec_pipeline: CodecPipeline, + chunk_grid: ChunkGrid, + ) -> None: + object.__setattr__(self, "metadata", metadata) + object.__setattr__(self, "store_path", store_path) + object.__setattr__(self, "config", config) + object.__setattr__(self, "codec_pipeline", codec_pipeline) + object.__setattr__(self, "chunk_grid", chunk_grid) + + @classmethod + def _from_parts( + cls, + metadata: ArrayMetadata, + store_path: StorePath, + config: ArrayConfig, + codec_pipeline: CodecPipeline, + chunk_grid: ChunkGrid, + ) -> AsyncArrayIO: + """A value over parts already derived, consistent with each other: an array's + own, or the parts of another value with only the shape changed.""" + io = object.__new__(cls) + io._assign(metadata, store_path, config, codec_pipeline, chunk_grid) + return io + @classmethod def from_array(cls, array: AsyncArray[Any] | Array[Any]) -> AsyncArrayIO: - """The array `array` reads and writes, as it is now.""" + """The array `array` reads and writes, as it is now. The codec pipeline and chunk + grid are the array's own, not derived again.""" return cls._of(array.async_array if isinstance(array, Array) else array) @classmethod def _of(cls, array: AsyncArray[Any]) -> AsyncArrayIO: - return cls( + return cls._from_parts( array.metadata, array.store_path, array.config, array.codec_pipeline, array._chunk_grid ) + def __repr__(self) -> str: + return f"" + @property def shape(self) -> tuple[int, ...]: """The shape of the array.""" return self.metadata.shape + @property + def dtype(self) -> TBaseDType: + """The NumPy data type of the array.""" + return self.metadata.dtype.to_native_dtype() + async def getitem( self, selection: BasicSelection, *, prototype: BufferPrototype | None = None ) -> NDArrayLikeOrScalar: """The values at `selection`, by basic indexing.""" indexer = BasicIndexer(selection, shape=self.metadata.shape, chunk_grid=self.chunk_grid) - return await self.get_selection( + return await self._get_selection( indexer, prototype=default_buffer_prototype() if prototype is None else prototype ) @@ -1992,13 +2060,18 @@ async def setitem( *, prototype: BufferPrototype | None = None, ) -> None: - """Write `value` at `selection`, by basic indexing.""" + """Write `value` at `selection`, by basic indexing. + + Raises `ValueError`, writing nothing, if chunks would be written under metadata + whose stored document needs a repair that moves chunks that has not been stored: + no reader of that document would find them (see `store_repair`). + """ indexer = BasicIndexer(selection, shape=self.metadata.shape, chunk_grid=self.chunk_grid) - await self.set_selection( + await self._set_selection( indexer, value, prototype=default_buffer_prototype() if prototype is None else prototype ) - async def get_selection( + async def _get_selection( self, indexer: Indexer, *, @@ -2006,7 +2079,6 @@ async def get_selection( out: NDBuffer | None = None, fields: Fields | None = None, ) -> NDArrayLikeOrScalar: - """The values `indexer` selects.""" return await _get_selection( self.store_path, self.metadata, @@ -2019,7 +2091,7 @@ async def get_selection( fields=fields, ) - async def set_selection( + async def _set_selection( self, indexer: Indexer, value: npt.ArrayLike, @@ -2027,12 +2099,8 @@ async def set_selection( prototype: BufferPrototype, fields: Fields | None = None, ) -> None: - """Write `value` to what `indexer` selects. - - Raises `ValueError`, writing nothing, if chunks would be written under metadata - read from a stored document whose repair moves chunks and has not been stored: - no reader of that document would find them (see `store_repair`). - """ + """`_write_selection`, refused while the metadata stands for a stored document + whose repair moves chunks and has not been stored (see `setitem`).""" if product(indexer.shape) > 0 and self.metadata._stored_document is not None: raise ValueError( f"Array {str(self.store_path)!r}: the stored metadata document needs a " @@ -2049,8 +2117,8 @@ async def _write_selection( prototype: BufferPrototype, fields: Fields | None = None, ) -> None: - """`set_selection` without its check against a repair that has not been stored, - for a caller that applies its own repair policy first (`AsyncArray`).""" + """Write without the check against a repair that has not been stored, for a + caller that applies its own repair policy first (`AsyncArray`).""" await _set_selection( self.store_path, self.metadata, @@ -2064,17 +2132,16 @@ async def _write_selection( ) async def store_repair(self) -> None: - """Store the repair of the array's current stored document, if it needs one - that moves chunks. + """Store the repair of the array's current stored document, if its metadata was + read from one that needs a repair that moves chunks, and clear the mark that + says so (see the class docstring). - Only for metadata read from a document whose repair moves chunks (see - `zarr.core.metadata.repair`). The document is read again, because the store may - hold a newer one than this metadata. If that one lays out chunks differently - (another writer stored a different chunk size since), chunks written under this - metadata would be found by no reader, so it raises and stores nothing. If it - needs no repair (the array was re-saved since, possibly by another - implementation), it is left as written; if there is none, there is nothing to - repair. + The document is read again, because the store may hold a newer one than this + metadata. If that one lays out chunks differently (another writer stored a + different chunk size since), chunks written under this metadata would be found + by no reader, so it raises, stores nothing and keeps the mark. If it needs no + repair (the array was re-saved since, possibly by another implementation), it is + left as written; if there is none, there is nothing to repair. Storing the same repair twice is harmless, so handles that write chunks concurrently need no coordination. The read and the store are not one atomic @@ -2106,13 +2173,14 @@ async def _store_repair_document(self) -> None: await upsert_metadata(self.store_path, current, documents) async def resize( - self, new_shape: ShapeLike, delete_outside_chunks: bool = True + self, new_shape: ShapeLike, *, delete_outside_chunks: bool = True ) -> AsyncArrayIO: """Store the metadata of the array resized to `new_shape`, deleting the chunks outside it if `delete_outside_chunks`, and return the array as resized. The new metadata is encoded before any chunk is deleted: metadata that cannot be - stored then fails with the store untouched.""" + stored then fails with the store untouched. The store then holds valid metadata, + so the repair mark of this value's metadata is cleared.""" resized = await self._resized(new_shape, delete_outside_chunks) _stored_document_replaced(self.metadata) return resized @@ -2153,36 +2221,24 @@ async def _resized(self, new_shape: ShapeLike, delete_outside_chunks: bool) -> A ) await store_documents(self.store_path, documents) - return replace(self, metadata=new_metadata, chunk_grid=new_chunk_grid) + # A resize leaves the chunk encoding as it was, so the pipeline is kept. + return AsyncArrayIO._from_parts( + new_metadata, self.store_path, self.config, self.codec_pipeline, new_chunk_grid + ) async def update_attributes(self, new_attributes: dict[str, JSON]) -> AsyncArrayIO: - """Merge `new_attributes` into the array's attributes and store its metadata. - - The attributes change in place, as they always have through an array: every - holder of this metadata sees them.""" - self.metadata.attributes.update(new_attributes) - await save_metadata(self.store_path, self.metadata) + """Store the array's metadata with `new_attributes` merged into its attributes, + and return the array as it then is. This value's attributes are left as they + were. The store then holds valid metadata, so the repair mark of this value's + metadata is cleared.""" + new_metadata = self.metadata.update_attributes( + {**self.metadata.attributes, **new_attributes} + ) + await save_metadata(self.store_path, new_metadata) _stored_document_replaced(self.metadata) - return self - - -class Runner(Protocol): - """Runs a coroutine to completion and returns its result, as `asyncio.run` does.""" - - def __call__[T](self, coroutine: Coroutine[Any, Any, T], /) -> T: ... - - -@dataclass(frozen=True, slots=True, kw_only=True) -class SyncContext: - """How a synchronous API runs the coroutines it is built on.""" - - run: Runner = sync - """Runs each coroutine to completion and returns its result, or raises its - exception, in the thread that called the synchronous API. The default, - `zarr.core.sync.sync`, runs it on zarr's own event loop, on zarr's IO thread; - `asyncio.Runner().run` runs it on the calling thread instead. A store whose async - clients belong to one event loop (as fsspec's async filesystems do) needs every - operation on it run on that loop.""" + return AsyncArrayIO._from_parts( + new_metadata, self.store_path, self.config, self.codec_pipeline, self.chunk_grid + ) @dataclass(frozen=True, slots=True) @@ -2195,7 +2251,7 @@ class ArrayIO: """ async_io: AsyncArrayIO - context: SyncContext = field(default_factory=SyncContext) + context: SyncContext = field(default_factory=SyncContext, kw_only=True) # Not hashable, as `AsyncArrayIO` is not. __hash__ = None # type: ignore[assignment] @@ -2205,7 +2261,12 @@ def from_array( cls, array: AsyncArray[Any] | Array[Any], *, context: SyncContext | None = None ) -> ArrayIO: """The array `array` reads and writes, as it is now.""" - return cls(AsyncArrayIO.from_array(array), SyncContext() if context is None else context) + return cls( + AsyncArrayIO.from_array(array), context=SyncContext() if context is None else context + ) + + def __repr__(self) -> str: + return f"" def _run[T](self, coroutine: Coroutine[Any, Any, T]) -> T: return self.context.run(coroutine) @@ -2220,11 +2281,21 @@ def store_path(self) -> StorePath: """Where in a store the array is.""" return self.async_io.store_path + @property + def config(self) -> ArrayConfig: + """The runtime configuration.""" + return self.async_io.config + @property def shape(self) -> tuple[int, ...]: """The shape of the array.""" return self.async_io.shape + @property + def dtype(self) -> TBaseDType: + """The NumPy data type of the array.""" + return self.async_io.dtype + def getitem( self, selection: BasicSelection, *, prototype: BufferPrototype | None = None ) -> NDArrayLikeOrScalar: @@ -2241,37 +2312,15 @@ def setitem( """See `AsyncArrayIO.setitem`.""" self._run(self.async_io.setitem(selection, value, prototype=prototype)) - def get_selection( - self, - indexer: Indexer, - *, - prototype: BufferPrototype, - out: NDBuffer | None = None, - fields: Fields | None = None, - ) -> NDArrayLikeOrScalar: - """See `AsyncArrayIO.get_selection`.""" - return self._run( - self.async_io.get_selection(indexer, prototype=prototype, out=out, fields=fields) - ) - - def set_selection( - self, - indexer: Indexer, - value: npt.ArrayLike, - *, - prototype: BufferPrototype, - fields: Fields | None = None, - ) -> None: - """See `AsyncArrayIO.set_selection`.""" - self._run(self.async_io.set_selection(indexer, value, prototype=prototype, fields=fields)) - def store_repair(self) -> None: """See `AsyncArrayIO.store_repair`.""" self._run(self.async_io.store_repair()) - def resize(self, new_shape: ShapeLike, delete_outside_chunks: bool = True) -> ArrayIO: + def resize(self, new_shape: ShapeLike, *, delete_outside_chunks: bool = True) -> ArrayIO: """See `AsyncArrayIO.resize`.""" - resized = self._run(self.async_io.resize(new_shape, delete_outside_chunks)) + resized = self._run( + self.async_io.resize(new_shape, delete_outside_chunks=delete_outside_chunks) + ) return replace(self, async_io=resized) def update_attributes(self, new_attributes: dict[str, JSON]) -> ArrayIO: diff --git a/src/zarr/core/sync.py b/src/zarr/core/sync.py index 16b1c577ff..5db789c16d 100644 --- a/src/zarr/core/sync.py +++ b/src/zarr/core/sync.py @@ -6,13 +6,13 @@ import os import threading from concurrent.futures import ThreadPoolExecutor, wait -from typing import TYPE_CHECKING +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Protocol from zarr.core.config import config if TYPE_CHECKING: from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine - from typing import Any logger = logging.getLogger(__name__) @@ -222,3 +222,21 @@ async def _with_semaphore[T]( return await func() async with semaphore: return await func() + + +class Runner(Protocol): + """Runs a coroutine to completion and returns its result, as `asyncio.run` does.""" + + def __call__[T](self, coroutine: Coroutine[Any, Any, T], /) -> T: ... + + +@dataclass(frozen=True, slots=True, kw_only=True) +class SyncContext: + """How a synchronous API runs the coroutines it is built on.""" + + run: Runner = sync + """Runs each coroutine to completion and returns its result, or raises its + exception, in the thread that called the synchronous API. The default, `sync`, runs + it on zarr's own event loop, on zarr's IO thread; `asyncio.Runner().run` runs it on + the calling thread instead. A store whose async clients belong to one event loop (as + fsspec's async filesystems do) needs every operation on it run on that loop.""" diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 81f2d759cd..af09ed9eac 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -3,15 +3,17 @@ from __future__ import annotations import asyncio +import dataclasses import json +import pickle from typing import TYPE_CHECKING, Any, Literal import numpy as np import pytest import zarr -from zarr.core.array import ArrayIO, AsyncArray, AsyncArrayIO, SyncContext -from zarr.core.sync import sync +from zarr.core.array import ArrayIO, AsyncArray, AsyncArrayIO +from zarr.core.sync import SyncContext, sync from zarr.errors import ZarrUserWarning from zarr.storage import MemoryStore @@ -67,11 +69,36 @@ def test_array_io_reads_writes_and_resizes( np.testing.assert_array_equal(updated.getitem(slice(None)), [0, 1, 2, 3, 7, 8]) assert (io.shape, resized.shape, array.shape) == ((4,), (6,), (4,)) + assert (resized.metadata.attributes, dict(array.attrs)) == ({}, {}) reopened = zarr.open_array(array.store_path.store) assert (reopened.shape, dict(reopened.attrs)) == ((6,), {"a": 1}) assert runner.runs == 5 +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_async_array_io_is_a_value_over_its_metadata(zarr_format: Literal[2, 3]) -> None: + """Making an `AsyncArrayIO` from its metadata, location and configuration derives its + codec pipeline and chunk grid. It equals the value read from an array over the same + parts, a changed copy derives them again, and it pickles.""" + array = zarr.create_array( + MemoryStore(), shape=(4,), chunks=(2,), dtype="int64", zarr_format=zarr_format + ) + made = AsyncArrayIO(metadata=array.metadata, store_path=array.store_path, config=array.config) + grown = dataclasses.replace(made, metadata=made.metadata.update_shape((8,))) + + assert made == AsyncArrayIO.from_array(array) + assert made.chunk_grid.grid_shape == array.async_array._chunk_grid.grid_shape + assert grown.chunk_grid.grid_shape == (4,) + assert pickle.loads(pickle.dumps(made)) == made + assert repr(made) == f"" + + +def test_async_array_io_takes_its_parts_by_keyword() -> None: + array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") + with pytest.raises(TypeError): + AsyncArrayIO(array.metadata, array.store_path) # type: ignore[call-arg] + + @pytest.mark.parametrize("zarr_format", [2, 3]) def test_async_array_io_stores_a_repair_then_writes( tmp_path: Path, zarr_format: Literal[2, 3] From aed95d8bab163e1e16253fbe2c303856c38f0ff4 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 19:16:10 +0100 Subject: [PATCH 09/31] refactor(array): reshape AsyncArrayIO and ArrayIO after zarrista An array is a value made with open (reads the metadata), from_metadata (binds metadata, storing and checking nothing) or of (snapshots an Array or AsyncArray). Metadata changes are values: with_shape and with_attrs return a new value and store nothing; store_metadata stores it, erase_metadata, erase_chunk and erase_chunks delete. Reads and writes use zarrs' vocabulary: retrieve_array_subset, store_array_subset, retrieve_chunk and store_chunk, with __getitem__ (and __setitem__ on ArrayIO) as sugar. A value opened from a document whose repair moves chunks needs a repair: storing chunks raises MetadataRepairRequiredError until store_metadata has stored the repaired metadata. Fields are private, equality is identity, and the classes are made only by their constructors. ArrayIO runs coroutines through SyncContext.runner, shaped like asyncio.Runner, and as_sync/as_async move between the two. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 702 +++++++++++++++++++++++++++-------------- src/zarr/core/sync.py | 25 +- src/zarr/errors.py | 9 + tests/test_array_io.py | 148 +++++---- 4 files changed, 570 insertions(+), 314 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 0b7e5c67d9..aa1d88943b 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -146,6 +146,7 @@ from zarr.errors import ( ArrayNotFoundError, ChunkNotFoundError, + MetadataRepairRequiredError, MetadataValidationError, ZarrDeprecationWarning, ZarrUserWarning, @@ -1935,75 +1936,49 @@ async def _delete_chunk(key: StorePath) -> None: await key.delete() -@dataclass(frozen=True, slots=True, init=False) -class AsyncArrayIO: - """Reads and writes an array: its metadata, bound to a location in a store, with its - runtime configuration. - - A value. Making one derives the codec pipeline and chunk grid from the metadata. An - operation that stores new metadata (`resize`, `update_attributes`) returns the - array as it then is, leaving this value and the array it was made from as they - were. Chunk reads and writes leave the value as it is. +def _snapshot(metadata: ArrayMetadata) -> ArrayMetadata: + """A copy of `metadata` with an attributes dict of its own, so a change to the + attributes of the original (which an `AsyncArray` makes in place) never reaches + the copy. The repair mark, an instance attribute, is copied with it.""" + copied = copy.copy(metadata) + object.__setattr__(copied, "attributes", dict(metadata.attributes)) + return copied - Nothing is repaired implicitly. Metadata read from a stored document that needs a - repair that moves chunks carries a mark that says so; writing chunks raises while - it is set, and `store_repair` stores the repair and clears it. The mark is state of - the store, shared by every holder of that metadata object (an `AsyncArray`, a - consolidated group, another `AsyncArrayIO`), so one repair serves them all. - `AsyncArray` reads and writes through one of these, built from its fields for each - operation. - - Parameters - ---------- - metadata : ArrayV2Metadata, ArrayV3Metadata, or a metadata document as a dict - The array's metadata. A document is read as opening the array reads it. - store_path : StorePath - Where in a store the array is. - config : ArrayConfigLike, optional - The runtime configuration; defaults from the global configuration. +@dataclass(frozen=True, slots=True, eq=False, init=False, repr=False) +class AsyncArrayIO: + """An array, as a value: its metadata, bound to a location in a store. + + Make one with `open` (reads the metadata from the store), `from_metadata` (binds + metadata you already have, storing and checking nothing) or `of` (the array an + `Array` or `AsyncArray` reads and writes). + + Metadata changes are values too. `with_shape` and `with_attrs` return a new value + and store nothing; `store_metadata` stores a value's metadata. Every operation acts + on this value's metadata as it is, whatever the store holds now: an older value + still describes the array as it was, and storing its metadata replaces newer + metadata. Chunks are erased only on request (`erase_chunk`, `erase_chunks`). + + Nothing is repaired implicitly. A value whose metadata was read from a document + that needs a repair that moves chunks (such as a stored chunk size of 0) holds the + repaired metadata and `needs_repair` is true; storing chunks raises + `MetadataRepairRequiredError` until `store_metadata` has stored the repaired + metadata. """ - metadata: ArrayMetadata - store_path: StorePath - config: ArrayConfig - # Derived from the metadata, so neither taken by the constructor nor compared. - codec_pipeline: CodecPipeline = field(init=False, compare=False, repr=False) - chunk_grid: ChunkGrid = field(init=False, compare=False, repr=False) - - # Not hashable, as `AsyncArray` is not: a store location is not. - __hash__ = None # type: ignore[assignment] - - def __init__( - self, - *, - metadata: ArrayMetadata | ArrayMetadataDict, - store_path: StorePath, - config: ArrayConfigLike | None = None, - ) -> None: - metadata_parsed = parse_array_metadata(metadata, str(store_path)) - self._assign( - metadata_parsed, - store_path, - parse_array_config(config), - create_codec_pipeline(metadata=metadata_parsed, store=store_path.store), - ChunkGrid.from_metadata(metadata_parsed), + _metadata: ArrayMetadata + _store_path: StorePath + _config: ArrayConfig + _codec_pipeline: CodecPipeline + _chunk_grid: ChunkGrid + _needs_repair: bool + + def __init__(self) -> None: + raise TypeError( + "Make an AsyncArrayIO with AsyncArrayIO.open, AsyncArrayIO.from_metadata or " + "AsyncArrayIO.of." ) - def _assign( - self, - metadata: ArrayMetadata, - store_path: StorePath, - config: ArrayConfig, - codec_pipeline: CodecPipeline, - chunk_grid: ChunkGrid, - ) -> None: - object.__setattr__(self, "metadata", metadata) - object.__setattr__(self, "store_path", store_path) - object.__setattr__(self, "config", config) - object.__setattr__(self, "codec_pipeline", codec_pipeline) - object.__setattr__(self, "chunk_grid", chunk_grid) - @classmethod def _from_parts( cls, @@ -2012,65 +1987,275 @@ def _from_parts( config: ArrayConfig, codec_pipeline: CodecPipeline, chunk_grid: ChunkGrid, + needs_repair: bool, ) -> AsyncArrayIO: - """A value over parts already derived, consistent with each other: an array's - own, or the parts of another value with only the shape changed.""" io = object.__new__(cls) - io._assign(metadata, store_path, config, codec_pipeline, chunk_grid) + object.__setattr__(io, "_metadata", metadata) + object.__setattr__(io, "_store_path", store_path) + object.__setattr__(io, "_config", config) + object.__setattr__(io, "_codec_pipeline", codec_pipeline) + object.__setattr__(io, "_chunk_grid", chunk_grid) + object.__setattr__(io, "_needs_repair", needs_repair) return io @classmethod - def from_array(cls, array: AsyncArray[Any] | Array[Any]) -> AsyncArrayIO: - """The array `array` reads and writes, as it is now. The codec pipeline and chunk - grid are the array's own, not derived again.""" - return cls._of(array.async_array if isinstance(array, Array) else array) + def _bound( + cls, + metadata: ArrayMetadata | ArrayMetadataDict, + store_path: StorePath, + config: ArrayConfigLike | None, + ) -> AsyncArrayIO: + """A value over `metadata`, read as `AsyncArray` reads it, deriving its codec + pipeline and chunk grid.""" + parsed = parse_array_metadata(metadata, str(store_path)) + return cls._from_parts( + parsed, + store_path, + parse_array_config(config), + create_codec_pipeline(metadata=parsed, store=store_path.store), + ChunkGrid.from_metadata(parsed), + parsed._stored_document is not None, + ) + + @classmethod + async def open( + cls, + store: Store, + path: str = "", + *, + zarr_format: ZarrFormat | None = None, + config: ArrayConfigLike | None = None, + ) -> AsyncArrayIO: + """The array whose metadata `store` holds at `path`, of either Zarr format + unless `zarr_format` says which. + + Raises `ArrayNotFoundError` if there is none.""" + store_path = StorePath(store, path) + document = await get_array_metadata(store_path, zarr_format=zarr_format) + return cls._bound(cast("ArrayMetadataDict", document), store_path, config) + + @classmethod + def from_metadata( + cls, + metadata: ArrayMetadata | ArrayMetadataDict, + store: Store, + path: str = "", + *, + config: ArrayConfigLike | None = None, + ) -> AsyncArrayIO: + """An array at `path` in `store` with `metadata`, a metadata object or document. + + Nothing is stored and nothing is checked against the store: call + `store_metadata` to store the metadata, and do so before storing chunks unless + the store already holds it.""" + if not isinstance(metadata, dict): + metadata = _snapshot(metadata) + return cls._bound(metadata, StorePath(store, path), config) + + @classmethod + def of(cls, array: AsyncArray[Any] | Array[Any]) -> AsyncArrayIO: + """The array `array` reads and writes, as it is now. Later changes through + `array` do not reach the value.""" + source = array.async_array if isinstance(array, Array) else array + metadata = _snapshot(source.metadata) + return cls._from_parts( + metadata, + source.store_path, + source.config, + source.codec_pipeline, + source._chunk_grid, + metadata._stored_document is not None, + ) @classmethod def _of(cls, array: AsyncArray[Any]) -> AsyncArrayIO: + """The routines over `array`'s own fields, sharing its metadata, for `AsyncArray` + to read and write through.""" return cls._from_parts( - array.metadata, array.store_path, array.config, array.codec_pipeline, array._chunk_grid + array.metadata, + array.store_path, + array.config, + array.codec_pipeline, + array._chunk_grid, + array.metadata._stored_document is not None, ) + def as_sync(self, *, context: SyncContext | None = None) -> ArrayIO: + """This array, read and written synchronously with the runner `context` holds.""" + return ArrayIO._wrap(self, SyncContext() if context is None else context) + def __repr__(self) -> str: - return f"" + return f"" + + @property + def metadata(self) -> dict[str, JSON]: + """The array's metadata document, as `store_metadata` would store it.""" + return self._metadata.to_dict() + + @property + def attrs(self) -> dict[str, JSON]: + """The array's user attributes.""" + return dict(self._metadata.attributes) @property def shape(self) -> tuple[int, ...]: """The shape of the array.""" - return self.metadata.shape + return self._metadata.shape + + @property + def ndim(self) -> int: + """The number of dimensions.""" + return len(self._metadata.shape) @property def dtype(self) -> TBaseDType: """The NumPy data type of the array.""" - return self.metadata.dtype.to_native_dtype() + return self._metadata.dtype.to_native_dtype() - async def getitem( + @property + def store(self) -> Store: + """The store that holds the array.""" + return self._store_path.store + + @property + def path(self) -> str: + """The array's path in its store.""" + return self._store_path.path + + @property + def read_only(self) -> bool: + """Whether the store refuses writes.""" + return self._store_path.store.read_only + + @property + def needs_repair(self) -> bool: + """Whether this value's metadata was repaired from a stored document in a way + that moves chunks, and has not been stored since: chunks cannot be stored until + `store_metadata` has stored it.""" + return self._needs_repair + + def with_shape(self, shape: ShapeLike) -> AsyncArrayIO: + """This array with `shape`. Nothing is stored and no chunk is erased: growing + reads the new region as the fill value, and chunks outside a smaller shape stay + in the store until erased (`erase_chunks`).""" + new_shape = parse_shapelike(shape) + if len(new_shape) != len(self._metadata.shape): + raise ValueError( + f"The new shape must have the same number of dimensions as the array. " + f"Got {len(new_shape)} dimension(s), expected {len(self._metadata.shape)}." + ) + new_metadata = self._metadata.update_shape(new_shape) + return AsyncArrayIO._from_parts( + new_metadata, + self._store_path, + self._config, + self._codec_pipeline, + ChunkGrid.from_metadata(new_metadata), + self._needs_repair, + ) + + def with_attrs(self, attrs: Mapping[str, JSON]) -> AsyncArrayIO: + """This array with the user attributes `attrs`, which replace the old ones: + merge them yourself to keep them (`io.with_attrs({**io.attrs, "units": "m"})`). + Nothing is stored.""" + return AsyncArrayIO._from_parts( + self._metadata.update_attributes(dict(attrs)), + self._store_path, + self._config, + self._codec_pipeline, + self._chunk_grid, + self._needs_repair, + ) + + async def store_metadata(self) -> AsyncArrayIO: + """Store this value's metadata at the array's path, replacing whatever metadata + is there, and return the array as stored: if this value needed a repair, the + returned one does not.""" + await save_metadata(self._store_path, self._metadata) + return AsyncArrayIO._from_parts( + self._metadata, + self._store_path, + self._config, + self._codec_pipeline, + self._chunk_grid, + False, + ) + + async def erase_metadata(self) -> None: + """Delete the array's metadata documents from the store; succeeds if there are + none.""" + keys = ARRAY_DOCUMENTS[self._metadata.zarr_format] + await gather(*((self._store_path / key).delete() for key in keys)) + + async def erase_chunk(self, chunk_coords: Sequence[int]) -> None: + """Delete the chunk at `chunk_coords` from the store; it then reads as the fill + value. Succeeds if there is none.""" + await (self._store_path / self._metadata.encode_chunk_key(tuple(chunk_coords))).delete() + + async def erase_chunks(self, chunk_coords: Iterable[Sequence[int]]) -> None: + """Delete the chunks at each of `chunk_coords` from the store.""" + keys = [ + (self._store_path / self._metadata.encode_chunk_key(tuple(coords)),) + for coords in chunk_coords + ] + if keys: + # `None` lifts the I/O concurrency limit, but the worker pool still needs a + # bound; 1000 keeps the pool far smaller than the work. + limit = zarr_config.get("async.concurrency") or 1000 + await concurrent_foreach(iter(keys), _delete_chunk, min(limit, len(keys))) + + async def retrieve_array_subset( self, selection: BasicSelection, *, prototype: BufferPrototype | None = None ) -> NDArrayLikeOrScalar: - """The values at `selection`, by basic indexing.""" - indexer = BasicIndexer(selection, shape=self.metadata.shape, chunk_grid=self.chunk_grid) + """The values at `selection`, by NumPy basic indexing.""" + indexer = BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) return await self._get_selection( indexer, prototype=default_buffer_prototype() if prototype is None else prototype ) - async def setitem( + async def store_array_subset( self, selection: BasicSelection, - value: npt.ArrayLike, + data: npt.ArrayLike, *, prototype: BufferPrototype | None = None, ) -> None: - """Write `value` at `selection`, by basic indexing. + """Write `data` at `selection`, by NumPy basic indexing. - Raises `ValueError`, writing nothing, if chunks would be written under metadata - whose stored document needs a repair that moves chunks that has not been stored: - no reader of that document would find them (see `store_repair`). - """ - indexer = BasicIndexer(selection, shape=self.metadata.shape, chunk_grid=self.chunk_grid) + Raises `MetadataRepairRequiredError`, writing nothing, while `needs_repair` is + true: no reader of the stored document would find the chunks.""" + indexer = BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) + await self._set_selection( + indexer, data, prototype=default_buffer_prototype() if prototype is None else prototype + ) + + async def retrieve_chunk( + self, chunk_coords: Sequence[int], *, prototype: BufferPrototype | None = None + ) -> NDArrayLikeOrScalar: + """The values of the chunk at `chunk_coords`, decoded.""" + indexer = BlockIndexer(tuple(chunk_coords), self._metadata.shape, self._chunk_grid) + return await self._get_selection( + indexer, prototype=default_buffer_prototype() if prototype is None else prototype + ) + + async def store_chunk( + self, + chunk_coords: Sequence[int], + data: npt.ArrayLike, + *, + prototype: BufferPrototype | None = None, + ) -> None: + """Encode `data` as the chunk at `chunk_coords` and write it; raises as + `store_array_subset` does.""" + indexer = BlockIndexer(tuple(chunk_coords), self._metadata.shape, self._chunk_grid) await self._set_selection( - indexer, value, prototype=default_buffer_prototype() if prototype is None else prototype + indexer, data, prototype=default_buffer_prototype() if prototype is None else prototype ) + async def __getitem__(self, selection: BasicSelection) -> NDArrayLikeOrScalar: + """`retrieve_array_subset(selection)`.""" + return await self.retrieve_array_subset(selection) + async def _get_selection( self, indexer: Indexer, @@ -2080,11 +2265,11 @@ async def _get_selection( fields: Fields | None = None, ) -> NDArrayLikeOrScalar: return await _get_selection( - self.store_path, - self.metadata, - self.codec_pipeline, - self.config, - self.chunk_grid, + self._store_path, + self._metadata, + self._codec_pipeline, + self._config, + self._chunk_grid, indexer, prototype=prototype, out=out, @@ -2099,13 +2284,12 @@ async def _set_selection( prototype: BufferPrototype, fields: Fields | None = None, ) -> None: - """`_write_selection`, refused while the metadata stands for a stored document - whose repair moves chunks and has not been stored (see `setitem`).""" - if product(indexer.shape) > 0 and self.metadata._stored_document is not None: - raise ValueError( - f"Array {str(self.store_path)!r}: the stored metadata document needs a " - "repair that moves chunks; call `store_repair()` before writing chunks. " - "Nothing was written." + """`_write_selection`, refused while `needs_repair` is true.""" + if product(indexer.shape) > 0 and self._needs_repair: + raise MetadataRepairRequiredError( + f"Array {str(self._store_path)!r}: the stored metadata document needs a " + "repair that moves chunks; store the repaired metadata with " + "`store_metadata()` before storing chunks. Nothing was written." ) await self._write_selection(indexer, value, prototype=prototype, fields=fields) @@ -2120,88 +2304,54 @@ async def _write_selection( """Write without the check against a repair that has not been stored, for a caller that applies its own repair policy first (`AsyncArray`).""" await _set_selection( - self.store_path, - self.metadata, - self.codec_pipeline, - self.config, - self.chunk_grid, + self._store_path, + self._metadata, + self._codec_pipeline, + self._config, + self._chunk_grid, indexer, value, prototype=prototype, fields=fields, ) - async def store_repair(self) -> None: - """Store the repair of the array's current stored document, if its metadata was - read from one that needs a repair that moves chunks, and clear the mark that - says so (see the class docstring). - - The document is read again, because the store may hold a newer one than this - metadata. If that one lays out chunks differently (another writer stored a - different chunk size since), chunks written under this metadata would be found - by no reader, so it raises, stores nothing and keeps the mark. If it needs no - repair (the array was re-saved since, possibly by another implementation), it is - left as written; if there is none, there is nothing to repair. - - Storing the same repair twice is harmless, so handles that write chunks - concurrently need no coordination. The read and the store are not one atomic - step, though: a metadata write by another handle between them (a resize, an - attribute update) is replaced by the repair of the document read before it, as - with any two metadata writes that race. - """ - if self.metadata._stored_document is None: - return - await self._store_repair_document() - _stored_document_replaced(self.metadata) - async def _store_repair_document(self) -> None: - """`store_repair`'s reading and storing, leaving the metadata's mark to its - caller: `AsyncArray` clears it through its own `_stored_document_replaced`.""" - zarr_format = self.metadata.zarr_format - documents = await read_documents(self.store_path, ARRAY_DOCUMENTS[zarr_format]) + """Store the repair of the array's current stored document, for `AsyncArray`, + which reads the stored document again and clears the shared repair mark itself. + + The store may hold a newer document than this metadata. If that one lays out + chunks differently (another writer stored a different chunk size since), chunks + written under this metadata would be found by no reader, so it raises and + stores nothing. If it needs no repair (the array was re-saved since, possibly by + another implementation), it is left as written; if there is none, there is + nothing to repair. Storing the same repair twice is harmless; the read and the + store are not one atomic step, as with any two metadata writes that race. + """ + zarr_format = self._metadata.zarr_format + documents = await read_documents(self._store_path, ARRAY_DOCUMENTS[zarr_format]) try: - current = parse_stored_array(documents, zarr_format, str(self.store_path)) + current = parse_stored_array(documents, zarr_format, str(self._store_path)) except ArrayNotFoundError: pass else: - if _chunk_layout(current) != _chunk_layout(self.metadata): + if _chunk_layout(current) != _chunk_layout(self._metadata): raise ValueError( - f"Array {str(self.store_path)!r}: the metadata stored has changed since " + f"Array {str(self._store_path)!r}: the metadata stored has changed since " "this array was opened; reopen the array to write to it. Nothing was stored." ) if current._stored_document is not None: - await upsert_metadata(self.store_path, current, documents) - - async def resize( - self, new_shape: ShapeLike, *, delete_outside_chunks: bool = True - ) -> AsyncArrayIO: - """Store the metadata of the array resized to `new_shape`, deleting the chunks - outside it if `delete_outside_chunks`, and return the array as resized. - - The new metadata is encoded before any chunk is deleted: metadata that cannot be - stored then fails with the store untouched. The store then holds valid metadata, - so the repair mark of this value's metadata is cleared.""" - resized = await self._resized(new_shape, delete_outside_chunks) - _stored_document_replaced(self.metadata) - return resized + await upsert_metadata(self._store_path, current, documents) async def _resized(self, new_shape: ShapeLike, delete_outside_chunks: bool) -> AsyncArrayIO: - """`resize`'s storing, leaving the metadata's mark to its caller: `AsyncArray` - clears it through its own `_stored_document_replaced`.""" - new_shape = parse_shapelike(new_shape) - if len(new_shape) != len(self.metadata.shape): - raise ValueError( - f"The new shape must have the same number of dimensions as the array. " - f"Got {len(new_shape)} dimension(s), expected {len(self.metadata.shape)}." - ) - - new_metadata = self.metadata.update_shape(new_shape) - new_chunk_grid = ChunkGrid.from_metadata(new_metadata) - documents = encode_documents(self.store_path, new_metadata) - + """Store the metadata of the array resized to `new_shape`, deleting the chunks + outside it if `delete_outside_chunks`, for `AsyncArray.resize`, which clears the + shared repair mark itself. The new metadata is encoded before any chunk is + deleted: metadata that cannot be stored then fails with the store untouched.""" + resized = self.with_shape(new_shape) + documents = encode_documents(self._store_path, resized._metadata) if delete_outside_chunks: - old_grid_shape = self.chunk_grid.grid_shape - new_grid_shape = new_chunk_grid.grid_shape + old_grid_shape = self._chunk_grid.grid_shape + new_grid_shape = resized._chunk_grid.grid_shape # Chunks of the old grid outside the box it shares with the new grid. # Zero whenever no axis loses a whole chunk, including pure growth. n_delete = math.prod(old_grid_shape) - math.prod( @@ -2213,119 +2363,199 @@ async def _resized(self, new_shape: ShapeLike, delete_outside_chunks: bool) -> A limit = zarr_config.get("async.concurrency") or 1000 await concurrent_foreach( ( - (self.store_path / self.metadata.encode_chunk_key(coords),) + (self._store_path / self._metadata.encode_chunk_key(coords),) for coords in _iter_chunk_coords_to_delete(old_grid_shape, new_grid_shape) ), _delete_chunk, min(limit, n_delete), ) - - await store_documents(self.store_path, documents) - # A resize leaves the chunk encoding as it was, so the pipeline is kept. - return AsyncArrayIO._from_parts( - new_metadata, self.store_path, self.config, self.codec_pipeline, new_chunk_grid - ) - - async def update_attributes(self, new_attributes: dict[str, JSON]) -> AsyncArrayIO: - """Store the array's metadata with `new_attributes` merged into its attributes, - and return the array as it then is. This value's attributes are left as they - were. The store then holds valid metadata, so the repair mark of this value's - metadata is cleared.""" - new_metadata = self.metadata.update_attributes( - {**self.metadata.attributes, **new_attributes} - ) - await save_metadata(self.store_path, new_metadata) - _stored_document_replaced(self.metadata) - return AsyncArrayIO._from_parts( - new_metadata, self.store_path, self.config, self.codec_pipeline, self.chunk_grid - ) + await store_documents(self._store_path, documents) + return resized -@dataclass(frozen=True, slots=True) +@dataclass(frozen=True, slots=True, eq=False, init=False, repr=False) class ArrayIO: - """Reads and writes an array synchronously: each operation runs the matching - `AsyncArrayIO` operation with the runner its context holds. + """An array, as a value, read and written synchronously: each operation runs the + matching `AsyncArrayIO` operation with the runner its `SyncContext` holds. - A value, as `AsyncArrayIO` is: `resize` and `update_attributes` return the array - as it then is. + Make one with `open`, `from_metadata` or `of`, as for `AsyncArrayIO`, whose + documentation describes the value and its metadata changes. """ - async_io: AsyncArrayIO - context: SyncContext = field(default_factory=SyncContext, kw_only=True) + _async_io: AsyncArrayIO + _context: SyncContext - # Not hashable, as `AsyncArrayIO` is not. - __hash__ = None # type: ignore[assignment] + def __init__(self) -> None: + raise TypeError("Make an ArrayIO with ArrayIO.open, ArrayIO.from_metadata or ArrayIO.of.") @classmethod - def from_array( - cls, array: AsyncArray[Any] | Array[Any], *, context: SyncContext | None = None + def _wrap(cls, async_io: AsyncArrayIO, context: SyncContext) -> ArrayIO: + io = object.__new__(cls) + object.__setattr__(io, "_async_io", async_io) + object.__setattr__(io, "_context", context) + return io + + def _rewrap(self, async_io: AsyncArrayIO) -> ArrayIO: + return ArrayIO._wrap(async_io, self._context) + + def _run[T](self, coroutine: Coroutine[Any, Any, T]) -> T: + return self._context.runner.run(coroutine) + + @classmethod + def open( + cls, + store: Store, + path: str = "", + *, + zarr_format: ZarrFormat | None = None, + config: ArrayConfigLike | None = None, + context: SyncContext | None = None, ) -> ArrayIO: - """The array `array` reads and writes, as it is now.""" - return cls( - AsyncArrayIO.from_array(array), context=SyncContext() if context is None else context + """See `AsyncArrayIO.open`.""" + context = SyncContext() if context is None else context + opened = context.runner.run( + AsyncArrayIO.open(store, path, zarr_format=zarr_format, config=config) ) + return cls._wrap(opened, context) - def __repr__(self) -> str: - return f"" + @classmethod + def from_metadata( + cls, + metadata: ArrayMetadata | ArrayMetadataDict, + store: Store, + path: str = "", + *, + config: ArrayConfigLike | None = None, + context: SyncContext | None = None, + ) -> ArrayIO: + """See `AsyncArrayIO.from_metadata`.""" + return cls._wrap( + AsyncArrayIO.from_metadata(metadata, store, path, config=config), + SyncContext() if context is None else context, + ) - def _run[T](self, coroutine: Coroutine[Any, Any, T]) -> T: - return self.context.run(coroutine) + @classmethod + def of( + cls, array: AsyncArray[Any] | Array[Any], *, context: SyncContext | None = None + ) -> ArrayIO: + """See `AsyncArrayIO.of`.""" + return cls._wrap(AsyncArrayIO.of(array), SyncContext() if context is None else context) - @property - def metadata(self) -> ArrayMetadata: - """The array's metadata.""" - return self.async_io.metadata + def as_async(self) -> AsyncArrayIO: + """This array, read and written asynchronously.""" + return self._async_io + + def __repr__(self) -> str: + return f"" @property - def store_path(self) -> StorePath: - """Where in a store the array is.""" - return self.async_io.store_path + def metadata(self) -> dict[str, JSON]: + """See `AsyncArrayIO.metadata`.""" + return self._async_io.metadata @property - def config(self) -> ArrayConfig: - """The runtime configuration.""" - return self.async_io.config + def attrs(self) -> dict[str, JSON]: + """See `AsyncArrayIO.attrs`.""" + return self._async_io.attrs @property def shape(self) -> tuple[int, ...]: - """The shape of the array.""" - return self.async_io.shape + """See `AsyncArrayIO.shape`.""" + return self._async_io.shape + + @property + def ndim(self) -> int: + """See `AsyncArrayIO.ndim`.""" + return self._async_io.ndim @property def dtype(self) -> TBaseDType: - """The NumPy data type of the array.""" - return self.async_io.dtype + """See `AsyncArrayIO.dtype`.""" + return self._async_io.dtype + + @property + def store(self) -> Store: + """See `AsyncArrayIO.store`.""" + return self._async_io.store + + @property + def path(self) -> str: + """See `AsyncArrayIO.path`.""" + return self._async_io.path + + @property + def read_only(self) -> bool: + """See `AsyncArrayIO.read_only`.""" + return self._async_io.read_only + + @property + def needs_repair(self) -> bool: + """See `AsyncArrayIO.needs_repair`.""" + return self._async_io.needs_repair + + def with_shape(self, shape: ShapeLike) -> ArrayIO: + """See `AsyncArrayIO.with_shape`.""" + return self._rewrap(self._async_io.with_shape(shape)) - def getitem( + def with_attrs(self, attrs: Mapping[str, JSON]) -> ArrayIO: + """See `AsyncArrayIO.with_attrs`.""" + return self._rewrap(self._async_io.with_attrs(attrs)) + + def store_metadata(self) -> ArrayIO: + """See `AsyncArrayIO.store_metadata`.""" + return self._rewrap(self._run(self._async_io.store_metadata())) + + def erase_metadata(self) -> None: + """See `AsyncArrayIO.erase_metadata`.""" + self._run(self._async_io.erase_metadata()) + + def erase_chunk(self, chunk_coords: Sequence[int]) -> None: + """See `AsyncArrayIO.erase_chunk`.""" + self._run(self._async_io.erase_chunk(chunk_coords)) + + def erase_chunks(self, chunk_coords: Iterable[Sequence[int]]) -> None: + """See `AsyncArrayIO.erase_chunks`.""" + self._run(self._async_io.erase_chunks(chunk_coords)) + + def retrieve_array_subset( self, selection: BasicSelection, *, prototype: BufferPrototype | None = None ) -> NDArrayLikeOrScalar: - """See `AsyncArrayIO.getitem`.""" - return self._run(self.async_io.getitem(selection, prototype=prototype)) + """See `AsyncArrayIO.retrieve_array_subset`.""" + return self._run(self._async_io.retrieve_array_subset(selection, prototype=prototype)) - def setitem( + def store_array_subset( self, selection: BasicSelection, - value: npt.ArrayLike, + data: npt.ArrayLike, *, prototype: BufferPrototype | None = None, ) -> None: - """See `AsyncArrayIO.setitem`.""" - self._run(self.async_io.setitem(selection, value, prototype=prototype)) + """See `AsyncArrayIO.store_array_subset`.""" + self._run(self._async_io.store_array_subset(selection, data, prototype=prototype)) - def store_repair(self) -> None: - """See `AsyncArrayIO.store_repair`.""" - self._run(self.async_io.store_repair()) + def retrieve_chunk( + self, chunk_coords: Sequence[int], *, prototype: BufferPrototype | None = None + ) -> NDArrayLikeOrScalar: + """See `AsyncArrayIO.retrieve_chunk`.""" + return self._run(self._async_io.retrieve_chunk(chunk_coords, prototype=prototype)) - def resize(self, new_shape: ShapeLike, *, delete_outside_chunks: bool = True) -> ArrayIO: - """See `AsyncArrayIO.resize`.""" - resized = self._run( - self.async_io.resize(new_shape, delete_outside_chunks=delete_outside_chunks) - ) - return replace(self, async_io=resized) + def store_chunk( + self, + chunk_coords: Sequence[int], + data: npt.ArrayLike, + *, + prototype: BufferPrototype | None = None, + ) -> None: + """See `AsyncArrayIO.store_chunk`.""" + self._run(self._async_io.store_chunk(chunk_coords, data, prototype=prototype)) + + def __getitem__(self, selection: BasicSelection) -> NDArrayLikeOrScalar: + """`retrieve_array_subset(selection)`.""" + return self.retrieve_array_subset(selection) - def update_attributes(self, new_attributes: dict[str, JSON]) -> ArrayIO: - """See `AsyncArrayIO.update_attributes`.""" - return replace(self, async_io=self._run(self.async_io.update_attributes(new_attributes))) + def __setitem__(self, selection: BasicSelection, data: npt.ArrayLike) -> None: + """`store_array_subset(selection, data)`.""" + self.store_array_subset(selection, data) # TODO: Array can be a frozen data class again once property setters (e.g. shape) are removed @@ -6362,8 +6592,8 @@ async def _resize( array._stored_document_replaced() # Update metadata and chunk_grid (in place) - object.__setattr__(array, "metadata", resized.metadata) - object.__setattr__(array, "_chunk_grid", resized.chunk_grid) + object.__setattr__(array, "metadata", resized._metadata) + object.__setattr__(array, "_chunk_grid", resized._chunk_grid) async def _append( diff --git a/src/zarr/core/sync.py b/src/zarr/core/sync.py index 5db789c16d..76dcaf59cf 100644 --- a/src/zarr/core/sync.py +++ b/src/zarr/core/sync.py @@ -6,7 +6,7 @@ import os import threading from concurrent.futures import ThreadPoolExecutor, wait -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Protocol from zarr.core.config import config @@ -225,18 +225,25 @@ async def _with_semaphore[T]( class Runner(Protocol): - """Runs a coroutine to completion and returns its result, as `asyncio.run` does.""" + """Runs coroutines to completion, as `asyncio.Runner` does: `run` returns each + coroutine's result, or raises its exception.""" - def __call__[T](self, coroutine: Coroutine[Any, Any, T], /) -> T: ... + def run[T](self, coroutine: Coroutine[Any, Any, T], /) -> T: ... + + +class _ZarrLoopRunner: + """Runs coroutines on zarr's own event loop, on zarr's IO thread (see `sync`).""" + + def run[T](self, coroutine: Coroutine[Any, Any, T], /) -> T: + return sync(coroutine) @dataclass(frozen=True, slots=True, kw_only=True) class SyncContext: """How a synchronous API runs the coroutines it is built on.""" - run: Runner = sync - """Runs each coroutine to completion and returns its result, or raises its - exception, in the thread that called the synchronous API. The default, `sync`, runs - it on zarr's own event loop, on zarr's IO thread; `asyncio.Runner().run` runs it on - the calling thread instead. A store whose async clients belong to one event loop (as - fsspec's async filesystems do) needs every operation on it run on that loop.""" + runner: Runner = field(default_factory=_ZarrLoopRunner) + """Runs each coroutine in the thread that called the synchronous API. The default + runs it on zarr's own event loop, on zarr's IO thread; an `asyncio.Runner()` runs it + on the calling thread instead. A store whose async clients belong to one event loop + (as fsspec's async filesystems do) needs every operation on it run on that loop.""" diff --git a/src/zarr/errors.py b/src/zarr/errors.py index 803faf4884..34ad9ddb93 100644 --- a/src/zarr/errors.py +++ b/src/zarr/errors.py @@ -9,6 +9,7 @@ "ContainsGroupError", "DataTypeValidationError", "GroupNotFoundError", + "MetadataRepairRequiredError", "MetadataValidationError", "NegativeStepError", "NodeTypeValidationError", @@ -97,6 +98,14 @@ class MetadataValidationError(BaseZarrError): _msg = "Invalid value for '{}'. Expected '{}'. Got '{}'." +class MetadataRepairRequiredError(BaseZarrError): + """ + Raised when chunks would be stored under metadata repaired from a stored document in + a way that moves chunks, before the repaired metadata itself is stored: no reader of + the stored document would find them. + """ + + class UnknownCodecError(BaseZarrError): """ Raised when an unknown codec was used. diff --git a/tests/test_array_io.py b/tests/test_array_io.py index af09ed9eac..a5488813a7 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -1,11 +1,9 @@ -"""`AsyncArrayIO` reads and writes an array, and `ArrayIO` runs it synchronously.""" +"""`AsyncArrayIO` and `ArrayIO`: an array as a value, read and written explicitly.""" from __future__ import annotations import asyncio -import dataclasses import json -import pickle from typing import TYPE_CHECKING, Any, Literal import numpy as np @@ -14,8 +12,8 @@ import zarr from zarr.core.array import ArrayIO, AsyncArray, AsyncArrayIO from zarr.core.sync import SyncContext, sync -from zarr.errors import ZarrUserWarning -from zarr.storage import MemoryStore +from zarr.errors import MetadataRepairRequiredError, ZarrUserWarning +from zarr.storage import LocalStore, MemoryStore, StorePath if TYPE_CHECKING: from collections.abc import Coroutine, Iterator @@ -23,14 +21,13 @@ class _CountingRunner: - """A runner that counts the coroutines it runs, through `runner`, or zarr's - `sync` by default.""" + """Runs coroutines through `runner`, or zarr's `sync` without one, counting them.""" def __init__(self, runner: asyncio.Runner | None = None) -> None: self.runner = runner self.runs = 0 - def __call__[T](self, coroutine: Coroutine[Any, Any, T], /) -> T: + def run[T](self, coroutine: Coroutine[Any, Any, T], /) -> T: self.runs += 1 return sync(coroutine) if self.runner is None else self.runner.run(coroutine) @@ -43,97 +40,116 @@ def calling_thread_runner() -> Iterator[asyncio.Runner]: @pytest.mark.parametrize("zarr_format", [2, 3]) -@pytest.mark.parametrize("from_async", [False, True]) +@pytest.mark.parametrize("made_by", ["open", "from_metadata", "of"]) @pytest.mark.parametrize("on_calling_thread", [False, True]) -def test_array_io_reads_writes_and_resizes( +def test_array_io_reads_writes_and_changes_metadata( zarr_format: Literal[2, 3], - from_async: bool, + made_by: str, on_calling_thread: bool, calling_thread_runner: asyncio.Runner, ) -> None: - """`ArrayIO` reads and writes an array through the runner its context holds, on - zarr's loop or on the calling thread. `resize` and `update_attributes` store the - metadata and return the array as it then is, leaving the value they were called on, - and the array it was made from, as they were.""" + """An `ArrayIO` reads and writes through the runner its context holds. Metadata + changes return new values and store nothing until `store_metadata`; the values they + were made from, and the array a value was made from, are left as they were. + `with_attrs` replaces the attributes.""" + store = MemoryStore() array = zarr.create_array( - MemoryStore(), shape=(4,), chunks=(2,), dtype="int64", zarr_format=zarr_format + store, + name="a", + shape=(4,), + chunks=(2,), + dtype="int64", + zarr_format=zarr_format, + attributes={"old": 0}, ) runner = _CountingRunner(calling_thread_runner if on_calling_thread else None) - source: AsyncArray[Any] | zarr.Array[Any] = array.async_array if from_async else array - io = ArrayIO.from_array(source, context=SyncContext(run=runner)) - - io.setitem(slice(None), np.arange(4)) - resized = io.resize((6,)) - resized.setitem(slice(4, 6), [7, 8]) - updated = resized.update_attributes({"a": 1}) - - np.testing.assert_array_equal(updated.getitem(slice(None)), [0, 1, 2, 3, 7, 8]) - assert (io.shape, resized.shape, array.shape) == ((4,), (6,), (4,)) - assert (resized.metadata.attributes, dict(array.attrs)) == ({}, {}) - reopened = zarr.open_array(array.store_path.store) + context = SyncContext(runner=runner) + if made_by == "open": + io = ArrayIO.open(store, "a", context=context) + elif made_by == "from_metadata": + io = ArrayIO.from_metadata(array.metadata, store, "a", context=context) + else: + io = ArrayIO.of(array, context=context) + array.attrs["late"] = 1 + + io[:] = np.arange(4) + io.store_chunk([1], [7, 8]) + grown = io.with_shape((6,)) + stored_before = zarr.open_array(store, path="a").shape + labeled = grown.store_metadata().with_attrs({"a": 1}).store_metadata() + labeled.erase_chunk([0]) + + np.testing.assert_array_equal(labeled[:], [0, 0, 7, 8, 0, 0]) + np.testing.assert_array_equal(labeled.retrieve_chunk([1]), [7, 8]) + assert stored_before == (4,) + assert (io.shape, io.attrs, labeled.attrs) == ((4,), {"old": 0}, {"a": 1}) + reopened = zarr.open_array(store, path="a") assert (reopened.shape, dict(reopened.attrs)) == ((6,), {"a": 1}) - assert runner.runs == 5 + assert runner.runs >= 6 -@pytest.mark.parametrize("zarr_format", [2, 3]) -def test_async_array_io_is_a_value_over_its_metadata(zarr_format: Literal[2, 3]) -> None: - """Making an `AsyncArrayIO` from its metadata, location and configuration derives its - codec pipeline and chunk grid. It equals the value read from an array over the same - parts, a changed copy derives them again, and it pickles.""" - array = zarr.create_array( - MemoryStore(), shape=(4,), chunks=(2,), dtype="int64", zarr_format=zarr_format - ) - made = AsyncArrayIO(metadata=array.metadata, store_path=array.store_path, config=array.config) - grown = dataclasses.replace(made, metadata=made.metadata.update_shape((8,))) +async def test_async_array_io_reads_and_writes() -> None: + """`AsyncArrayIO` opens, reads and writes an array asynchronously, and `as_sync` and + `as_async` move between it and `ArrayIO`.""" + store = MemoryStore() + zarr.create_array(store, name="a", shape=(4,), chunks=(2,), dtype="int64") + io = await AsyncArrayIO.open(store, "a") - assert made == AsyncArrayIO.from_array(array) - assert made.chunk_grid.grid_shape == array.async_array._chunk_grid.grid_shape - assert grown.chunk_grid.grid_shape == (4,) - assert pickle.loads(pickle.dumps(made)) == made - assert repr(made) == f"" + await io.store_array_subset(slice(None), np.arange(4)) - -def test_async_array_io_takes_its_parts_by_keyword() -> None: - array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") - with pytest.raises(TypeError): - AsyncArrayIO(array.metadata, array.store_path) # type: ignore[call-arg] + np.testing.assert_array_equal(await io[1:3], [1, 2]) + np.testing.assert_array_equal(await io.retrieve_chunk([1]), [2, 3]) + assert io.as_sync().as_async() is io + assert repr(io) == f"" @pytest.mark.parametrize("zarr_format", [2, 3]) -def test_async_array_io_stores_a_repair_then_writes( - tmp_path: Path, zarr_format: Literal[2, 3] -) -> None: - """An array read from a stored document whose repair moves chunks writes chunks once - `store_repair` has stored the repair.""" +def test_store_metadata_stores_the_repair(tmp_path: Path, zarr_format: Literal[2, 3]) -> None: + """A value opened from a stored document whose repair moves chunks needs a repair; + storing its metadata stores the repair, and the value returned writes chunks.""" path = tmp_path / "legacy.zarr" _legacy_array(path, zarr_format) with pytest.warns(ZarrUserWarning, match="is read as"): - io = AsyncArrayIO.from_array(zarr.open_array(path, mode="r+")) + io = ArrayIO.open(LocalStore(path)) - sync(io.store_repair()) - sync(io.setitem(slice(None), [1, 2, 3])) + repaired = io.store_metadata() + repaired[:] = [1, 2, 3] + assert (io.needs_repair, repaired.needs_repair) == (True, False) np.testing.assert_array_equal(zarr.open_array(path)[:], [1, 2, 3]) @pytest.mark.parametrize("zarr_format", [2, 3]) -def test_async_array_io_refuses_chunk_writes_before_a_repair( +def test_chunks_are_refused_until_the_repair_is_stored( tmp_path: Path, zarr_format: Literal[2, 3] ) -> None: - """Writing chunks under metadata read from a document whose repair moves chunks - raises, writing nothing, until the repair is stored.""" + """Storing chunks under metadata whose repair moves chunks, or under a value derived + from it, raises and writes nothing until the repaired metadata is stored.""" path = tmp_path / "legacy.zarr" _legacy_array(path, zarr_format) with pytest.warns(ZarrUserWarning, match="is read as"): - io = AsyncArrayIO.from_array(zarr.open_array(path, mode="r+")) + io = ArrayIO.open(LocalStore(path)).with_attrs({"a": 1}) before = {p: p.read_bytes() for p in path.rglob("*") if p.is_file()} - with pytest.raises(ValueError, match=r"call `store_repair\(\)` before writing chunks"): - sync(io.setitem(slice(None), [1, 2, 3])) + with pytest.raises(MetadataRepairRequiredError, match=r"store_metadata\(\)"): + io[:] = [1, 2, 3] assert {p: p.read_bytes() for p in path.rglob("*") if p.is_file()} == before +def test_array_io_is_made_only_by_its_constructors() -> None: + with pytest.raises(TypeError, match="AsyncArrayIO.open"): + AsyncArrayIO() + with pytest.raises(TypeError, match="ArrayIO.open"): + ArrayIO() + + +def test_with_shape_rejects_another_number_of_dimensions() -> None: + array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") + with pytest.raises(ValueError, match="same number of dimensions"): + AsyncArrayIO.of(array).with_shape((4, 4)) + + class _HookedAsyncArray(AsyncArray[Any]): """An `AsyncArray` subclass that records its repair hooks and stores no repair.""" @@ -192,12 +208,6 @@ def test_async_array_clears_the_repair_mark_through_its_hook( assert keeps.metadata._stored_document is not None -def test_async_array_io_resize_rejects_another_number_of_dimensions() -> None: - array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") - with pytest.raises(ValueError, match="same number of dimensions"): - sync(AsyncArrayIO.from_array(array).resize((4, 4))) - - def _legacy_array(path: Path, zarr_format: Literal[2, 3]) -> None: """Store an array of shape (3,) whose stored chunk shape is `[0]`.""" zarr.create_array(store=path, shape=(3,), chunks=(3,), dtype="int16", zarr_format=zarr_format) From 869da17c8c125de5aceb1509d1499c05ff1098b6 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 19:31:36 +0100 Subject: [PATCH 10/31] fix(array): make ArrayIO values stateless and refuse writes that lose data From the review of the reshaped API: - attributes are deep-copied wherever a value takes them in or hands them out, so no dict reaches another value or the array a value was made from; - store_array_subset and store_chunk refuse data that does not fit the region (ValueError) or whose values would not survive the cast (TypeError); - every chunk method takes non-negative chunk indices, one for each dimension; reads and writes need them inside the chunk grid, erasing does not; - open and from_metadata take no config: values use fixed defaults, not the global configuration; - read_only is gone, the classes are final, selection, data, indices, shape and attrs are positional-only, and as_sync needs its context; - docstrings say what metadata returns, what growing after a shrink reads, and how to write after storing a repair. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 248 +++++++++++++++++++++++++++-------------- src/zarr/core/sync.py | 9 +- tests/test_array_io.py | 114 +++++++++++++++++-- 3 files changed, 274 insertions(+), 97 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index aa1d88943b..4650b1b65f 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -3,6 +3,7 @@ import contextlib import copy import math +import operator import warnings from asyncio import gather from collections.abc import Iterable, Mapping, Sequence @@ -12,9 +13,11 @@ from typing import ( TYPE_CHECKING, Any, + Final, Literal, TypedDict, cast, + final, overload, ) from warnings import warn @@ -1937,14 +1940,62 @@ async def _delete_chunk(key: StorePath) -> None: def _snapshot(metadata: ArrayMetadata) -> ArrayMetadata: - """A copy of `metadata` with an attributes dict of its own, so a change to the - attributes of the original (which an `AsyncArray` makes in place) never reaches - the copy. The repair mark, an instance attribute, is copied with it.""" + """A copy of `metadata` with attributes of its own, nested values included, so a + change to the attributes of the original (which an `AsyncArray` makes in place) + never reaches the copy. The repair mark, an instance attribute, is copied with it.""" copied = copy.copy(metadata) - object.__setattr__(copied, "attributes", dict(metadata.attributes)) + object.__setattr__(copied, "attributes", copy.deepcopy(metadata.attributes)) return copied +_ARRAY_IO_CONFIG: Final = ArrayConfig(order="C", write_empty_chunks=False) +"""The runtime configuration of an `AsyncArrayIO` that is not made from an array: fixed, +not read from the global configuration.""" + + +def _checked_data(data: npt.ArrayLike, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: + """`data` to write to a region of `shape` of an array of `dtype`, refused if writing + it would lose values: if it does not broadcast to `shape` (extra values would be + dropped), or, for numeric data, if its values do not cast to `dtype` without + changing kind (a float into an integer, a signed integer array into an unsigned one). + Python numbers are cast by their values, as NumPy casts them: one out of range + raises.""" + numeric = "biufc" + if hasattr(data, "dtype") and hasattr(data, "shape"): + if ( + data.dtype.kind in numeric + and dtype.kind in numeric + and not np.can_cast(data.dtype, dtype, casting="same_kind") + ): + raise TypeError( + f"Cannot write data of dtype {data.dtype} to an array of dtype {dtype} " + "without losing values; cast it first." + ) + data_shape = tuple(data.shape) + else: + natural = np.asarray(data) + if natural.dtype.kind in "iu" and dtype.kind in "iu": + data = np.asarray(data, dtype=dtype) + elif ( + natural.dtype.kind in numeric + and dtype.kind in numeric + and not np.can_cast(natural.dtype, dtype, casting="same_kind") + ): + raise TypeError( + f"Cannot write values of dtype {natural.dtype} to an array of dtype {dtype} " + "without losing values; cast them first." + ) + data_shape = natural.shape + try: + broadcast = np.broadcast_shapes(data_shape, shape) + except ValueError: + broadcast = None + if broadcast != shape: + raise ValueError(f"Data of shape {data_shape} does not fit a region of shape {shape}.") + return data + + +@final @dataclass(frozen=True, slots=True, eq=False, init=False, repr=False) class AsyncArrayIO: """An array, as a value: its metadata, bound to a location in a store. @@ -2000,10 +2051,7 @@ def _from_parts( @classmethod def _bound( - cls, - metadata: ArrayMetadata | ArrayMetadataDict, - store_path: StorePath, - config: ArrayConfigLike | None, + cls, metadata: ArrayMetadata | ArrayMetadataDict, store_path: StorePath ) -> AsyncArrayIO: """A value over `metadata`, read as `AsyncArray` reads it, deriving its codec pipeline and chunk grid.""" @@ -2011,7 +2059,7 @@ def _bound( return cls._from_parts( parsed, store_path, - parse_array_config(config), + _ARRAY_IO_CONFIG, create_codec_pipeline(metadata=parsed, store=store_path.store), ChunkGrid.from_metadata(parsed), parsed._stored_document is not None, @@ -2024,15 +2072,15 @@ async def open( path: str = "", *, zarr_format: ZarrFormat | None = None, - config: ArrayConfigLike | None = None, ) -> AsyncArrayIO: """The array whose metadata `store` holds at `path`, of either Zarr format unless `zarr_format` says which. - Raises `ArrayNotFoundError` if there is none.""" + Raises `ArrayNotFoundError` if there is no array metadata there, and + `NodeTypeValidationError` if a group's is.""" store_path = StorePath(store, path) document = await get_array_metadata(store_path, zarr_format=zarr_format) - return cls._bound(cast("ArrayMetadataDict", document), store_path, config) + return cls._bound(cast("ArrayMetadataDict", document), store_path) @classmethod def from_metadata( @@ -2040,17 +2088,14 @@ def from_metadata( metadata: ArrayMetadata | ArrayMetadataDict, store: Store, path: str = "", - *, - config: ArrayConfigLike | None = None, ) -> AsyncArrayIO: """An array at `path` in `store` with `metadata`, a metadata object or document. Nothing is stored and nothing is checked against the store: call `store_metadata` to store the metadata, and do so before storing chunks unless the store already holds it.""" - if not isinstance(metadata, dict): - metadata = _snapshot(metadata) - return cls._bound(metadata, StorePath(store, path), config) + metadata = copy.deepcopy(metadata) if isinstance(metadata, dict) else _snapshot(metadata) + return cls._bound(metadata, StorePath(store, path)) @classmethod def of(cls, array: AsyncArray[Any] | Array[Any]) -> AsyncArrayIO: @@ -2080,22 +2125,25 @@ def _of(cls, array: AsyncArray[Any]) -> AsyncArrayIO: array.metadata._stored_document is not None, ) - def as_sync(self, *, context: SyncContext | None = None) -> ArrayIO: - """This array, read and written synchronously with the runner `context` holds.""" - return ArrayIO._wrap(self, SyncContext() if context is None else context) + def as_sync(self, *, context: SyncContext) -> ArrayIO: + """This array, read and written synchronously with the runner `context` holds: + one that runs coroutines where this value's store clients can run them.""" + return ArrayIO._wrap(self, context) def __repr__(self) -> str: return f"" @property def metadata(self) -> dict[str, JSON]: - """The array's metadata document, as `store_metadata` would store it.""" - return self._metadata.to_dict() + """The array's metadata as a document of its own, which `from_metadata` reads + back: the `zarr.json` document for Zarr format 3, or for format 2 the `.zarray` + document with the attributes under `"attributes"`.""" + return copy.deepcopy(self._metadata.to_dict()) @property def attrs(self) -> dict[str, JSON]: - """The array's user attributes.""" - return dict(self._metadata.attributes) + """The array's user attributes, as a dict of its own.""" + return copy.deepcopy(self._metadata.attributes) @property def shape(self) -> tuple[int, ...]: @@ -2122,22 +2170,20 @@ def path(self) -> str: """The array's path in its store.""" return self._store_path.path - @property - def read_only(self) -> bool: - """Whether the store refuses writes.""" - return self._store_path.store.read_only - @property def needs_repair(self) -> bool: """Whether this value's metadata was repaired from a stored document in a way that moves chunks, and has not been stored since: chunks cannot be stored until - `store_metadata` has stored it.""" + `store_metadata` has stored it, and are then stored through the value it + returns. A repair that reads a regular grid's edge lists as a rectilinear grid + can be stored only while rectilinear chunk grids are enabled.""" return self._needs_repair - def with_shape(self, shape: ShapeLike) -> AsyncArrayIO: - """This array with `shape`. Nothing is stored and no chunk is erased: growing - reads the new region as the fill value, and chunks outside a smaller shape stay - in the store until erased (`erase_chunks`).""" + def with_shape(self, shape: ShapeLike, /) -> AsyncArrayIO: + """This array with `shape`. Nothing is stored and no chunk is erased: chunks + outside a smaller shape stay in the store until erased (`erase_chunks`), and + growing again reads what they and the edge chunks still hold beyond the old + shape; the new region reads as the fill value only where no chunk was stored.""" new_shape = parse_shapelike(shape) if len(new_shape) != len(self._metadata.shape): raise ValueError( @@ -2154,12 +2200,12 @@ def with_shape(self, shape: ShapeLike) -> AsyncArrayIO: self._needs_repair, ) - def with_attrs(self, attrs: Mapping[str, JSON]) -> AsyncArrayIO: + def with_attrs(self, attrs: Mapping[str, JSON], /) -> AsyncArrayIO: """This array with the user attributes `attrs`, which replace the old ones: merge them yourself to keep them (`io.with_attrs({**io.attrs, "units": "m"})`). Nothing is stored.""" return AsyncArrayIO._from_parts( - self._metadata.update_attributes(dict(attrs)), + self._metadata.update_attributes(copy.deepcopy(dict(attrs))), self._store_path, self._config, self._codec_pipeline, @@ -2187,16 +2233,39 @@ async def erase_metadata(self) -> None: keys = ARRAY_DOCUMENTS[self._metadata.zarr_format] await gather(*((self._store_path / key).delete() for key in keys)) - async def erase_chunk(self, chunk_coords: Sequence[int]) -> None: - """Delete the chunk at `chunk_coords` from the store; it then reads as the fill - value. Succeeds if there is none.""" - await (self._store_path / self._metadata.encode_chunk_key(tuple(chunk_coords))).delete() - - async def erase_chunks(self, chunk_coords: Iterable[Sequence[int]]) -> None: - """Delete the chunks at each of `chunk_coords` from the store.""" + def _chunk_indices(self, chunk_indices: Sequence[int], *, in_grid: bool) -> tuple[int, ...]: + """`chunk_indices` as a tuple of non-negative ints, one for each dimension; with + `in_grid`, within the chunk grid.""" + indices = tuple(operator.index(index) for index in chunk_indices) + if len(indices) != self.ndim: + raise ValueError( + f"Chunk indices {indices} do not have one index for each of the array's " + f"{self.ndim} dimensions." + ) + if any(index < 0 for index in indices): + raise ValueError(f"Chunk indices {indices} must be non-negative.") + grid_shape = self._chunk_grid.grid_shape + if in_grid and any( + index >= extent for index, extent in zip(indices, grid_shape, strict=True) + ): + raise IndexError(f"Chunk indices {indices} are outside the chunk grid {grid_shape}.") + return indices + + async def erase_chunk(self, chunk_indices: Sequence[int], /) -> None: + """Delete the chunk at `chunk_indices` from the store; it then reads as the fill + value. Succeeds if there is none. Indices outside the chunk grid are allowed, + to reclaim chunks left outside a smaller shape.""" + indices = self._chunk_indices(chunk_indices, in_grid=False) + await (self._store_path / self._metadata.encode_chunk_key(indices)).delete() + + async def erase_chunks(self, chunk_indices: Iterable[Sequence[int]], /) -> None: + """Delete the chunk at each of `chunk_indices`, as `erase_chunk` does.""" keys = [ - (self._store_path / self._metadata.encode_chunk_key(tuple(coords)),) - for coords in chunk_coords + ( + self._store_path + / self._metadata.encode_chunk_key(self._chunk_indices(indices, in_grid=False)), + ) + for indices in chunk_indices ] if keys: # `None` lifts the I/O concurrency limit, but the worker pool still needs a @@ -2205,7 +2274,7 @@ async def erase_chunks(self, chunk_coords: Iterable[Sequence[int]]) -> None: await concurrent_foreach(iter(keys), _delete_chunk, min(limit, len(keys))) async def retrieve_array_subset( - self, selection: BasicSelection, *, prototype: BufferPrototype | None = None + self, selection: BasicSelection, /, *, prototype: BufferPrototype | None = None ) -> NDArrayLikeOrScalar: """The values at `selection`, by NumPy basic indexing.""" indexer = BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) @@ -2217,42 +2286,60 @@ async def store_array_subset( self, selection: BasicSelection, data: npt.ArrayLike, + /, *, prototype: BufferPrototype | None = None, ) -> None: """Write `data` at `selection`, by NumPy basic indexing. - Raises `MetadataRepairRequiredError`, writing nothing, while `needs_repair` is - true: no reader of the stored document would find the chunks.""" + Raises `ValueError` if `data` does not broadcast to the selected region, and + `TypeError` if its values would not survive the cast to the array's data type + (see the class documentation). Raises `MetadataRepairRequiredError` while + `needs_repair` is true. Nothing is written when it raises.""" indexer = BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) await self._set_selection( - indexer, data, prototype=default_buffer_prototype() if prototype is None else prototype + indexer, + _checked_data(data, self.dtype, indexer.shape), + prototype=default_buffer_prototype() if prototype is None else prototype, ) async def retrieve_chunk( - self, chunk_coords: Sequence[int], *, prototype: BufferPrototype | None = None + self, chunk_indices: Sequence[int], /, *, prototype: BufferPrototype | None = None ) -> NDArrayLikeOrScalar: - """The values of the chunk at `chunk_coords`, decoded.""" - indexer = BlockIndexer(tuple(chunk_coords), self._metadata.shape, self._chunk_grid) + """The decoded values of the chunk at `chunk_indices`, within the array: a chunk + at the array's edge gives only the part inside the array's shape.""" + indexer = BlockIndexer( + self._chunk_indices(chunk_indices, in_grid=True), + self._metadata.shape, + self._chunk_grid, + ) return await self._get_selection( indexer, prototype=default_buffer_prototype() if prototype is None else prototype ) async def store_chunk( self, - chunk_coords: Sequence[int], + chunk_indices: Sequence[int], data: npt.ArrayLike, + /, *, prototype: BufferPrototype | None = None, ) -> None: - """Encode `data` as the chunk at `chunk_coords` and write it; raises as - `store_array_subset` does.""" - indexer = BlockIndexer(tuple(chunk_coords), self._metadata.shape, self._chunk_grid) + """Encode `data` as the chunk at `chunk_indices` and write it. For a chunk at + the array's edge, `data` covers only the part inside the array's shape, as + `retrieve_chunk` gives it. Raises as `store_array_subset` does.""" + indexer = BlockIndexer( + self._chunk_indices(chunk_indices, in_grid=True), + self._metadata.shape, + self._chunk_grid, + ) await self._set_selection( - indexer, data, prototype=default_buffer_prototype() if prototype is None else prototype + indexer, + _checked_data(data, self.dtype, indexer.shape), + prototype=default_buffer_prototype() if prototype is None else prototype, ) - async def __getitem__(self, selection: BasicSelection) -> NDArrayLikeOrScalar: + async def __getitem__(self, selection: BasicSelection, /) -> NDArrayLikeOrScalar: """`retrieve_array_subset(selection)`.""" return await self.retrieve_array_subset(selection) @@ -2289,7 +2376,8 @@ async def _set_selection( raise MetadataRepairRequiredError( f"Array {str(self._store_path)!r}: the stored metadata document needs a " "repair that moves chunks; store the repaired metadata with " - "`store_metadata()` before storing chunks. Nothing was written." + "`store_metadata()` and write through the value it returns. Nothing was " + "written." ) await self._write_selection(indexer, value, prototype=prototype, fields=fields) @@ -2373,6 +2461,7 @@ async def _resized(self, new_shape: ShapeLike, delete_outside_chunks: bool) -> A return resized +@final @dataclass(frozen=True, slots=True, eq=False, init=False, repr=False) class ArrayIO: """An array, as a value, read and written synchronously: each operation runs the @@ -2408,14 +2497,11 @@ def open( path: str = "", *, zarr_format: ZarrFormat | None = None, - config: ArrayConfigLike | None = None, context: SyncContext | None = None, ) -> ArrayIO: """See `AsyncArrayIO.open`.""" context = SyncContext() if context is None else context - opened = context.runner.run( - AsyncArrayIO.open(store, path, zarr_format=zarr_format, config=config) - ) + opened = context.runner.run(AsyncArrayIO.open(store, path, zarr_format=zarr_format)) return cls._wrap(opened, context) @classmethod @@ -2425,12 +2511,11 @@ def from_metadata( store: Store, path: str = "", *, - config: ArrayConfigLike | None = None, context: SyncContext | None = None, ) -> ArrayIO: """See `AsyncArrayIO.from_metadata`.""" return cls._wrap( - AsyncArrayIO.from_metadata(metadata, store, path, config=config), + AsyncArrayIO.from_metadata(metadata, store, path), SyncContext() if context is None else context, ) @@ -2483,21 +2568,16 @@ def path(self) -> str: """See `AsyncArrayIO.path`.""" return self._async_io.path - @property - def read_only(self) -> bool: - """See `AsyncArrayIO.read_only`.""" - return self._async_io.read_only - @property def needs_repair(self) -> bool: """See `AsyncArrayIO.needs_repair`.""" return self._async_io.needs_repair - def with_shape(self, shape: ShapeLike) -> ArrayIO: + def with_shape(self, shape: ShapeLike, /) -> ArrayIO: """See `AsyncArrayIO.with_shape`.""" return self._rewrap(self._async_io.with_shape(shape)) - def with_attrs(self, attrs: Mapping[str, JSON]) -> ArrayIO: + def with_attrs(self, attrs: Mapping[str, JSON], /) -> ArrayIO: """See `AsyncArrayIO.with_attrs`.""" return self._rewrap(self._async_io.with_attrs(attrs)) @@ -2509,16 +2589,16 @@ def erase_metadata(self) -> None: """See `AsyncArrayIO.erase_metadata`.""" self._run(self._async_io.erase_metadata()) - def erase_chunk(self, chunk_coords: Sequence[int]) -> None: + def erase_chunk(self, chunk_indices: Sequence[int], /) -> None: """See `AsyncArrayIO.erase_chunk`.""" - self._run(self._async_io.erase_chunk(chunk_coords)) + self._run(self._async_io.erase_chunk(chunk_indices)) - def erase_chunks(self, chunk_coords: Iterable[Sequence[int]]) -> None: + def erase_chunks(self, chunk_indices: Iterable[Sequence[int]], /) -> None: """See `AsyncArrayIO.erase_chunks`.""" - self._run(self._async_io.erase_chunks(chunk_coords)) + self._run(self._async_io.erase_chunks(chunk_indices)) def retrieve_array_subset( - self, selection: BasicSelection, *, prototype: BufferPrototype | None = None + self, selection: BasicSelection, /, *, prototype: BufferPrototype | None = None ) -> NDArrayLikeOrScalar: """See `AsyncArrayIO.retrieve_array_subset`.""" return self._run(self._async_io.retrieve_array_subset(selection, prototype=prototype)) @@ -2527,6 +2607,7 @@ def store_array_subset( self, selection: BasicSelection, data: npt.ArrayLike, + /, *, prototype: BufferPrototype | None = None, ) -> None: @@ -2534,26 +2615,27 @@ def store_array_subset( self._run(self._async_io.store_array_subset(selection, data, prototype=prototype)) def retrieve_chunk( - self, chunk_coords: Sequence[int], *, prototype: BufferPrototype | None = None + self, chunk_indices: Sequence[int], /, *, prototype: BufferPrototype | None = None ) -> NDArrayLikeOrScalar: """See `AsyncArrayIO.retrieve_chunk`.""" - return self._run(self._async_io.retrieve_chunk(chunk_coords, prototype=prototype)) + return self._run(self._async_io.retrieve_chunk(chunk_indices, prototype=prototype)) def store_chunk( self, - chunk_coords: Sequence[int], + chunk_indices: Sequence[int], data: npt.ArrayLike, + /, *, prototype: BufferPrototype | None = None, ) -> None: """See `AsyncArrayIO.store_chunk`.""" - self._run(self._async_io.store_chunk(chunk_coords, data, prototype=prototype)) + self._run(self._async_io.store_chunk(chunk_indices, data, prototype=prototype)) - def __getitem__(self, selection: BasicSelection) -> NDArrayLikeOrScalar: + def __getitem__(self, selection: BasicSelection, /) -> NDArrayLikeOrScalar: """`retrieve_array_subset(selection)`.""" return self.retrieve_array_subset(selection) - def __setitem__(self, selection: BasicSelection, data: npt.ArrayLike) -> None: + def __setitem__(self, selection: BasicSelection, data: npt.ArrayLike, /) -> None: """`store_array_subset(selection, data)`.""" self.store_array_subset(selection, data) diff --git a/src/zarr/core/sync.py b/src/zarr/core/sync.py index 76dcaf59cf..c91e6c3094 100644 --- a/src/zarr/core/sync.py +++ b/src/zarr/core/sync.py @@ -243,7 +243,8 @@ class SyncContext: """How a synchronous API runs the coroutines it is built on.""" runner: Runner = field(default_factory=_ZarrLoopRunner) - """Runs each coroutine in the thread that called the synchronous API. The default - runs it on zarr's own event loop, on zarr's IO thread; an `asyncio.Runner()` runs it - on the calling thread instead. A store whose async clients belong to one event loop - (as fsspec's async filesystems do) needs every operation on it run on that loop.""" + """Runs each coroutine to completion for the thread that called the synchronous API, + which waits for it. The default runs it on zarr's own event loop, on zarr's IO + thread, with no timeout; an `asyncio.Runner()` runs it on the calling thread. A + store whose async clients belong to one event loop (as fsspec's async filesystems + do) needs every operation on it run on that loop.""" diff --git a/tests/test_array_io.py b/tests/test_array_io.py index a5488813a7..8e638415da 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -4,7 +4,7 @@ import asyncio import json -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Any, Literal, cast import numpy as np import pytest @@ -40,7 +40,7 @@ def calling_thread_runner() -> Iterator[asyncio.Runner]: @pytest.mark.parametrize("zarr_format", [2, 3]) -@pytest.mark.parametrize("made_by", ["open", "from_metadata", "of"]) +@pytest.mark.parametrize("made_by", ["open", "from_metadata", "of", "of-async"]) @pytest.mark.parametrize("on_calling_thread", [False, True]) def test_array_io_reads_writes_and_changes_metadata( zarr_format: Literal[2, 3], @@ -51,7 +51,8 @@ def test_array_io_reads_writes_and_changes_metadata( """An `ArrayIO` reads and writes through the runner its context holds. Metadata changes return new values and store nothing until `store_metadata`; the values they were made from, and the array a value was made from, are left as they were. - `with_attrs` replaces the attributes.""" + `with_attrs` replaces the attributes, and no attribute dict a value takes in or hands + out reaches another value or the array.""" store = MemoryStore() array = zarr.create_array( store, @@ -60,7 +61,7 @@ def test_array_io_reads_writes_and_changes_metadata( chunks=(2,), dtype="int64", zarr_format=zarr_format, - attributes={"old": 0}, + attributes={"old": 0, "n": [1]}, ) runner = _CountingRunner(calling_thread_runner if on_calling_thread else None) context = SyncContext(runner=runner) @@ -68,24 +69,31 @@ def test_array_io_reads_writes_and_changes_metadata( io = ArrayIO.open(store, "a", context=context) elif made_by == "from_metadata": io = ArrayIO.from_metadata(array.metadata, store, "a", context=context) - else: + elif made_by == "of": io = ArrayIO.of(array, context=context) + else: + io = ArrayIO.of(array.async_array, context=context) array.attrs["late"] = 1 + cast("list[int]", io.attrs["n"]).append(2) + cast("list[int]", cast("dict[str, Any]", io.metadata["attributes"])["n"]).append(3) + attrs = {"a": [1]} io[:] = np.arange(4) io.store_chunk([1], [7, 8]) grown = io.with_shape((6,)) stored_before = zarr.open_array(store, path="a").shape - labeled = grown.store_metadata().with_attrs({"a": 1}).store_metadata() + labeled = grown.store_metadata().with_attrs(attrs).store_metadata() + attrs["a"].append(2) labeled.erase_chunk([0]) np.testing.assert_array_equal(labeled[:], [0, 0, 7, 8, 0, 0]) np.testing.assert_array_equal(labeled.retrieve_chunk([1]), [7, 8]) assert stored_before == (4,) - assert (io.shape, io.attrs, labeled.attrs) == ((4,), {"old": 0}, {"a": 1}) + assert (io.shape, io.attrs, labeled.attrs) == ((4,), {"old": 0, "n": [1]}, {"a": [1]}) reopened = zarr.open_array(store, path="a") - assert (reopened.shape, dict(reopened.attrs)) == ((6,), {"a": 1}) - assert runner.runs >= 6 + assert (reopened.shape, dict(reopened.attrs)) == ((6,), {"a": [1]}) + # One run for each read and write, and for opening. + assert runner.runs == 7 + (made_by == "open") async def test_async_array_io_reads_and_writes() -> None: @@ -99,7 +107,7 @@ async def test_async_array_io_reads_and_writes() -> None: np.testing.assert_array_equal(await io[1:3], [1, 2]) np.testing.assert_array_equal(await io.retrieve_chunk([1]), [2, 3]) - assert io.as_sync().as_async() is io + assert io.as_sync(context=SyncContext()).as_async() is io assert repr(io) == f"" @@ -116,6 +124,7 @@ def test_store_metadata_stores_the_repair(tmp_path: Path, zarr_format: Literal[2 repaired[:] = [1, 2, 3] assert (io.needs_repair, repaired.needs_repair) == (True, False) + assert _stored_chunks(path, zarr_format) == [1] np.testing.assert_array_equal(zarr.open_array(path)[:], [1, 2, 3]) @@ -137,6 +146,79 @@ def test_chunks_are_refused_until_the_repair_is_stored( assert {p: p.read_bytes() for p in path.rglob("*") if p.is_file()} == before +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("separator", [".", "/"]) +def test_erase_deletes_chunks_and_metadata(zarr_format: Literal[2, 3], separator: str) -> None: + """`erase_chunk` and `erase_chunks` delete chunks, inside the chunk grid or left + outside a smaller shape, and `erase_metadata` deletes the array's documents.""" + store = MemoryStore() + array = zarr.create_array( + store, + name="a", + shape=(6,), + chunks=(2,), + dtype="int64", + zarr_format=zarr_format, + chunk_key_encoding={ + "name": "v2" if zarr_format == 2 else "default", + "separator": separator, + }, + ) + array[:] = np.arange(1, 7) + io = ArrayIO.of(array).with_shape((2,)).store_metadata() + + io.erase_chunks([[1], [2]]) + regrown = io.with_shape((6,)) + io.erase_chunk([0]) + + np.testing.assert_array_equal(regrown[:], [0, 0, 0, 0, 0, 0]) + io.erase_metadata() + # The root group's documents stay. + assert [key for key in sync(_keys(store)) if key.startswith("a/")] == [] + + +def test_store_array_subset_refuses_data_that_does_not_fit() -> None: + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + with pytest.raises(ValueError, match="does not fit"): + io[0:2] = [5, 6, 7] + + +def test_store_chunk_refuses_data_beyond_an_edge_chunk() -> None: + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(5,), chunks=(2,), dtype="int64")) + with pytest.raises(ValueError, match="does not fit"): + io.store_chunk([2], [1, 2]) + + +def test_store_array_subset_refuses_a_lossy_cast() -> None: + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(3,), chunks=(3,), dtype="uint8")) + with pytest.raises(TypeError, match="without losing values"): + io[:] = np.array([1.7, 300.0, -1.0]) + + +def test_store_array_subset_refuses_an_out_of_range_number() -> None: + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(3,), chunks=(3,), dtype="uint8")) + with pytest.raises(OverflowError): + io[:] = [1, 300, 2] + + +def test_chunk_indices_must_be_non_negative() -> None: + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + with pytest.raises(ValueError, match="non-negative"): + io.erase_chunk([-1]) + + +def test_chunk_indices_need_one_index_for_each_dimension() -> None: + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + with pytest.raises(ValueError, match="one index for each"): + io.erase_chunk([]) + + +def test_chunk_reads_need_indices_inside_the_chunk_grid() -> None: + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + with pytest.raises(IndexError, match="outside the chunk grid"): + io.retrieve_chunk([2]) + + def test_array_io_is_made_only_by_its_constructors() -> None: with pytest.raises(TypeError, match="AsyncArrayIO.open"): AsyncArrayIO() @@ -208,6 +290,18 @@ def test_async_array_clears_the_repair_mark_through_its_hook( assert keeps.metadata._stored_document is not None +async def _keys(store: MemoryStore) -> list[str]: + return [key async for key in store.list()] + + +def _stored_chunks(path: Path, zarr_format: Literal[2, 3]) -> Any: + if zarr_format == 2: + return json.loads((path / ".zarray").read_text())["chunks"] + return json.loads((path / "zarr.json").read_text())["chunk_grid"]["configuration"][ + "chunk_shape" + ] + + def _legacy_array(path: Path, zarr_format: Literal[2, 3]) -> None: """Store an array of shape (3,) whose stored chunk shape is `[0]`.""" zarr.create_array(store=path, shape=(3,), chunks=(3,), dtype="int16", zarr_format=zarr_format) From 6bb24a3d3c3ae55e0ac2c537abd2d11bbab51a23 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 19:42:17 +0100 Subject: [PATCH 11/31] fix(array): refuse only writes that do not fit, and take metadata as a plain dict The casting check refused lossless writes (an int64 array into uint8, ints into bool) and let lossy ones through (narrowing within a kind), and it read a structured record as an extra dimension. Writes through ArrayIO now refuse only data that does not broadcast to the region, which would drop values, reading a sequence as the array's data type first; values cast as NumPy casts them, as they do through Array. Chunk indices refuse booleans. from_metadata accepts the plain dict that the metadata property returns. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 64 ++++++++++++++++-------------------------- tests/test_array_io.py | 62 +++++++++++++++++++++++++++++++++++++--- 2 files changed, 82 insertions(+), 44 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 4650b1b65f..6045426d58 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -1953,39 +1953,18 @@ def _snapshot(metadata: ArrayMetadata) -> ArrayMetadata: not read from the global configuration.""" -def _checked_data(data: npt.ArrayLike, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: - """`data` to write to a region of `shape` of an array of `dtype`, refused if writing - it would lose values: if it does not broadcast to `shape` (extra values would be - dropped), or, for numeric data, if its values do not cast to `dtype` without - changing kind (a float into an integer, a signed integer array into an unsigned one). - Python numbers are cast by their values, as NumPy casts them: one out of range - raises.""" - numeric = "biufc" - if hasattr(data, "dtype") and hasattr(data, "shape"): - if ( - data.dtype.kind in numeric - and dtype.kind in numeric - and not np.can_cast(data.dtype, dtype, casting="same_kind") - ): - raise TypeError( - f"Cannot write data of dtype {data.dtype} to an array of dtype {dtype} " - "without losing values; cast it first." - ) +def _fitted_data(data: npt.ArrayLike, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: + """`data` to write to a region of `shape` of an array of `dtype`, refused with + `ValueError` if it does not broadcast to `shape`: writing it would drop values. A + sequence is read as an array of `dtype` first (as the write reads it), so a tuple is + one record of a structured data type; values are cast as NumPy casts them.""" + if hasattr(data, "shape"): data_shape = tuple(data.shape) + elif np.isscalar(data): + data_shape = () else: - natural = np.asarray(data) - if natural.dtype.kind in "iu" and dtype.kind in "iu": - data = np.asarray(data, dtype=dtype) - elif ( - natural.dtype.kind in numeric - and dtype.kind in numeric - and not np.can_cast(natural.dtype, dtype, casting="same_kind") - ): - raise TypeError( - f"Cannot write values of dtype {natural.dtype} to an array of dtype {dtype} " - "without losing values; cast them first." - ) - data_shape = natural.shape + data = np.asarray(data, dtype=dtype) + data_shape = data.shape try: broadcast = np.broadcast_shapes(data_shape, shape) except ValueError: @@ -2085,7 +2064,7 @@ async def open( @classmethod def from_metadata( cls, - metadata: ArrayMetadata | ArrayMetadataDict, + metadata: ArrayMetadata | Mapping[str, JSON], store: Store, path: str = "", ) -> AsyncArrayIO: @@ -2094,8 +2073,12 @@ def from_metadata( Nothing is stored and nothing is checked against the store: call `store_metadata` to store the metadata, and do so before storing chunks unless the store already holds it.""" - metadata = copy.deepcopy(metadata) if isinstance(metadata, dict) else _snapshot(metadata) - return cls._bound(metadata, StorePath(store, path)) + bound: ArrayMetadata | ArrayMetadataDict = ( + _snapshot(metadata) + if isinstance(metadata, ArrayV2Metadata | ArrayV3Metadata) + else cast("ArrayMetadataDict", copy.deepcopy(dict(metadata))) + ) + return cls._bound(bound, StorePath(store, path)) @classmethod def of(cls, array: AsyncArray[Any] | Array[Any]) -> AsyncArrayIO: @@ -2236,6 +2219,8 @@ async def erase_metadata(self) -> None: def _chunk_indices(self, chunk_indices: Sequence[int], *, in_grid: bool) -> tuple[int, ...]: """`chunk_indices` as a tuple of non-negative ints, one for each dimension; with `in_grid`, within the chunk grid.""" + if any(isinstance(index, bool | np.bool_) for index in chunk_indices): + raise TypeError(f"Chunk indices must be integers, not booleans: {chunk_indices}.") indices = tuple(operator.index(index) for index in chunk_indices) if len(indices) != self.ndim: raise ValueError( @@ -2293,13 +2278,12 @@ async def store_array_subset( """Write `data` at `selection`, by NumPy basic indexing. Raises `ValueError` if `data` does not broadcast to the selected region, and - `TypeError` if its values would not survive the cast to the array's data type - (see the class documentation). Raises `MetadataRepairRequiredError` while - `needs_repair` is true. Nothing is written when it raises.""" + `MetadataRepairRequiredError` while `needs_repair` is true; nothing is written + when it raises. Values are cast to the array's data type as NumPy casts them.""" indexer = BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) await self._set_selection( indexer, - _checked_data(data, self.dtype, indexer.shape), + _fitted_data(data, self.dtype, indexer.shape), prototype=default_buffer_prototype() if prototype is None else prototype, ) @@ -2335,7 +2319,7 @@ async def store_chunk( ) await self._set_selection( indexer, - _checked_data(data, self.dtype, indexer.shape), + _fitted_data(data, self.dtype, indexer.shape), prototype=default_buffer_prototype() if prototype is None else prototype, ) @@ -2507,7 +2491,7 @@ def open( @classmethod def from_metadata( cls, - metadata: ArrayMetadata | ArrayMetadataDict, + metadata: ArrayMetadata | Mapping[str, JSON], store: Store, path: str = "", *, diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 8e638415da..941f44b1d7 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -177,6 +177,35 @@ def test_erase_deletes_chunks_and_metadata(zarr_format: Literal[2, 3], separator assert [key for key in sync(_keys(store)) if key.startswith("a/")] == [] +def test_a_value_keeps_attributes_changed_where_it_came_from() -> None: + """Nested attribute values changed through the array a value was taken from, or in + the document a value was made from, do not reach the value.""" + store = MemoryStore() + array = zarr.create_array(store, name="a", shape=(2,), dtype="int8", attributes={"n": [1]}) + document = array.metadata.to_dict() + taken = ArrayIO.of(array) + made = ArrayIO.from_metadata(document, store, "a") + + cast("list[int]", array.attrs["n"]).append(2) + cast("list[int]", cast("dict[str, Any]", document["attributes"])["n"]).append(3) + + assert (taken.attrs, made.attrs) == ({"n": [1]}, {"n": [1]}) + + +def test_values_not_taken_from_an_array_ignore_the_global_configuration() -> None: + """`open` and `from_metadata` use fixed defaults, not the global configuration: an + all-fill-value chunk is not stored, whatever `array.write_empty_chunks` says.""" + store = MemoryStore() + array = zarr.create_array(store, name="a", shape=(4,), chunks=(2,), dtype="int8") + with zarr.config.set({"array.write_empty_chunks": True}): + opened = ArrayIO.open(store, "a") + made = ArrayIO.from_metadata(array.metadata, store, "a") + opened[0:2] = [0, 0] + made[2:4] = [0, 0] + + assert [key for key in sync(_keys(store)) if key.startswith("a/c")] == [] + + def test_store_array_subset_refuses_data_that_does_not_fit() -> None: io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(ValueError, match="does not fit"): @@ -189,10 +218,29 @@ def test_store_chunk_refuses_data_beyond_an_edge_chunk() -> None: io.store_chunk([2], [1, 2]) -def test_store_array_subset_refuses_a_lossy_cast() -> None: - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(3,), chunks=(3,), dtype="uint8")) - with pytest.raises(TypeError, match="without losing values"): - io[:] = np.array([1.7, 300.0, -1.0]) +@pytest.mark.parametrize( + ("dtype", "selection", "data"), + [ + ([("x", "i4"), ("y", "f8")], slice(None), [(1, 2.0), (3, 4.0), (5, 6.0), (7, 8.0)]), + ([("x", "i4"), ("y", "f8")], 0, (1, 2.0)), + ([("x", "i4"), ("y", "f8")], slice(None), (1, 2.0)), + ("uint8", slice(None), np.arange(4)), + ("bool", slice(0, 2), [0, 1]), + ("float32", 1, 1.5), + (" None: + """`store_array_subset` writes every value `Array` writes for the same selection, + structured records included, and stores the same result.""" + io_store, array_store = MemoryStore(), MemoryStore() + io = ArrayIO.of(zarr.create_array(io_store, shape=(4,), chunks=(2,), dtype=dtype)) + array = zarr.create_array(array_store, shape=(4,), chunks=(2,), dtype=dtype) + + io[selection] = data + array[selection] = data + + np.testing.assert_array_equal(io[:], array[:]) def test_store_array_subset_refuses_an_out_of_range_number() -> None: @@ -213,6 +261,12 @@ def test_chunk_indices_need_one_index_for_each_dimension() -> None: io.erase_chunk([]) +def test_chunk_indices_are_not_booleans() -> None: + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + with pytest.raises(TypeError, match="not booleans"): + io.retrieve_chunk([True]) + + def test_chunk_reads_need_indices_inside_the_chunk_grid() -> None: io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(IndexError, match="outside the chunk grid"): From 0ad8b6ef8a587408dfa853c5f0989dc11068c1b2 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 19:51:52 +0100 Subject: [PATCH 12/31] fix(array): accept leading length-1 axes and read chunk indices once Writes through ArrayIO drop leading axes of length 1 beyond the region's, as NumPy assignment does. Chunk indices are read once, so an iterator works. A test covers from_metadata with a read-only mapping. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 15 +++++++++++---- tests/test_array_io.py | 11 ++++++++++- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 6045426d58..fea542cc62 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -1957,7 +1957,8 @@ def _fitted_data(data: npt.ArrayLike, dtype: TBaseDType, shape: tuple[int, ...]) """`data` to write to a region of `shape` of an array of `dtype`, refused with `ValueError` if it does not broadcast to `shape`: writing it would drop values. A sequence is read as an array of `dtype` first (as the write reads it), so a tuple is - one record of a structured data type; values are cast as NumPy casts them.""" + one record of a structured data type; values are cast as NumPy casts them. Leading + axes of length 1 beyond `shape`'s are dropped, as NumPy assignment drops them.""" if hasattr(data, "shape"): data_shape = tuple(data.shape) elif np.isscalar(data): @@ -1965,6 +1966,11 @@ def _fitted_data(data: npt.ArrayLike, dtype: TBaseDType, shape: tuple[int, ...]) else: data = np.asarray(data, dtype=dtype) data_shape = data.shape + extra = len(data_shape) - len(shape) + if extra > 0 and all(length == 1 for length in data_shape[:extra]): + data_shape = data_shape[extra:] + # Arrays of every kind accepted here (NumPy, GPU, buffers) have `reshape`. + data = cast("Any", data).reshape(data_shape) try: broadcast = np.broadcast_shapes(data_shape, shape) except ValueError: @@ -2219,9 +2225,10 @@ async def erase_metadata(self) -> None: def _chunk_indices(self, chunk_indices: Sequence[int], *, in_grid: bool) -> tuple[int, ...]: """`chunk_indices` as a tuple of non-negative ints, one for each dimension; with `in_grid`, within the chunk grid.""" - if any(isinstance(index, bool | np.bool_) for index in chunk_indices): - raise TypeError(f"Chunk indices must be integers, not booleans: {chunk_indices}.") - indices = tuple(operator.index(index) for index in chunk_indices) + given = tuple(chunk_indices) + if any(isinstance(index, bool | np.bool_) for index in given): + raise TypeError(f"Chunk indices must be integers, not booleans: {given}.") + indices = tuple(operator.index(index) for index in given) if len(indices) != self.ndim: raise ValueError( f"Chunk indices {indices} do not have one index for each of the array's " diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 941f44b1d7..0ac737d91f 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -4,6 +4,7 @@ import asyncio import json +from types import MappingProxyType from typing import TYPE_CHECKING, Any, Literal, cast import numpy as np @@ -184,7 +185,7 @@ def test_a_value_keeps_attributes_changed_where_it_came_from() -> None: array = zarr.create_array(store, name="a", shape=(2,), dtype="int8", attributes={"n": [1]}) document = array.metadata.to_dict() taken = ArrayIO.of(array) - made = ArrayIO.from_metadata(document, store, "a") + made = ArrayIO.from_metadata(MappingProxyType(document), store, "a") cast("list[int]", array.attrs["n"]).append(2) cast("list[int]", cast("dict[str, Any]", document["attributes"])["n"]).append(3) @@ -206,6 +207,14 @@ def test_values_not_taken_from_an_array_ignore_the_global_configuration() -> Non assert [key for key in sync(_keys(store)) if key.startswith("a/c")] == [] +def test_store_array_subset_drops_leading_axes_of_length_one() -> None: + """Data with leading axes of length 1 beyond the region's writes as NumPy assignment + writes it, across chunks.""" + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + io[:] = np.arange(1, 5)[None] + np.testing.assert_array_equal(io[:], [1, 2, 3, 4]) + + def test_store_array_subset_refuses_data_that_does_not_fit() -> None: io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(ValueError, match="does not fit"): From 968d103bbbe835d9b8f8480a59c11079323331b0 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 19:59:42 +0100 Subject: [PATCH 13/31] fix(array): broadcast data to the region once before an ArrayIO write _fitted_data now returns the data broadcast to the selected region, so data that broadcasts writes as NumPy assignment writes it whatever chunks the region spans (it failed across chunks before, as it still does through Array). Inputs without reshape, such as a memoryview, are read as arrays first, and a refusal names the shape the caller passed. Chunk indices accept any iterable of ints. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 61 ++++++++++++++++++++++-------------------- tests/test_array_io.py | 34 +++++++++++++++++------ 2 files changed, 58 insertions(+), 37 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index fea542cc62..2d14ca3869 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -1954,30 +1954,33 @@ def _snapshot(metadata: ArrayMetadata) -> ArrayMetadata: def _fitted_data(data: npt.ArrayLike, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: - """`data` to write to a region of `shape` of an array of `dtype`, refused with - `ValueError` if it does not broadcast to `shape`: writing it would drop values. A - sequence is read as an array of `dtype` first (as the write reads it), so a tuple is - one record of a structured data type; values are cast as NumPy casts them. Leading - axes of length 1 beyond `shape`'s are dropped, as NumPy assignment drops them.""" - if hasattr(data, "shape"): - data_shape = tuple(data.shape) - elif np.isscalar(data): - data_shape = () - else: - data = np.asarray(data, dtype=dtype) - data_shape = data.shape - extra = len(data_shape) - len(shape) - if extra > 0 and all(length == 1 for length in data_shape[:extra]): - data_shape = data_shape[extra:] - # Arrays of every kind accepted here (NumPy, GPU, buffers) have `reshape`. - data = cast("Any", data).reshape(data_shape) + """`data` broadcast to a region of `shape` of an array of `dtype`, refused with + `ValueError` if it does not broadcast there: writing it would drop values. + + Data that is not an array (a list, a tuple, a memoryview) is read as an array of + `dtype` first, as the write reads it, so a tuple is one record of a structured data + type. Leading axes of length 1 beyond the region's are dropped. Values are cast as + NumPy casts them. Broadcasting here, once, lets the write split the data by chunk + whatever its shape.""" + if np.isscalar(data): + return data + array = ( + data + if hasattr(data, "shape") and hasattr(data, "reshape") + else np.asarray(data, dtype=dtype) + ) + given = tuple(array.shape) + trimmed = given + while len(trimmed) > len(shape) and trimmed[0] == 1: + trimmed = trimmed[1:] try: - broadcast = np.broadcast_shapes(data_shape, shape) + broadcast = np.broadcast_shapes(trimmed, shape) except ValueError: broadcast = None if broadcast != shape: - raise ValueError(f"Data of shape {data_shape} does not fit a region of shape {shape}.") - return data + raise ValueError(f"Data of shape {given} does not fit a region of shape {shape}.") + # A read-only view; the write only reads it. + return np.broadcast_to(array.reshape(trimmed), shape) @final @@ -2222,7 +2225,7 @@ async def erase_metadata(self) -> None: keys = ARRAY_DOCUMENTS[self._metadata.zarr_format] await gather(*((self._store_path / key).delete() for key in keys)) - def _chunk_indices(self, chunk_indices: Sequence[int], *, in_grid: bool) -> tuple[int, ...]: + def _chunk_indices(self, chunk_indices: Iterable[int], *, in_grid: bool) -> tuple[int, ...]: """`chunk_indices` as a tuple of non-negative ints, one for each dimension; with `in_grid`, within the chunk grid.""" given = tuple(chunk_indices) @@ -2243,14 +2246,14 @@ def _chunk_indices(self, chunk_indices: Sequence[int], *, in_grid: bool) -> tupl raise IndexError(f"Chunk indices {indices} are outside the chunk grid {grid_shape}.") return indices - async def erase_chunk(self, chunk_indices: Sequence[int], /) -> None: + async def erase_chunk(self, chunk_indices: Iterable[int], /) -> None: """Delete the chunk at `chunk_indices` from the store; it then reads as the fill value. Succeeds if there is none. Indices outside the chunk grid are allowed, to reclaim chunks left outside a smaller shape.""" indices = self._chunk_indices(chunk_indices, in_grid=False) await (self._store_path / self._metadata.encode_chunk_key(indices)).delete() - async def erase_chunks(self, chunk_indices: Iterable[Sequence[int]], /) -> None: + async def erase_chunks(self, chunk_indices: Iterable[Iterable[int]], /) -> None: """Delete the chunk at each of `chunk_indices`, as `erase_chunk` does.""" keys = [ ( @@ -2295,7 +2298,7 @@ async def store_array_subset( ) async def retrieve_chunk( - self, chunk_indices: Sequence[int], /, *, prototype: BufferPrototype | None = None + self, chunk_indices: Iterable[int], /, *, prototype: BufferPrototype | None = None ) -> NDArrayLikeOrScalar: """The decoded values of the chunk at `chunk_indices`, within the array: a chunk at the array's edge gives only the part inside the array's shape.""" @@ -2310,7 +2313,7 @@ async def retrieve_chunk( async def store_chunk( self, - chunk_indices: Sequence[int], + chunk_indices: Iterable[int], data: npt.ArrayLike, /, *, @@ -2580,11 +2583,11 @@ def erase_metadata(self) -> None: """See `AsyncArrayIO.erase_metadata`.""" self._run(self._async_io.erase_metadata()) - def erase_chunk(self, chunk_indices: Sequence[int], /) -> None: + def erase_chunk(self, chunk_indices: Iterable[int], /) -> None: """See `AsyncArrayIO.erase_chunk`.""" self._run(self._async_io.erase_chunk(chunk_indices)) - def erase_chunks(self, chunk_indices: Iterable[Sequence[int]], /) -> None: + def erase_chunks(self, chunk_indices: Iterable[Iterable[int]], /) -> None: """See `AsyncArrayIO.erase_chunks`.""" self._run(self._async_io.erase_chunks(chunk_indices)) @@ -2606,14 +2609,14 @@ def store_array_subset( self._run(self._async_io.store_array_subset(selection, data, prototype=prototype)) def retrieve_chunk( - self, chunk_indices: Sequence[int], /, *, prototype: BufferPrototype | None = None + self, chunk_indices: Iterable[int], /, *, prototype: BufferPrototype | None = None ) -> NDArrayLikeOrScalar: """See `AsyncArrayIO.retrieve_chunk`.""" return self._run(self._async_io.retrieve_chunk(chunk_indices, prototype=prototype)) def store_chunk( self, - chunk_indices: Sequence[int], + chunk_indices: Iterable[int], data: npt.ArrayLike, /, *, diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 0ac737d91f..573378ae6d 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -207,18 +207,30 @@ def test_values_not_taken_from_an_array_ignore_the_global_configuration() -> Non assert [key for key in sync(_keys(store)) if key.startswith("a/c")] == [] -def test_store_array_subset_drops_leading_axes_of_length_one() -> None: - """Data with leading axes of length 1 beyond the region's writes as NumPy assignment - writes it, across chunks.""" - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) - io[:] = np.arange(1, 5)[None] - np.testing.assert_array_equal(io[:], [1, 2, 3, 4]) +@pytest.mark.parametrize( + ("shape", "chunks", "selection", "data", "expected"), + [ + ((4,), (2,), slice(None), np.arange(1, 5)[None, None], [1, 2, 3, 4]), + ((4,), (2,), slice(None), np.array([7]), [7, 7, 7, 7]), + ((2, 4), (1, 2), slice(None), np.arange(4)[None], [[0, 1, 2, 3], [0, 1, 2, 3]]), + ((2, 4), (1, 2), slice(None), np.array([[1], [2]]), [[1, 1, 1, 1], [2, 2, 2, 2]]), + ((4,), (2,), slice(None), memoryview(np.arange(4)), [0, 1, 2, 3]), + ], +) +def test_store_array_subset_broadcasts_across_chunks( + shape: tuple[int, ...], chunks: tuple[int, ...], selection: Any, data: Any, expected: Any +) -> None: + """Data that broadcasts to the selected region writes as NumPy assignment writes it, + leading axes of length 1 dropped, whatever chunks the region spans.""" + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=shape, chunks=chunks, dtype="int64")) + io[selection] = data + np.testing.assert_array_equal(io[:], expected) def test_store_array_subset_refuses_data_that_does_not_fit() -> None: io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) - with pytest.raises(ValueError, match="does not fit"): - io[0:2] = [5, 6, 7] + with pytest.raises(ValueError, match=r"shape \(1, 3\) does not fit"): + io[0:2] = [[5, 6, 7]] def test_store_chunk_refuses_data_beyond_an_edge_chunk() -> None: @@ -276,6 +288,12 @@ def test_chunk_indices_are_not_booleans() -> None: io.retrieve_chunk([True]) +def test_chunk_indices_may_be_any_iterable() -> None: + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + io.store_chunk((index for index in (1,)), [7, 8]) + np.testing.assert_array_equal(io.retrieve_chunk(iter([1])), [7, 8]) + + def test_chunk_reads_need_indices_inside_the_chunk_grid() -> None: io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(IndexError, match="outside the chunk grid"): From 31cacfa3e742b2ef68cdc8e5f25de76bb5291f6e Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 20:13:58 +0100 Subject: [PATCH 14/31] fix(array): only check that ArrayIO write data fits, leaving casts to the write Broadcasting the data to the region before the write cast the whole region at once (a 0-d float64 into a large float32 array allocated it all), lost sharding's scalar fast path, and let a memoryview skip the check, since NumPy counts memoryview as a scalar. _fitted_data now only checks: data with a shape keeps it, a sequence is read as the array's data type, leading length-1 axes are dropped, and data that does not broadcast is refused. The write then casts and splits the data as it does for Array. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 34 ++++++++++++++++++---------------- tests/test_array_io.py | 31 +++++++++++++++---------------- 2 files changed, 33 insertions(+), 32 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 2d14ca3869..3a3a94fff3 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -1954,22 +1954,20 @@ def _snapshot(metadata: ArrayMetadata) -> ArrayMetadata: def _fitted_data(data: npt.ArrayLike, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: - """`data` broadcast to a region of `shape` of an array of `dtype`, refused with + """`data` to write to a region of `shape` of an array of `dtype`, refused with `ValueError` if it does not broadcast there: writing it would drop values. - Data that is not an array (a list, a tuple, a memoryview) is read as an array of - `dtype` first, as the write reads it, so a tuple is one record of a structured data - type. Leading axes of length 1 beyond the region's are dropped. Values are cast as - NumPy casts them. Broadcasting here, once, lets the write split the data by chunk - whatever its shape.""" - if np.isscalar(data): - return data - array = ( - data - if hasattr(data, "shape") and hasattr(data, "reshape") - else np.asarray(data, dtype=dtype) - ) - given = tuple(array.shape) + It only checks; the write casts and splits the data as it does for `Array`. A + sequence (a list, a tuple) is read as an array of `dtype` first, as the write reads + it, so a tuple is one record of a structured data type. Leading axes of length 1 + beyond the region's are dropped, as NumPy assignment drops them.""" + if hasattr(data, "shape"): + given = tuple(data.shape) + elif np.isscalar(data): + given = () + else: + data = np.asarray(data, dtype=dtype) + given = tuple(data.shape) trimmed = given while len(trimmed) > len(shape) and trimmed[0] == 1: trimmed = trimmed[1:] @@ -1979,8 +1977,12 @@ def _fitted_data(data: npt.ArrayLike, dtype: TBaseDType, shape: tuple[int, ...]) broadcast = None if broadcast != shape: raise ValueError(f"Data of shape {given} does not fit a region of shape {shape}.") - # A read-only view; the write only reads it. - return np.broadcast_to(array.reshape(trimmed), shape) + if trimmed != given: + # A view with the same values; inputs without `reshape` (a memoryview) are + # read as arrays, without a copy. + reshapable = data if hasattr(data, "reshape") else np.asarray(data) + data = cast("Any", reshapable).reshape(trimmed) + return data @final diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 573378ae6d..61a081da0e 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -208,23 +208,16 @@ def test_values_not_taken_from_an_array_ignore_the_global_configuration() -> Non @pytest.mark.parametrize( - ("shape", "chunks", "selection", "data", "expected"), - [ - ((4,), (2,), slice(None), np.arange(1, 5)[None, None], [1, 2, 3, 4]), - ((4,), (2,), slice(None), np.array([7]), [7, 7, 7, 7]), - ((2, 4), (1, 2), slice(None), np.arange(4)[None], [[0, 1, 2, 3], [0, 1, 2, 3]]), - ((2, 4), (1, 2), slice(None), np.array([[1], [2]]), [[1, 1, 1, 1], [2, 2, 2, 2]]), - ((4,), (2,), slice(None), memoryview(np.arange(4)), [0, 1, 2, 3]), - ], + "data", + [np.arange(1, 5)[None, None], [[[1, 2, 3, 4]]], memoryview(np.arange(1, 5))], + ids=["array", "list", "memoryview"], ) -def test_store_array_subset_broadcasts_across_chunks( - shape: tuple[int, ...], chunks: tuple[int, ...], selection: Any, data: Any, expected: Any -) -> None: - """Data that broadcasts to the selected region writes as NumPy assignment writes it, - leading axes of length 1 dropped, whatever chunks the region spans.""" - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=shape, chunks=chunks, dtype="int64")) - io[selection] = data - np.testing.assert_array_equal(io[:], expected) +def test_store_array_subset_drops_leading_axes_of_length_one(data: Any) -> None: + """Data with leading axes of length 1 beyond the region's writes as NumPy assignment + writes it, across chunks.""" + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + io[:] = data + np.testing.assert_array_equal(io[:], [1, 2, 3, 4]) def test_store_array_subset_refuses_data_that_does_not_fit() -> None: @@ -233,6 +226,12 @@ def test_store_array_subset_refuses_data_that_does_not_fit() -> None: io[0:2] = [[5, 6, 7]] +def test_store_array_subset_refuses_a_memoryview_that_does_not_fit() -> None: + io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + with pytest.raises(ValueError, match=r"shape \(3,\) does not fit"): + io[0:2] = memoryview(np.arange(3)) + + def test_store_chunk_refuses_data_beyond_an_edge_chunk() -> None: io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(5,), chunks=(2,), dtype="int64")) with pytest.raises(ValueError, match="does not fit"): From 1a69bf5c5436a84299e89d0a15365fc169abbbdb Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 20:20:10 +0100 Subject: [PATCH 15/31] test(array): cover ArrayIO's memoryview trimming and unbroadcast scalars Also rewrite the changelog fragment for #470 to describe the current API. Assisted-by: ClaudeCode:claude-opus-5-5 --- changes/470.misc.md | 2 +- tests/test_array_io.py | 11 +++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/changes/470.misc.md b/changes/470.misc.md index 210df0b3ae..44f8c1a036 100644 --- a/changes/470.misc.md +++ b/changes/470.misc.md @@ -1 +1 @@ -Arrays now read and write through `AsyncArrayIO`, which `AsyncArray` builds from its fields for each operation, with a synchronous `ArrayIO` built on it. `Array` and `AsyncArray` behave as before. +Add `AsyncArrayIO` and `ArrayIO`, which read and write an array as a value: `open`, `from_metadata` and `of` make one, `with_shape` and `with_attrs` return changed values without storing them, and `store_metadata` stores them. `AsyncArray` reads and writes through the same routines; `Array` and `AsyncArray` behave as before. diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 61a081da0e..621a2ea624 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -11,7 +11,7 @@ import pytest import zarr -from zarr.core.array import ArrayIO, AsyncArray, AsyncArrayIO +from zarr.core.array import ArrayIO, AsyncArray, AsyncArrayIO, _fitted_data from zarr.core.sync import SyncContext, sync from zarr.errors import MetadataRepairRequiredError, ZarrUserWarning from zarr.storage import LocalStore, MemoryStore, StorePath @@ -209,7 +209,7 @@ def test_values_not_taken_from_an_array_ignore_the_global_configuration() -> Non @pytest.mark.parametrize( "data", - [np.arange(1, 5)[None, None], [[[1, 2, 3, 4]]], memoryview(np.arange(1, 5))], + [np.arange(1, 5)[None, None], [[[1, 2, 3, 4]]], memoryview(np.arange(1, 5)[None, None])], ids=["array", "list", "memoryview"], ) def test_store_array_subset_drops_leading_axes_of_length_one(data: Any) -> None: @@ -220,6 +220,13 @@ def test_store_array_subset_drops_leading_axes_of_length_one(data: Any) -> None: np.testing.assert_array_equal(io[:], [1, 2, 3, 4]) +def test_write_data_is_checked_not_broadcast() -> None: + """A 0-d input is handed to the write as it is, not broadcast or cast over the + region: the write casts it once, and sharding keeps its fast path for scalars.""" + data = np.array(2.0) + assert _fitted_data(data, np.dtype("int64"), (10**12,)) is data + + def test_store_array_subset_refuses_data_that_does_not_fit() -> None: io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(ValueError, match=r"shape \(1, 3\) does not fit"): From 48608f06c5a97944ed9fd6e03d61e662c23e9455 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 20:20:59 +0100 Subject: [PATCH 16/31] docs: file the changelog fragment for #470 as a feature Assisted-by: ClaudeCode:claude-opus-5-5 --- changes/{470.misc.md => 470.feature.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changes/{470.misc.md => 470.feature.md} (100%) diff --git a/changes/470.misc.md b/changes/470.feature.md similarity index 100% rename from changes/470.misc.md rename to changes/470.feature.md From 19d95e8653a4e6480304e0551ea6576668469ce5 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 21:41:03 +0100 Subject: [PATCH 17/31] feat(array): choose ArrayIO's runtime settings per call Reads take read_missing_chunks (a missing chunk reads as the fill value, or raises ChunkNotFoundError for data known to be complete read over a connection that can fail) and writes take store_empty_chunks. Neither comes from the value or from the array it was taken from, and data reads in C order, except that a Zarr format 2 array keeps the order its metadata declares. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 119 +++++++++++++++++++++++++++++++++-------- tests/test_array_io.py | 29 +++++++++- 2 files changed, 125 insertions(+), 23 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 3a3a94fff3..fa28a5df0f 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -1949,8 +1949,18 @@ def _snapshot(metadata: ArrayMetadata) -> ArrayMetadata: _ARRAY_IO_CONFIG: Final = ArrayConfig(order="C", write_empty_chunks=False) -"""The runtime configuration of an `AsyncArrayIO` that is not made from an array: fixed, -not read from the global configuration.""" +"""The runtime configuration `AsyncArrayIO`'s public reads and writes start from: fixed, +not read from the global configuration. Each operation sets its own choices on it.""" + + +def _read_config(read_missing_chunks: bool) -> ArrayConfig: + """The configuration of one public read.""" + return replace(_ARRAY_IO_CONFIG, read_missing_chunks=read_missing_chunks) + + +def _write_config(store_empty_chunks: bool) -> ArrayConfig: + """The configuration of one public write.""" + return replace(_ARRAY_IO_CONFIG, write_empty_chunks=store_empty_chunks) def _fitted_data(data: npt.ArrayLike, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: @@ -2005,6 +2015,10 @@ class AsyncArrayIO: repaired metadata and `needs_repair` is true; storing chunks raises `MetadataRepairRequiredError` until `store_metadata` has stored the repaired metadata. + + Runtime choices belong to the operation, not the value: a read takes + `read_missing_chunks`, a write takes `store_empty_chunks`. Data is returned in C + order, except that a Zarr format 2 array keeps the order its metadata declares. """ _metadata: ArrayMetadata @@ -2271,12 +2285,23 @@ async def erase_chunks(self, chunk_indices: Iterable[Iterable[int]], /) -> None: await concurrent_foreach(iter(keys), _delete_chunk, min(limit, len(keys))) async def retrieve_array_subset( - self, selection: BasicSelection, /, *, prototype: BufferPrototype | None = None + self, + selection: BasicSelection, + /, + *, + read_missing_chunks: bool = True, + prototype: BufferPrototype | None = None, ) -> NDArrayLikeOrScalar: - """The values at `selection`, by NumPy basic indexing.""" + """The values at `selection`, by NumPy basic indexing. + + A chunk missing from the store reads as the fill value; with + `read_missing_chunks=False`, it raises `ChunkNotFoundError` instead, for data + known to be complete that is read over a connection that can fail.""" indexer = BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) return await self._get_selection( - indexer, prototype=default_buffer_prototype() if prototype is None else prototype + indexer, + prototype=default_buffer_prototype() if prototype is None else prototype, + config=_read_config(read_missing_chunks), ) async def store_array_subset( @@ -2285,32 +2310,44 @@ async def store_array_subset( data: npt.ArrayLike, /, *, + store_empty_chunks: bool = False, prototype: BufferPrototype | None = None, ) -> None: """Write `data` at `selection`, by NumPy basic indexing. - Raises `ValueError` if `data` does not broadcast to the selected region, and - `MetadataRepairRequiredError` while `needs_repair` is true; nothing is written - when it raises. Values are cast to the array's data type as NumPy casts them.""" + A chunk left holding only the fill value is deleted from the store, unless + `store_empty_chunks`. Raises `ValueError` if `data` does not broadcast to the + selected region, and `MetadataRepairRequiredError` while `needs_repair` is true; + nothing is written when it raises. Values are cast to the array's data type as + NumPy casts them.""" indexer = BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) await self._set_selection( indexer, _fitted_data(data, self.dtype, indexer.shape), prototype=default_buffer_prototype() if prototype is None else prototype, + config=_write_config(store_empty_chunks), ) async def retrieve_chunk( - self, chunk_indices: Iterable[int], /, *, prototype: BufferPrototype | None = None + self, + chunk_indices: Iterable[int], + /, + *, + read_missing_chunks: bool = True, + prototype: BufferPrototype | None = None, ) -> NDArrayLikeOrScalar: """The decoded values of the chunk at `chunk_indices`, within the array: a chunk - at the array's edge gives only the part inside the array's shape.""" + at the array's edge gives only the part inside the array's shape. A missing + chunk is handled as `retrieve_array_subset` handles it.""" indexer = BlockIndexer( self._chunk_indices(chunk_indices, in_grid=True), self._metadata.shape, self._chunk_grid, ) return await self._get_selection( - indexer, prototype=default_buffer_prototype() if prototype is None else prototype + indexer, + prototype=default_buffer_prototype() if prototype is None else prototype, + config=_read_config(read_missing_chunks), ) async def store_chunk( @@ -2319,11 +2356,13 @@ async def store_chunk( data: npt.ArrayLike, /, *, + store_empty_chunks: bool = False, prototype: BufferPrototype | None = None, ) -> None: """Encode `data` as the chunk at `chunk_indices` and write it. For a chunk at the array's edge, `data` covers only the part inside the array's shape, as - `retrieve_chunk` gives it. Raises as `store_array_subset` does.""" + `retrieve_chunk` gives it. `store_empty_chunks` and errors are as for + `store_array_subset`.""" indexer = BlockIndexer( self._chunk_indices(chunk_indices, in_grid=True), self._metadata.shape, @@ -2333,6 +2372,7 @@ async def store_chunk( indexer, _fitted_data(data, self.dtype, indexer.shape), prototype=default_buffer_prototype() if prototype is None else prototype, + config=_write_config(store_empty_chunks), ) async def __getitem__(self, selection: BasicSelection, /) -> NDArrayLikeOrScalar: @@ -2346,12 +2386,14 @@ async def _get_selection( prototype: BufferPrototype, out: NDBuffer | None = None, fields: Fields | None = None, + config: ArrayConfig | None = None, ) -> NDArrayLikeOrScalar: + """Read through the codec pipeline, with `config` or, for `AsyncArray`, its own.""" return await _get_selection( self._store_path, self._metadata, self._codec_pipeline, - self._config, + self._config if config is None else config, self._chunk_grid, indexer, prototype=prototype, @@ -2366,6 +2408,7 @@ async def _set_selection( *, prototype: BufferPrototype, fields: Fields | None = None, + config: ArrayConfig | None = None, ) -> None: """`_write_selection`, refused while `needs_repair` is true.""" if product(indexer.shape) > 0 and self._needs_repair: @@ -2375,7 +2418,9 @@ async def _set_selection( "`store_metadata()` and write through the value it returns. Nothing was " "written." ) - await self._write_selection(indexer, value, prototype=prototype, fields=fields) + await self._write_selection( + indexer, value, prototype=prototype, fields=fields, config=config + ) async def _write_selection( self, @@ -2384,14 +2429,16 @@ async def _write_selection( *, prototype: BufferPrototype, fields: Fields | None = None, + config: ArrayConfig | None = None, ) -> None: """Write without the check against a repair that has not been stored, for a - caller that applies its own repair policy first (`AsyncArray`).""" + caller that applies its own repair policy first (`AsyncArray`), with `config` + or the value's own.""" await _set_selection( self._store_path, self._metadata, self._codec_pipeline, - self._config, + self._config if config is None else config, self._chunk_grid, indexer, value, @@ -2594,10 +2641,19 @@ def erase_chunks(self, chunk_indices: Iterable[Iterable[int]], /) -> None: self._run(self._async_io.erase_chunks(chunk_indices)) def retrieve_array_subset( - self, selection: BasicSelection, /, *, prototype: BufferPrototype | None = None + self, + selection: BasicSelection, + /, + *, + read_missing_chunks: bool = True, + prototype: BufferPrototype | None = None, ) -> NDArrayLikeOrScalar: """See `AsyncArrayIO.retrieve_array_subset`.""" - return self._run(self._async_io.retrieve_array_subset(selection, prototype=prototype)) + return self._run( + self._async_io.retrieve_array_subset( + selection, read_missing_chunks=read_missing_chunks, prototype=prototype + ) + ) def store_array_subset( self, @@ -2605,16 +2661,30 @@ def store_array_subset( data: npt.ArrayLike, /, *, + store_empty_chunks: bool = False, prototype: BufferPrototype | None = None, ) -> None: """See `AsyncArrayIO.store_array_subset`.""" - self._run(self._async_io.store_array_subset(selection, data, prototype=prototype)) + self._run( + self._async_io.store_array_subset( + selection, data, store_empty_chunks=store_empty_chunks, prototype=prototype + ) + ) def retrieve_chunk( - self, chunk_indices: Iterable[int], /, *, prototype: BufferPrototype | None = None + self, + chunk_indices: Iterable[int], + /, + *, + read_missing_chunks: bool = True, + prototype: BufferPrototype | None = None, ) -> NDArrayLikeOrScalar: """See `AsyncArrayIO.retrieve_chunk`.""" - return self._run(self._async_io.retrieve_chunk(chunk_indices, prototype=prototype)) + return self._run( + self._async_io.retrieve_chunk( + chunk_indices, read_missing_chunks=read_missing_chunks, prototype=prototype + ) + ) def store_chunk( self, @@ -2622,10 +2692,15 @@ def store_chunk( data: npt.ArrayLike, /, *, + store_empty_chunks: bool = False, prototype: BufferPrototype | None = None, ) -> None: """See `AsyncArrayIO.store_chunk`.""" - self._run(self._async_io.store_chunk(chunk_indices, data, prototype=prototype)) + self._run( + self._async_io.store_chunk( + chunk_indices, data, store_empty_chunks=store_empty_chunks, prototype=prototype + ) + ) def __getitem__(self, selection: BasicSelection, /) -> NDArrayLikeOrScalar: """`retrieve_array_subset(selection)`.""" diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 621a2ea624..dad89bb14a 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -13,7 +13,7 @@ import zarr from zarr.core.array import ArrayIO, AsyncArray, AsyncArrayIO, _fitted_data from zarr.core.sync import SyncContext, sync -from zarr.errors import MetadataRepairRequiredError, ZarrUserWarning +from zarr.errors import ChunkNotFoundError, MetadataRepairRequiredError, ZarrUserWarning from zarr.storage import LocalStore, MemoryStore, StorePath if TYPE_CHECKING: @@ -227,6 +227,33 @@ def test_write_data_is_checked_not_broadcast() -> None: assert _fitted_data(data, np.dtype("int64"), (10**12,)) is data +def test_runtime_choices_are_made_per_call() -> None: + """Whether an all-fill-value chunk is stored, and whether a missing chunk reads as + the fill value, are chosen by each call, whatever the array the value was taken + from was configured with; data reads in C order.""" + store = MemoryStore() + array = zarr.create_array( + store, + name="a", + shape=(2, 4), + chunks=(2, 2), + dtype="int8", + config={"write_empty_chunks": True, "read_missing_chunks": False, "order": "F"}, + ) + io = ArrayIO.of(array) + + io[:, 0:2] = 0 + io.store_array_subset((slice(None), slice(2, 4)), 0, store_empty_chunks=True) + + assert sorted(key for key in sync(_keys(store)) if key.startswith("a/c")) == ["a/c/0/1"] + assert cast("np.ndarray[Any, Any]", io[:]).flags.c_contiguous + io.erase_chunk([0, 1]) + with pytest.raises(ChunkNotFoundError): + io.retrieve_array_subset(slice(None), read_missing_chunks=False) + with pytest.raises(ChunkNotFoundError): + io.retrieve_chunk([0, 0], read_missing_chunks=False) + + def test_store_array_subset_refuses_data_that_does_not_fit() -> None: io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(ValueError, match=r"shape \(1, 3\) does not fit"): From e90a6b9152dcc6df9268d70e0f33a113ff39d7fd Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 21:50:57 +0100 Subject: [PATCH 18/31] refactor(array): keep no runtime configuration in an ArrayIO value AsyncArrayIO no longer holds an ArrayConfig. Its internal reads and writes take one as a required keyword: a public operation's, built from its own options, or an AsyncArray's own, which AsyncArray now passes explicitly. A future operation cannot fall back to a configuration the value happened to carry. Tests cover store_chunk's store_empty_chunks and a default read of a missing chunk. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 32 ++++++++++++-------------------- tests/test_array_io.py | 10 +++++++--- 2 files changed, 19 insertions(+), 23 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index fa28a5df0f..ba05d83eb0 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -1479,7 +1479,7 @@ async def _get_selection( fields: Fields | None = None, ) -> NDArrayLikeOrScalar: return await AsyncArrayIO._of(self)._get_selection( - indexer, prototype=prototype, out=out, fields=fields + indexer, prototype=prototype, out=out, fields=fields, config=self.config ) async def getitem( @@ -1663,7 +1663,7 @@ async def _set_selection( # `_store_repaired_document` is this array's repair policy, which a subclass may # override, so the write is not checked against the repair a second time. return await AsyncArrayIO._of(self)._write_selection( - indexer, value, prototype=prototype, fields=fields + indexer, value, prototype=prototype, fields=fields, config=self.config ) async def setitem( @@ -2023,7 +2023,6 @@ class AsyncArrayIO: _metadata: ArrayMetadata _store_path: StorePath - _config: ArrayConfig _codec_pipeline: CodecPipeline _chunk_grid: ChunkGrid _needs_repair: bool @@ -2039,7 +2038,6 @@ def _from_parts( cls, metadata: ArrayMetadata, store_path: StorePath, - config: ArrayConfig, codec_pipeline: CodecPipeline, chunk_grid: ChunkGrid, needs_repair: bool, @@ -2047,7 +2045,6 @@ def _from_parts( io = object.__new__(cls) object.__setattr__(io, "_metadata", metadata) object.__setattr__(io, "_store_path", store_path) - object.__setattr__(io, "_config", config) object.__setattr__(io, "_codec_pipeline", codec_pipeline) object.__setattr__(io, "_chunk_grid", chunk_grid) object.__setattr__(io, "_needs_repair", needs_repair) @@ -2063,7 +2060,6 @@ def _bound( return cls._from_parts( parsed, store_path, - _ARRAY_IO_CONFIG, create_codec_pipeline(metadata=parsed, store=store_path.store), ChunkGrid.from_metadata(parsed), parsed._stored_document is not None, @@ -2114,7 +2110,6 @@ def of(cls, array: AsyncArray[Any] | Array[Any]) -> AsyncArrayIO: return cls._from_parts( metadata, source.store_path, - source.config, source.codec_pipeline, source._chunk_grid, metadata._stored_document is not None, @@ -2127,7 +2122,6 @@ def _of(cls, array: AsyncArray[Any]) -> AsyncArrayIO: return cls._from_parts( array.metadata, array.store_path, - array.config, array.codec_pipeline, array._chunk_grid, array.metadata._stored_document is not None, @@ -2202,7 +2196,6 @@ def with_shape(self, shape: ShapeLike, /) -> AsyncArrayIO: return AsyncArrayIO._from_parts( new_metadata, self._store_path, - self._config, self._codec_pipeline, ChunkGrid.from_metadata(new_metadata), self._needs_repair, @@ -2215,7 +2208,6 @@ def with_attrs(self, attrs: Mapping[str, JSON], /) -> AsyncArrayIO: return AsyncArrayIO._from_parts( self._metadata.update_attributes(copy.deepcopy(dict(attrs))), self._store_path, - self._config, self._codec_pipeline, self._chunk_grid, self._needs_repair, @@ -2229,7 +2221,6 @@ async def store_metadata(self) -> AsyncArrayIO: return AsyncArrayIO._from_parts( self._metadata, self._store_path, - self._config, self._codec_pipeline, self._chunk_grid, False, @@ -2386,14 +2377,15 @@ async def _get_selection( prototype: BufferPrototype, out: NDBuffer | None = None, fields: Fields | None = None, - config: ArrayConfig | None = None, + config: ArrayConfig, ) -> NDArrayLikeOrScalar: - """Read through the codec pipeline, with `config` or, for `AsyncArray`, its own.""" + """Read through the codec pipeline with the runtime configuration `config`: a + public read's, or an `AsyncArray`'s own.""" return await _get_selection( self._store_path, self._metadata, self._codec_pipeline, - self._config if config is None else config, + config, self._chunk_grid, indexer, prototype=prototype, @@ -2408,7 +2400,7 @@ async def _set_selection( *, prototype: BufferPrototype, fields: Fields | None = None, - config: ArrayConfig | None = None, + config: ArrayConfig, ) -> None: """`_write_selection`, refused while `needs_repair` is true.""" if product(indexer.shape) > 0 and self._needs_repair: @@ -2429,16 +2421,16 @@ async def _write_selection( *, prototype: BufferPrototype, fields: Fields | None = None, - config: ArrayConfig | None = None, + config: ArrayConfig, ) -> None: - """Write without the check against a repair that has not been stored, for a - caller that applies its own repair policy first (`AsyncArray`), with `config` - or the value's own.""" + """Write with the runtime configuration `config`, without the check against a + repair that has not been stored, for a caller that applies its own repair policy + first (`AsyncArray`).""" await _set_selection( self._store_path, self._metadata, self._codec_pipeline, - self._config if config is None else config, + config, self._chunk_grid, indexer, value, diff --git a/tests/test_array_io.py b/tests/test_array_io.py index dad89bb14a..728facae81 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -244,14 +244,18 @@ def test_runtime_choices_are_made_per_call() -> None: io[:, 0:2] = 0 io.store_array_subset((slice(None), slice(2, 4)), 0, store_empty_chunks=True) + stored = sorted(key for key in sync(_keys(store)) if key.startswith("a/c")) + io.store_chunk([0, 0], np.zeros((2, 2)), store_empty_chunks=True) + io.store_chunk([0, 1], np.zeros((2, 2))) + restored = sorted(key for key in sync(_keys(store)) if key.startswith("a/c")) - assert sorted(key for key in sync(_keys(store)) if key.startswith("a/c")) == ["a/c/0/1"] + assert (stored, restored) == (["a/c/0/1"], ["a/c/0/0"]) assert cast("np.ndarray[Any, Any]", io[:]).flags.c_contiguous - io.erase_chunk([0, 1]) + np.testing.assert_array_equal(io.retrieve_chunk([0, 1]), np.zeros((2, 2))) with pytest.raises(ChunkNotFoundError): io.retrieve_array_subset(slice(None), read_missing_chunks=False) with pytest.raises(ChunkNotFoundError): - io.retrieve_chunk([0, 0], read_missing_chunks=False) + io.retrieve_chunk([0, 1], read_missing_chunks=False) def test_store_array_subset_refuses_data_that_does_not_fit() -> None: From 78c6d4b1d2977bfc6f7495295cba24086a358dec Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 21:56:55 +0100 Subject: [PATCH 19/31] refactor(array): drop dtype and ndim from ArrayIO Both are in the metadata, and what dtype should return (a NumPy dtype or zarr's data type) is undecided; adding it later breaks nothing. The reprs still name the data type, and ArrayIO's repr is AsyncArrayIO's. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/core/array.py | 34 ++++++++-------------------------- tests/test_array_io.py | 3 +++ 2 files changed, 11 insertions(+), 26 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index ba05d83eb0..84324d4e14 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -2133,7 +2133,8 @@ def as_sync(self, *, context: SyncContext) -> ArrayIO: return ArrayIO._wrap(self, context) def __repr__(self) -> str: - return f"" + dtype = self._metadata.dtype.to_native_dtype() + return f"" @property def metadata(self) -> dict[str, JSON]: @@ -2152,16 +2153,6 @@ def shape(self) -> tuple[int, ...]: """The shape of the array.""" return self._metadata.shape - @property - def ndim(self) -> int: - """The number of dimensions.""" - return len(self._metadata.shape) - - @property - def dtype(self) -> TBaseDType: - """The NumPy data type of the array.""" - return self._metadata.dtype.to_native_dtype() - @property def store(self) -> Store: """The store that holds the array.""" @@ -2239,10 +2230,11 @@ def _chunk_indices(self, chunk_indices: Iterable[int], *, in_grid: bool) -> tupl if any(isinstance(index, bool | np.bool_) for index in given): raise TypeError(f"Chunk indices must be integers, not booleans: {given}.") indices = tuple(operator.index(index) for index in given) - if len(indices) != self.ndim: + ndim = len(self._metadata.shape) + if len(indices) != ndim: raise ValueError( f"Chunk indices {indices} do not have one index for each of the array's " - f"{self.ndim} dimensions." + f"{ndim} dimensions." ) if any(index < 0 for index in indices): raise ValueError(f"Chunk indices {indices} must be non-negative.") @@ -2314,7 +2306,7 @@ async def store_array_subset( indexer = BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) await self._set_selection( indexer, - _fitted_data(data, self.dtype, indexer.shape), + _fitted_data(data, self._metadata.dtype.to_native_dtype(), indexer.shape), prototype=default_buffer_prototype() if prototype is None else prototype, config=_write_config(store_empty_chunks), ) @@ -2361,7 +2353,7 @@ async def store_chunk( ) await self._set_selection( indexer, - _fitted_data(data, self.dtype, indexer.shape), + _fitted_data(data, self._metadata.dtype.to_native_dtype(), indexer.shape), prototype=default_buffer_prototype() if prototype is None else prototype, config=_write_config(store_empty_chunks), ) @@ -2566,7 +2558,7 @@ def as_async(self) -> AsyncArrayIO: return self._async_io def __repr__(self) -> str: - return f"" + return " dict[str, JSON]: @@ -2583,16 +2575,6 @@ def shape(self) -> tuple[int, ...]: """See `AsyncArrayIO.shape`.""" return self._async_io.shape - @property - def ndim(self) -> int: - """See `AsyncArrayIO.ndim`.""" - return self._async_io.ndim - - @property - def dtype(self) -> TBaseDType: - """See `AsyncArrayIO.dtype`.""" - return self._async_io.dtype - @property def store(self) -> Store: """See `AsyncArrayIO.store`.""" diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 728facae81..032a2d7378 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -109,6 +109,9 @@ async def test_async_array_io_reads_and_writes() -> None: np.testing.assert_array_equal(await io[1:3], [1, 2]) np.testing.assert_array_equal(await io.retrieve_chunk([1]), [2, 3]) assert io.as_sync(context=SyncContext()).as_async() is io + assert repr(io.as_sync(context=SyncContext())) == repr(io).replace( + "" From bf5cc0aea83bdf33c98b63cb9dce7b8f50240054 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 29 Nov 2026 22:39:09 +0100 Subject: [PATCH 20/31] feat(array): define ArrayIO and AsyncArrayIO as protocols Move the interface to zarr.abc.array_io as typing protocols, so other implementations (one built on zarrs, such as zarrista) can satisfy it without zarr-python's internals. zarr-python's classes become ZarrArrayIO and AsyncZarrArrayIO. Reads return ArrayResult, anything numpy.asarray accepts; a selection of only integers reads into a 0-d buffer of the array's data type, so byte order, StringDType and trailing NULs survive. Writes take ArrayData: data that exports only through DLPack is viewed as NumPy when it is in host memory and refused otherwise; anything with __array__ is written as Array writes it. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- changes/470.feature.md | 2 +- src/zarr/abc/array_io.py | 275 +++++++++++++++++++++++++++++++++++++++ src/zarr/core/array.py | 193 ++++++++++++++++----------- tests/test_array_io.py | 180 ++++++++++++++++++++----- 4 files changed, 535 insertions(+), 115 deletions(-) create mode 100644 src/zarr/abc/array_io.py diff --git a/changes/470.feature.md b/changes/470.feature.md index 44f8c1a036..c469cf2a7c 100644 --- a/changes/470.feature.md +++ b/changes/470.feature.md @@ -1 +1 @@ -Add `AsyncArrayIO` and `ArrayIO`, which read and write an array as a value: `open`, `from_metadata` and `of` make one, `with_shape` and `with_attrs` return changed values without storing them, and `store_metadata` stores them. `AsyncArray` reads and writes through the same routines; `Array` and `AsyncArray` behave as before. +Add `zarr.abc.array_io`, an interface of protocols for reading and writing an array as a value: `AsyncArrayIO`, `ArrayIO` (its synchronous counterpart), `ArrayResult` (what reads return) and `ArrayData` (what writes accept). zarr-python implements it with `AsyncZarrArrayIO` and `ZarrArrayIO`, which `AsyncArray` reads and writes through; `Array` and `AsyncArray` behave as before. diff --git a/src/zarr/abc/array_io.py b/src/zarr/abc/array_io.py new file mode 100644 index 0000000000..e4aef896c6 --- /dev/null +++ b/src/zarr/abc/array_io.py @@ -0,0 +1,275 @@ +"""The interface for reading and writing an array as a value: `ArrayIO` (synchronous) +and `AsyncArrayIO` (asynchronous). + +An implementation holds an array's metadata, bound to a location in a store. It is a +value: metadata changes (`with_shape`, `with_attrs`) return a new value and store +nothing, `store_metadata` stores a value's metadata, and every operation acts on the +value's metadata as it is, whatever the store holds now. How a value is made (opening +an array, binding metadata) is up to each implementation and is not part of the +interface. + +zarr-python implements it with `zarr.core.array.ZarrArrayIO` and +`zarr.core.array.AsyncZarrArrayIO`. The interface is kept to what another +implementation, such as one built on zarrs, can provide without zarr-python's +internals: + +- Selections are basic: integers, slices with a step of 1 and `Ellipsis`. An integer + drops its axis, as NumPy basic indexing does. +- Data read comes back as an array that `numpy.asarray` accepts (`ArrayResult`), + which may also export through DLPack, for `numpy.from_dlpack` or another library's + `from_dlpack`. Data written is anything that exports through DLPack or the buffer + protocol (`ArrayData`); an implementation may refuse data on a device it cannot + read. A `bytes` object is one value of a bytes data type, as NumPy reads it, not a + buffer of elements. +- Chunk indices are non-negative integers, one for each dimension. +- Runtime choices are per operation: `read_missing_chunks` on reads, + `store_empty_chunks` on writes. Implementations may take more keyword options. +""" + +from __future__ import annotations + +from collections.abc import Buffer +from types import EllipsisType +from typing import TYPE_CHECKING, Any, Protocol, Self, runtime_checkable + +from typing_extensions import CapsuleType + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping, Sequence + + +__all__ = [ + "ArrayData", + "ArrayIO", + "ArrayResult", + "AsyncArrayIO", + "Selection", + "SupportsDLPack", +] + +type Selection = int | slice | EllipsisType | tuple[int | slice | EllipsisType, ...] +"""A basic selection: integers, slices with a step of 1, and at most one `Ellipsis`.""" + + +@runtime_checkable +class SupportsDLPack(Protocol): + """An array that exports its data through DLPack, as NumPy, CuPy, PyTorch and JAX + arrays do.""" + + def __dlpack__( + self, + *, + stream: int | None = None, + max_version: tuple[int, int] | None = None, + dl_device: tuple[int, int] | None = None, + copy: bool | None = None, + ) -> CapsuleType: + """Export the data as a DLPack capsule, with the keywords of the Python array + API standard.""" + ... + + def __dlpack_device__(self) -> tuple[int, int]: ... + + +@runtime_checkable +class ArrayResult(Protocol): + """Data read from an array: an array that `numpy.asarray` accepts, through + `__array__`. A NumPy array is one. A result may also export through DLPack + (`SupportsDLPack`), for `numpy.from_dlpack` and other libraries' `from_dlpack`, but + not every result can: DLPack has no strings or other variable-length data, and + NumPy exports only native byte order.""" + + def __array__(self, dtype: Any = ..., /, *, copy: bool | None = ...) -> Any: ... + + +type ArrayData = SupportsDLPack | Buffer +"""Data to write to an array: anything that exports through DLPack or the buffer +protocol, such as a NumPy, CuPy, PyTorch or JAX array, or a `memoryview`. An +implementation may refuse data on a device it cannot read; `bytes` is one value, as +NumPy reads it.""" + + +@runtime_checkable +class AsyncArrayIO(Protocol): + """An array as a value, read and written asynchronously (see the module + documentation).""" + + @property + def metadata(self) -> Mapping[str, object]: + """The array's metadata document, which another value can be made from.""" + ... + + @property + def attrs(self) -> Mapping[str, object]: + """The array's user attributes.""" + ... + + @property + def shape(self) -> Sequence[int]: + """The shape of the array.""" + ... + + @property + def path(self) -> str: + """The array's path in its store.""" + ... + + @property + def needs_repair(self) -> bool: + """Whether chunks cannot be stored until `store_metadata` has stored this + value's metadata, because it was repaired from a stored document in a way that + moves chunks. An implementation that repairs nothing returns `False`.""" + ... + + def with_shape(self, shape: Sequence[int], /) -> Self: + """This array with `shape`; nothing is stored and no chunk is erased.""" + ... + + def with_attrs(self, attrs: Mapping[str, Any], /) -> Self: + """This array with the user attributes `attrs`, which replace the old ones; + nothing is stored.""" + ... + + async def store_metadata(self) -> Self: + """Store this value's metadata, replacing what is stored, and return the array + as stored.""" + ... + + async def erase_metadata(self) -> None: + """Delete the array's metadata from the store; succeeds if there is none.""" + ... + + async def erase_chunk(self, chunk_indices: Sequence[int], /) -> None: + """Delete the chunk at `chunk_indices`; succeeds if there is none.""" + ... + + async def erase_chunks(self, chunk_indices: Iterable[Sequence[int]], /) -> None: + """Delete the chunk at each of `chunk_indices`.""" + ... + + async def retrieve_array_subset( + self, selection: Selection, /, *, read_missing_chunks: bool = True + ) -> ArrayResult: + """The values at `selection`. A missing chunk reads as the fill value, or + raises with `read_missing_chunks=False`.""" + ... + + async def store_array_subset( + self, selection: Selection, data: ArrayData, /, *, store_empty_chunks: bool = False + ) -> None: + """Write `data` at `selection`. A chunk left holding only the fill value is + deleted, unless `store_empty_chunks`.""" + ... + + async def retrieve_chunk( + self, chunk_indices: Sequence[int], /, *, read_missing_chunks: bool = True + ) -> ArrayResult: + """The values of the chunk at `chunk_indices`.""" + ... + + async def store_chunk( + self, + chunk_indices: Sequence[int], + data: ArrayData, + /, + *, + store_empty_chunks: bool = False, + ) -> None: + """Write `data` as the chunk at `chunk_indices`.""" + ... + + async def __getitem__(self, selection: Selection, /) -> ArrayResult: + """`retrieve_array_subset(selection)`.""" + ... + + +@runtime_checkable +class ArrayIO(Protocol): + """An array as a value, read and written synchronously: the same operations as + `AsyncArrayIO`, returning their results directly (see the module documentation).""" + + @property + def metadata(self) -> Mapping[str, object]: + """See `AsyncArrayIO.metadata`.""" + ... + + @property + def attrs(self) -> Mapping[str, object]: + """See `AsyncArrayIO.attrs`.""" + ... + + @property + def shape(self) -> Sequence[int]: + """See `AsyncArrayIO.shape`.""" + ... + + @property + def path(self) -> str: + """See `AsyncArrayIO.path`.""" + ... + + @property + def needs_repair(self) -> bool: + """See `AsyncArrayIO.needs_repair`.""" + ... + + def with_shape(self, shape: Sequence[int], /) -> Self: + """See `AsyncArrayIO.with_shape`.""" + ... + + def with_attrs(self, attrs: Mapping[str, Any], /) -> Self: + """See `AsyncArrayIO.with_attrs`.""" + ... + + def store_metadata(self) -> Self: + """See `AsyncArrayIO.store_metadata`.""" + ... + + def erase_metadata(self) -> None: + """See `AsyncArrayIO.erase_metadata`.""" + ... + + def erase_chunk(self, chunk_indices: Sequence[int], /) -> None: + """See `AsyncArrayIO.erase_chunk`.""" + ... + + def erase_chunks(self, chunk_indices: Iterable[Sequence[int]], /) -> None: + """See `AsyncArrayIO.erase_chunks`.""" + ... + + def retrieve_array_subset( + self, selection: Selection, /, *, read_missing_chunks: bool = True + ) -> ArrayResult: + """See `AsyncArrayIO.retrieve_array_subset`.""" + ... + + def store_array_subset( + self, selection: Selection, data: ArrayData, /, *, store_empty_chunks: bool = False + ) -> None: + """See `AsyncArrayIO.store_array_subset`.""" + ... + + def retrieve_chunk( + self, chunk_indices: Sequence[int], /, *, read_missing_chunks: bool = True + ) -> ArrayResult: + """See `AsyncArrayIO.retrieve_chunk`.""" + ... + + def store_chunk( + self, + chunk_indices: Sequence[int], + data: ArrayData, + /, + *, + store_empty_chunks: bool = False, + ) -> None: + """See `AsyncArrayIO.store_chunk`.""" + ... + + def __getitem__(self, selection: Selection, /) -> ArrayResult: + """See `AsyncArrayIO.retrieve_array_subset`.""" + ... + + def __setitem__(self, selection: Selection, data: ArrayData, /) -> None: + """See `AsyncArrayIO.store_array_subset`.""" + ... diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 84324d4e14..88c22b44ef 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -26,6 +26,7 @@ from typing_extensions import Sentinel, deprecated import zarr +from zarr.abc.array_io import SupportsDLPack from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec, Codec from zarr.abc.numcodec import Numcodec, _is_numcodec from zarr.codecs._v2 import V2Codec @@ -170,6 +171,7 @@ import numpy.typing as npt + from zarr.abc.array_io import ArrayData, ArrayResult from zarr.abc.codec import CodecPipeline from zarr.abc.store import Store from zarr.codecs.sharding import IndexLocation, ShardingCodec @@ -1478,7 +1480,7 @@ async def _get_selection( out: NDBuffer | None = None, fields: Fields | None = None, ) -> NDArrayLikeOrScalar: - return await AsyncArrayIO._of(self)._get_selection( + return await AsyncZarrArrayIO._of(self)._get_selection( indexer, prototype=prototype, out=out, fields=fields, config=self.config ) @@ -1643,7 +1645,7 @@ async def _store_repaired_document(self) -> None: """ if self.metadata._stored_document is None: return - await AsyncArrayIO._of(self)._store_repair_document() + await AsyncZarrArrayIO._of(self)._store_repair_document() # The mark is cleared through the method, as always, so a subclass that # overrides it decides. self._stored_document_replaced() @@ -1662,7 +1664,7 @@ async def _set_selection( await self._store_repaired_document() # `_store_repaired_document` is this array's repair policy, which a subclass may # override, so the write is not checked against the repair a second time. - return await AsyncArrayIO._of(self)._write_selection( + return await AsyncZarrArrayIO._of(self)._write_selection( indexer, value, prototype=prototype, fields=fields, config=self.config ) @@ -1949,7 +1951,7 @@ def _snapshot(metadata: ArrayMetadata) -> ArrayMetadata: _ARRAY_IO_CONFIG: Final = ArrayConfig(order="C", write_empty_chunks=False) -"""The runtime configuration `AsyncArrayIO`'s public reads and writes start from: fixed, +"""The runtime configuration `AsyncZarrArrayIO`'s public reads and writes start from: fixed, not read from the global configuration. Each operation sets its own choices on it.""" @@ -1963,7 +1965,11 @@ def _write_config(store_empty_chunks: bool) -> ArrayConfig: return replace(_ARRAY_IO_CONFIG, write_empty_chunks=store_empty_chunks) -def _fitted_data(data: npt.ArrayLike, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: +_DLPACK_CPU: Final = 1 +"""DLPack's device type for host memory (`kDLCPU`).""" + + +def _fitted_data(data: npt.ArrayLike | ArrayData, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: """`data` to write to a region of `shape` of an array of `dtype`, refused with `ValueError` if it does not broadcast there: writing it would drop values. @@ -1971,6 +1977,18 @@ def _fitted_data(data: npt.ArrayLike, dtype: TBaseDType, shape: tuple[int, ...]) sequence (a list, a tuple) is read as an array of `dtype` first, as the write reads it, so a tuple is one record of a structured data type. Leading axes of length 1 beyond the region's are dropped, as NumPy assignment drops them.""" + if isinstance(data, SupportsDLPack) and not hasattr(data, "__array__"): + # Data that exports only through DLPack. Anything with `__array__` (NumPy, CuPy, + # PyTorch, pyarrow) is written as `Array` writes it, since some of those + # (pyarrow with nulls or strings) cannot export through DLPack. + device = data.__dlpack_device__() + if device[0] != _DLPACK_CPU: + raise TypeError( + f"Data that exports only through DLPack must be in host memory; it is on " + f"DLPack device {device}." + ) + # Viewed as NumPy without a copy. + data = np.from_dlpack(cast("Any", data)) if hasattr(data, "shape"): given = tuple(data.shape) elif np.isscalar(data): @@ -1997,7 +2015,7 @@ def _fitted_data(data: npt.ArrayLike, dtype: TBaseDType, shape: tuple[int, ...]) @final @dataclass(frozen=True, slots=True, eq=False, init=False, repr=False) -class AsyncArrayIO: +class AsyncZarrArrayIO: """An array, as a value: its metadata, bound to a location in a store. Make one with `open` (reads the metadata from the store), `from_metadata` (binds @@ -2029,8 +2047,8 @@ class AsyncArrayIO: def __init__(self) -> None: raise TypeError( - "Make an AsyncArrayIO with AsyncArrayIO.open, AsyncArrayIO.from_metadata or " - "AsyncArrayIO.of." + "Make an AsyncZarrArrayIO with AsyncZarrArrayIO.open, AsyncZarrArrayIO.from_metadata or " + "AsyncZarrArrayIO.of." ) @classmethod @@ -2041,7 +2059,7 @@ def _from_parts( codec_pipeline: CodecPipeline, chunk_grid: ChunkGrid, needs_repair: bool, - ) -> AsyncArrayIO: + ) -> AsyncZarrArrayIO: io = object.__new__(cls) object.__setattr__(io, "_metadata", metadata) object.__setattr__(io, "_store_path", store_path) @@ -2053,7 +2071,7 @@ def _from_parts( @classmethod def _bound( cls, metadata: ArrayMetadata | ArrayMetadataDict, store_path: StorePath - ) -> AsyncArrayIO: + ) -> AsyncZarrArrayIO: """A value over `metadata`, read as `AsyncArray` reads it, deriving its codec pipeline and chunk grid.""" parsed = parse_array_metadata(metadata, str(store_path)) @@ -2072,7 +2090,7 @@ async def open( path: str = "", *, zarr_format: ZarrFormat | None = None, - ) -> AsyncArrayIO: + ) -> AsyncZarrArrayIO: """The array whose metadata `store` holds at `path`, of either Zarr format unless `zarr_format` says which. @@ -2088,7 +2106,7 @@ def from_metadata( metadata: ArrayMetadata | Mapping[str, JSON], store: Store, path: str = "", - ) -> AsyncArrayIO: + ) -> AsyncZarrArrayIO: """An array at `path` in `store` with `metadata`, a metadata object or document. Nothing is stored and nothing is checked against the store: call @@ -2102,7 +2120,7 @@ def from_metadata( return cls._bound(bound, StorePath(store, path)) @classmethod - def of(cls, array: AsyncArray[Any] | Array[Any]) -> AsyncArrayIO: + def of(cls, array: AsyncArray[Any] | Array[Any]) -> AsyncZarrArrayIO: """The array `array` reads and writes, as it is now. Later changes through `array` do not reach the value.""" source = array.async_array if isinstance(array, Array) else array @@ -2116,7 +2134,7 @@ def of(cls, array: AsyncArray[Any] | Array[Any]) -> AsyncArrayIO: ) @classmethod - def _of(cls, array: AsyncArray[Any]) -> AsyncArrayIO: + def _of(cls, array: AsyncArray[Any]) -> AsyncZarrArrayIO: """The routines over `array`'s own fields, sharing its metadata, for `AsyncArray` to read and write through.""" return cls._from_parts( @@ -2127,14 +2145,14 @@ def _of(cls, array: AsyncArray[Any]) -> AsyncArrayIO: array.metadata._stored_document is not None, ) - def as_sync(self, *, context: SyncContext) -> ArrayIO: + def as_sync(self, *, context: SyncContext) -> ZarrArrayIO: """This array, read and written synchronously with the runner `context` holds: one that runs coroutines where this value's store clients can run them.""" - return ArrayIO._wrap(self, context) + return ZarrArrayIO._wrap(self, context) def __repr__(self) -> str: dtype = self._metadata.dtype.to_native_dtype() - return f"" + return f"" @property def metadata(self) -> dict[str, JSON]: @@ -2172,7 +2190,7 @@ def needs_repair(self) -> bool: can be stored only while rectilinear chunk grids are enabled.""" return self._needs_repair - def with_shape(self, shape: ShapeLike, /) -> AsyncArrayIO: + def with_shape(self, shape: ShapeLike, /) -> AsyncZarrArrayIO: """This array with `shape`. Nothing is stored and no chunk is erased: chunks outside a smaller shape stay in the store until erased (`erase_chunks`), and growing again reads what they and the edge chunks still hold beyond the old @@ -2184,7 +2202,7 @@ def with_shape(self, shape: ShapeLike, /) -> AsyncArrayIO: f"Got {len(new_shape)} dimension(s), expected {len(self._metadata.shape)}." ) new_metadata = self._metadata.update_shape(new_shape) - return AsyncArrayIO._from_parts( + return AsyncZarrArrayIO._from_parts( new_metadata, self._store_path, self._codec_pipeline, @@ -2192,11 +2210,11 @@ def with_shape(self, shape: ShapeLike, /) -> AsyncArrayIO: self._needs_repair, ) - def with_attrs(self, attrs: Mapping[str, JSON], /) -> AsyncArrayIO: + def with_attrs(self, attrs: Mapping[str, JSON], /) -> AsyncZarrArrayIO: """This array with the user attributes `attrs`, which replace the old ones: merge them yourself to keep them (`io.with_attrs({**io.attrs, "units": "m"})`). Nothing is stored.""" - return AsyncArrayIO._from_parts( + return AsyncZarrArrayIO._from_parts( self._metadata.update_attributes(copy.deepcopy(dict(attrs))), self._store_path, self._codec_pipeline, @@ -2204,12 +2222,12 @@ def with_attrs(self, attrs: Mapping[str, JSON], /) -> AsyncArrayIO: self._needs_repair, ) - async def store_metadata(self) -> AsyncArrayIO: + async def store_metadata(self) -> AsyncZarrArrayIO: """Store this value's metadata at the array's path, replacing whatever metadata is there, and return the array as stored: if this value needed a repair, the returned one does not.""" await save_metadata(self._store_path, self._metadata) - return AsyncArrayIO._from_parts( + return AsyncZarrArrayIO._from_parts( self._metadata, self._store_path, self._codec_pipeline, @@ -2274,23 +2292,23 @@ async def retrieve_array_subset( *, read_missing_chunks: bool = True, prototype: BufferPrototype | None = None, - ) -> NDArrayLikeOrScalar: + ) -> ArrayResult: """The values at `selection`, by NumPy basic indexing. A chunk missing from the store reads as the fill value; with `read_missing_chunks=False`, it raises `ChunkNotFoundError` instead, for data known to be complete that is read over a connection that can fail.""" indexer = BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) - return await self._get_selection( + return await self._retrieve( indexer, prototype=default_buffer_prototype() if prototype is None else prototype, - config=_read_config(read_missing_chunks), + read_missing_chunks=read_missing_chunks, ) async def store_array_subset( self, selection: BasicSelection, - data: npt.ArrayLike, + data: npt.ArrayLike | ArrayData, /, *, store_empty_chunks: bool = False, @@ -2318,7 +2336,7 @@ async def retrieve_chunk( *, read_missing_chunks: bool = True, prototype: BufferPrototype | None = None, - ) -> NDArrayLikeOrScalar: + ) -> ArrayResult: """The decoded values of the chunk at `chunk_indices`, within the array: a chunk at the array's edge gives only the part inside the array's shape. A missing chunk is handled as `retrieve_array_subset` handles it.""" @@ -2327,16 +2345,16 @@ async def retrieve_chunk( self._metadata.shape, self._chunk_grid, ) - return await self._get_selection( + return await self._retrieve( indexer, prototype=default_buffer_prototype() if prototype is None else prototype, - config=_read_config(read_missing_chunks), + read_missing_chunks=read_missing_chunks, ) async def store_chunk( self, chunk_indices: Iterable[int], - data: npt.ArrayLike, + data: npt.ArrayLike | ArrayData, /, *, store_empty_chunks: bool = False, @@ -2358,10 +2376,27 @@ async def store_chunk( config=_write_config(store_empty_chunks), ) - async def __getitem__(self, selection: BasicSelection, /) -> NDArrayLikeOrScalar: + async def __getitem__(self, selection: BasicSelection, /) -> ArrayResult: """`retrieve_array_subset(selection)`.""" return await self.retrieve_array_subset(selection) + async def _retrieve( + self, indexer: Indexer, *, prototype: BufferPrototype, read_missing_chunks: bool + ) -> ArrayResult: + """A public read: an array of the prototype's kind, 0-d for a selection of only + integers. That read goes into a 0-d buffer of the array's data type, because + `_get_selection` would return a scalar, which loses the data type (a byte order, + `StringDType`) and the prototype's kind.""" + config = _read_config(read_missing_chunks) + if indexer.shape != (): + return cast( + "ArrayResult", + await self._get_selection(indexer, prototype=prototype, config=config), + ) + out = prototype.nd_buffer.empty(shape=(), dtype=self._metadata.dtype.to_native_dtype()) + await self._get_selection(indexer, prototype=prototype, out=out, config=config) + return cast("ArrayResult", out.as_ndarray_like()) + async def _get_selection( self, indexer: Indexer, @@ -2457,7 +2492,7 @@ async def _store_repair_document(self) -> None: if current._stored_document is not None: await upsert_metadata(self._store_path, current, documents) - async def _resized(self, new_shape: ShapeLike, delete_outside_chunks: bool) -> AsyncArrayIO: + async def _resized(self, new_shape: ShapeLike, delete_outside_chunks: bool) -> AsyncZarrArrayIO: """Store the metadata of the array resized to `new_shape`, deleting the chunks outside it if `delete_outside_chunks`, for `AsyncArray.resize`, which clears the shared repair mark itself. The new metadata is encoded before any chunk is @@ -2490,29 +2525,31 @@ async def _resized(self, new_shape: ShapeLike, delete_outside_chunks: bool) -> A @final @dataclass(frozen=True, slots=True, eq=False, init=False, repr=False) -class ArrayIO: +class ZarrArrayIO: """An array, as a value, read and written synchronously: each operation runs the - matching `AsyncArrayIO` operation with the runner its `SyncContext` holds. + matching `AsyncZarrArrayIO` operation with the runner its `SyncContext` holds. - Make one with `open`, `from_metadata` or `of`, as for `AsyncArrayIO`, whose + Make one with `open`, `from_metadata` or `of`, as for `AsyncZarrArrayIO`, whose documentation describes the value and its metadata changes. """ - _async_io: AsyncArrayIO + _async_io: AsyncZarrArrayIO _context: SyncContext def __init__(self) -> None: - raise TypeError("Make an ArrayIO with ArrayIO.open, ArrayIO.from_metadata or ArrayIO.of.") + raise TypeError( + "Make a ZarrArrayIO with ZarrArrayIO.open, ZarrArrayIO.from_metadata or ZarrArrayIO.of." + ) @classmethod - def _wrap(cls, async_io: AsyncArrayIO, context: SyncContext) -> ArrayIO: + def _wrap(cls, async_io: AsyncZarrArrayIO, context: SyncContext) -> ZarrArrayIO: io = object.__new__(cls) object.__setattr__(io, "_async_io", async_io) object.__setattr__(io, "_context", context) return io - def _rewrap(self, async_io: AsyncArrayIO) -> ArrayIO: - return ArrayIO._wrap(async_io, self._context) + def _rewrap(self, async_io: AsyncZarrArrayIO) -> ZarrArrayIO: + return ZarrArrayIO._wrap(async_io, self._context) def _run[T](self, coroutine: Coroutine[Any, Any, T]) -> T: return self._context.runner.run(coroutine) @@ -2525,10 +2562,10 @@ def open( *, zarr_format: ZarrFormat | None = None, context: SyncContext | None = None, - ) -> ArrayIO: - """See `AsyncArrayIO.open`.""" + ) -> ZarrArrayIO: + """See `AsyncZarrArrayIO.open`.""" context = SyncContext() if context is None else context - opened = context.runner.run(AsyncArrayIO.open(store, path, zarr_format=zarr_format)) + opened = context.runner.run(AsyncZarrArrayIO.open(store, path, zarr_format=zarr_format)) return cls._wrap(opened, context) @classmethod @@ -2539,79 +2576,79 @@ def from_metadata( path: str = "", *, context: SyncContext | None = None, - ) -> ArrayIO: - """See `AsyncArrayIO.from_metadata`.""" + ) -> ZarrArrayIO: + """See `AsyncZarrArrayIO.from_metadata`.""" return cls._wrap( - AsyncArrayIO.from_metadata(metadata, store, path), + AsyncZarrArrayIO.from_metadata(metadata, store, path), SyncContext() if context is None else context, ) @classmethod def of( cls, array: AsyncArray[Any] | Array[Any], *, context: SyncContext | None = None - ) -> ArrayIO: - """See `AsyncArrayIO.of`.""" - return cls._wrap(AsyncArrayIO.of(array), SyncContext() if context is None else context) + ) -> ZarrArrayIO: + """See `AsyncZarrArrayIO.of`.""" + return cls._wrap(AsyncZarrArrayIO.of(array), SyncContext() if context is None else context) - def as_async(self) -> AsyncArrayIO: + def as_async(self) -> AsyncZarrArrayIO: """This array, read and written asynchronously.""" return self._async_io def __repr__(self) -> str: - return " dict[str, JSON]: - """See `AsyncArrayIO.metadata`.""" + """See `AsyncZarrArrayIO.metadata`.""" return self._async_io.metadata @property def attrs(self) -> dict[str, JSON]: - """See `AsyncArrayIO.attrs`.""" + """See `AsyncZarrArrayIO.attrs`.""" return self._async_io.attrs @property def shape(self) -> tuple[int, ...]: - """See `AsyncArrayIO.shape`.""" + """See `AsyncZarrArrayIO.shape`.""" return self._async_io.shape @property def store(self) -> Store: - """See `AsyncArrayIO.store`.""" + """See `AsyncZarrArrayIO.store`.""" return self._async_io.store @property def path(self) -> str: - """See `AsyncArrayIO.path`.""" + """See `AsyncZarrArrayIO.path`.""" return self._async_io.path @property def needs_repair(self) -> bool: - """See `AsyncArrayIO.needs_repair`.""" + """See `AsyncZarrArrayIO.needs_repair`.""" return self._async_io.needs_repair - def with_shape(self, shape: ShapeLike, /) -> ArrayIO: - """See `AsyncArrayIO.with_shape`.""" + def with_shape(self, shape: ShapeLike, /) -> ZarrArrayIO: + """See `AsyncZarrArrayIO.with_shape`.""" return self._rewrap(self._async_io.with_shape(shape)) - def with_attrs(self, attrs: Mapping[str, JSON], /) -> ArrayIO: - """See `AsyncArrayIO.with_attrs`.""" + def with_attrs(self, attrs: Mapping[str, JSON], /) -> ZarrArrayIO: + """See `AsyncZarrArrayIO.with_attrs`.""" return self._rewrap(self._async_io.with_attrs(attrs)) - def store_metadata(self) -> ArrayIO: - """See `AsyncArrayIO.store_metadata`.""" + def store_metadata(self) -> ZarrArrayIO: + """See `AsyncZarrArrayIO.store_metadata`.""" return self._rewrap(self._run(self._async_io.store_metadata())) def erase_metadata(self) -> None: - """See `AsyncArrayIO.erase_metadata`.""" + """See `AsyncZarrArrayIO.erase_metadata`.""" self._run(self._async_io.erase_metadata()) def erase_chunk(self, chunk_indices: Iterable[int], /) -> None: - """See `AsyncArrayIO.erase_chunk`.""" + """See `AsyncZarrArrayIO.erase_chunk`.""" self._run(self._async_io.erase_chunk(chunk_indices)) def erase_chunks(self, chunk_indices: Iterable[Iterable[int]], /) -> None: - """See `AsyncArrayIO.erase_chunks`.""" + """See `AsyncZarrArrayIO.erase_chunks`.""" self._run(self._async_io.erase_chunks(chunk_indices)) def retrieve_array_subset( @@ -2621,8 +2658,8 @@ def retrieve_array_subset( *, read_missing_chunks: bool = True, prototype: BufferPrototype | None = None, - ) -> NDArrayLikeOrScalar: - """See `AsyncArrayIO.retrieve_array_subset`.""" + ) -> ArrayResult: + """See `AsyncZarrArrayIO.retrieve_array_subset`.""" return self._run( self._async_io.retrieve_array_subset( selection, read_missing_chunks=read_missing_chunks, prototype=prototype @@ -2632,13 +2669,13 @@ def retrieve_array_subset( def store_array_subset( self, selection: BasicSelection, - data: npt.ArrayLike, + data: npt.ArrayLike | ArrayData, /, *, store_empty_chunks: bool = False, prototype: BufferPrototype | None = None, ) -> None: - """See `AsyncArrayIO.store_array_subset`.""" + """See `AsyncZarrArrayIO.store_array_subset`.""" self._run( self._async_io.store_array_subset( selection, data, store_empty_chunks=store_empty_chunks, prototype=prototype @@ -2652,8 +2689,8 @@ def retrieve_chunk( *, read_missing_chunks: bool = True, prototype: BufferPrototype | None = None, - ) -> NDArrayLikeOrScalar: - """See `AsyncArrayIO.retrieve_chunk`.""" + ) -> ArrayResult: + """See `AsyncZarrArrayIO.retrieve_chunk`.""" return self._run( self._async_io.retrieve_chunk( chunk_indices, read_missing_chunks=read_missing_chunks, prototype=prototype @@ -2663,24 +2700,24 @@ def retrieve_chunk( def store_chunk( self, chunk_indices: Iterable[int], - data: npt.ArrayLike, + data: npt.ArrayLike | ArrayData, /, *, store_empty_chunks: bool = False, prototype: BufferPrototype | None = None, ) -> None: - """See `AsyncArrayIO.store_chunk`.""" + """See `AsyncZarrArrayIO.store_chunk`.""" self._run( self._async_io.store_chunk( chunk_indices, data, store_empty_chunks=store_empty_chunks, prototype=prototype ) ) - def __getitem__(self, selection: BasicSelection, /) -> NDArrayLikeOrScalar: + def __getitem__(self, selection: BasicSelection, /) -> ArrayResult: """`retrieve_array_subset(selection)`.""" return self.retrieve_array_subset(selection) - def __setitem__(self, selection: BasicSelection, data: npt.ArrayLike, /) -> None: + def __setitem__(self, selection: BasicSelection, data: npt.ArrayLike | ArrayData, /) -> None: """`store_array_subset(selection, data)`.""" self.store_array_subset(selection, data) @@ -6713,7 +6750,7 @@ async def _resize( If True (default), chunks that fall outside the new shape will be deleted. If False, the data in those chunks will be preserved. """ - resized = await AsyncArrayIO._of(array)._resized(new_shape, delete_outside_chunks) + resized = await AsyncZarrArrayIO._of(array)._resized(new_shape, delete_outside_chunks) # The mark is cleared through the method, as always, so a subclass that overrides # it decides. array._stored_document_replaced() diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 032a2d7378..c6cd20fccc 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -1,4 +1,4 @@ -"""`AsyncArrayIO` and `ArrayIO`: an array as a value, read and written explicitly.""" +"""`AsyncZarrArrayIO` and `ZarrArrayIO`: an array as a value, read and written explicitly.""" from __future__ import annotations @@ -9,9 +9,11 @@ import numpy as np import pytest +from typing_extensions import CapsuleType import zarr -from zarr.core.array import ArrayIO, AsyncArray, AsyncArrayIO, _fitted_data +from zarr.abc.array_io import ArrayIO, ArrayResult, AsyncArrayIO, SupportsDLPack +from zarr.core.array import AsyncArray, AsyncZarrArrayIO, ZarrArrayIO, _fitted_data from zarr.core.sync import SyncContext, sync from zarr.errors import ChunkNotFoundError, MetadataRepairRequiredError, ZarrUserWarning from zarr.storage import LocalStore, MemoryStore, StorePath @@ -49,7 +51,7 @@ def test_array_io_reads_writes_and_changes_metadata( on_calling_thread: bool, calling_thread_runner: asyncio.Runner, ) -> None: - """An `ArrayIO` reads and writes through the runner its context holds. Metadata + """An `ZarrArrayIO` reads and writes through the runner its context holds. Metadata changes return new values and store nothing until `store_metadata`; the values they were made from, and the array a value was made from, are left as they were. `with_attrs` replaces the attributes, and no attribute dict a value takes in or hands @@ -67,13 +69,13 @@ def test_array_io_reads_writes_and_changes_metadata( runner = _CountingRunner(calling_thread_runner if on_calling_thread else None) context = SyncContext(runner=runner) if made_by == "open": - io = ArrayIO.open(store, "a", context=context) + io = ZarrArrayIO.open(store, "a", context=context) elif made_by == "from_metadata": - io = ArrayIO.from_metadata(array.metadata, store, "a", context=context) + io = ZarrArrayIO.from_metadata(array.metadata, store, "a", context=context) elif made_by == "of": - io = ArrayIO.of(array, context=context) + io = ZarrArrayIO.of(array, context=context) else: - io = ArrayIO.of(array.async_array, context=context) + io = ZarrArrayIO.of(array.async_array, context=context) array.attrs["late"] = 1 cast("list[int]", io.attrs["n"]).append(2) cast("list[int]", cast("dict[str, Any]", io.metadata["attributes"])["n"]).append(3) @@ -98,11 +100,11 @@ def test_array_io_reads_writes_and_changes_metadata( async def test_async_array_io_reads_and_writes() -> None: - """`AsyncArrayIO` opens, reads and writes an array asynchronously, and `as_sync` and - `as_async` move between it and `ArrayIO`.""" + """`AsyncZarrArrayIO` opens, reads and writes an array asynchronously, and `as_sync` and + `as_async` move between it and `ZarrArrayIO`.""" store = MemoryStore() zarr.create_array(store, name="a", shape=(4,), chunks=(2,), dtype="int64") - io = await AsyncArrayIO.open(store, "a") + io = await AsyncZarrArrayIO.open(store, "a") await io.store_array_subset(slice(None), np.arange(4)) @@ -110,9 +112,9 @@ async def test_async_array_io_reads_and_writes() -> None: np.testing.assert_array_equal(await io.retrieve_chunk([1]), [2, 3]) assert io.as_sync(context=SyncContext()).as_async() is io assert repr(io.as_sync(context=SyncContext())) == repr(io).replace( - "" + assert repr(io) == f"" @pytest.mark.parametrize("zarr_format", [2, 3]) @@ -122,7 +124,7 @@ def test_store_metadata_stores_the_repair(tmp_path: Path, zarr_format: Literal[2 path = tmp_path / "legacy.zarr" _legacy_array(path, zarr_format) with pytest.warns(ZarrUserWarning, match="is read as"): - io = ArrayIO.open(LocalStore(path)) + io = ZarrArrayIO.open(LocalStore(path)) repaired = io.store_metadata() repaired[:] = [1, 2, 3] @@ -141,7 +143,7 @@ def test_chunks_are_refused_until_the_repair_is_stored( path = tmp_path / "legacy.zarr" _legacy_array(path, zarr_format) with pytest.warns(ZarrUserWarning, match="is read as"): - io = ArrayIO.open(LocalStore(path)).with_attrs({"a": 1}) + io = ZarrArrayIO.open(LocalStore(path)).with_attrs({"a": 1}) before = {p: p.read_bytes() for p in path.rglob("*") if p.is_file()} with pytest.raises(MetadataRepairRequiredError, match=r"store_metadata\(\)"): @@ -169,7 +171,7 @@ def test_erase_deletes_chunks_and_metadata(zarr_format: Literal[2, 3], separator }, ) array[:] = np.arange(1, 7) - io = ArrayIO.of(array).with_shape((2,)).store_metadata() + io = ZarrArrayIO.of(array).with_shape((2,)).store_metadata() io.erase_chunks([[1], [2]]) regrown = io.with_shape((6,)) @@ -187,8 +189,8 @@ def test_a_value_keeps_attributes_changed_where_it_came_from() -> None: store = MemoryStore() array = zarr.create_array(store, name="a", shape=(2,), dtype="int8", attributes={"n": [1]}) document = array.metadata.to_dict() - taken = ArrayIO.of(array) - made = ArrayIO.from_metadata(MappingProxyType(document), store, "a") + taken = ZarrArrayIO.of(array) + made = ZarrArrayIO.from_metadata(MappingProxyType(document), store, "a") cast("list[int]", array.attrs["n"]).append(2) cast("list[int]", cast("dict[str, Any]", document["attributes"])["n"]).append(3) @@ -202,8 +204,8 @@ def test_values_not_taken_from_an_array_ignore_the_global_configuration() -> Non store = MemoryStore() array = zarr.create_array(store, name="a", shape=(4,), chunks=(2,), dtype="int8") with zarr.config.set({"array.write_empty_chunks": True}): - opened = ArrayIO.open(store, "a") - made = ArrayIO.from_metadata(array.metadata, store, "a") + opened = ZarrArrayIO.open(store, "a") + made = ZarrArrayIO.from_metadata(array.metadata, store, "a") opened[0:2] = [0, 0] made[2:4] = [0, 0] @@ -218,7 +220,7 @@ def test_values_not_taken_from_an_array_ignore_the_global_configuration() -> Non def test_store_array_subset_drops_leading_axes_of_length_one(data: Any) -> None: """Data with leading axes of length 1 beyond the region's writes as NumPy assignment writes it, across chunks.""" - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) io[:] = data np.testing.assert_array_equal(io[:], [1, 2, 3, 4]) @@ -243,7 +245,7 @@ def test_runtime_choices_are_made_per_call() -> None: dtype="int8", config={"write_empty_chunks": True, "read_missing_chunks": False, "order": "F"}, ) - io = ArrayIO.of(array) + io = ZarrArrayIO.of(array) io[:, 0:2] = 0 io.store_array_subset((slice(None), slice(2, 4)), 0, store_empty_chunks=True) @@ -261,20 +263,126 @@ def test_runtime_choices_are_made_per_call() -> None: io.retrieve_chunk([0, 1], read_missing_chunks=False) +class _DLPackOnly: + """An array that exports only through DLPack, as a PyTorch or JAX tensor can.""" + + def __init__(self, array: np.ndarray[Any, Any]) -> None: + self._array = array + + def __dlpack__( + self, + *, + stream: int | None = None, + max_version: tuple[int, int] | None = None, + dl_device: tuple[int, int] | None = None, + copy: bool | None = None, + ) -> CapsuleType: + # NumPy 2.0 (the oldest NumPy supported) takes none of the keywords. + return self._array.__dlpack__() + + def __dlpack_device__(self) -> tuple[int, int]: + return self._array.__dlpack_device__() + + +def test_zarr_array_io_implements_the_interface() -> None: + """`ZarrArrayIO` and `AsyncZarrArrayIO` are `ArrayIO` and `AsyncArrayIO`: they + write data that exports only through DLPack, and read `ArrayResult`s, a selection + of only integers included (as a 0-d array), that export numeric data through + DLPack.""" + array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") + io: ArrayIO = ZarrArrayIO.of(array) + async_io: AsyncArrayIO = AsyncZarrArrayIO.of(array) + + io[:] = _DLPackOnly(np.arange(4)) + point = io[1] + + assert isinstance(io, ArrayIO) + assert isinstance(async_io, AsyncArrayIO) + assert isinstance(point, ArrayResult) + assert np.asarray(point).shape == () + numeric = io[:] + assert isinstance(numeric, SupportsDLPack) + np.testing.assert_array_equal(np.from_dlpack(numeric), [0, 1, 2, 3]) + + +class _ArrayWithoutDLPackExport: + """Data with `__array__` whose DLPack export fails, as a pyarrow array with nulls + or strings does; it has no `shape`.""" + + def __init__(self, values: list[float]) -> None: + self._values = values + + def __array__(self, dtype: Any = None, copy: bool | None = None) -> np.ndarray[Any, Any]: + return np.asarray(self._values, dtype=dtype) + + def __dlpack__(self, **kwargs: object) -> CapsuleType: + raise BufferError("cannot export through DLPack") + + def __dlpack_device__(self) -> tuple[int, int]: + return (1, 0) + + +class _DLPackOnlyOnDevice: + """Data that exports only through DLPack, from a device other than the host.""" + + def __dlpack__(self, **kwargs: object) -> CapsuleType: + raise AssertionError("not exported") + + def __dlpack_device__(self) -> tuple[int, int]: + return (2, 0) + + +@pytest.mark.parametrize( + ("dtype", "zarr_format", "value"), + [ + (str, 3, "ab\x00"), + (str, 2, "ab\x00"), + (">i4", 2, 7), + ("int64", 3, 7), + ], +) +def test_integer_reads_keep_the_data_type( + dtype: str | type, zarr_format: Literal[2, 3], value: object +) -> None: + """A selection of only integers reads as a 0-d array of the same data type a slice + reads as, with the value intact (a string keeps its trailing NULs); writes take + data with `__array__` as `Array` takes it, even when its DLPack export fails.""" + array = zarr.create_array( + MemoryStore(), shape=(2,), chunks=(2,), dtype=dtype, zarr_format=zarr_format + ) + io = ZarrArrayIO.of(array) + io[:] = np.asarray([value, value], dtype=np.asarray(array[:]).dtype) + floats = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(2,), dtype="float64")) + floats[:] = _ArrayWithoutDLPackExport([1.0, np.nan]) + + point = np.asarray(io[0]) + + assert point.shape == () + assert point.dtype == np.asarray(io[0:1]).dtype + assert point.item() == value + np.testing.assert_array_equal(np.asarray(floats[:]), [1.0, np.nan]) + + +def test_store_array_subset_refuses_dlpack_only_data_off_the_host() -> None: + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(2,), dtype="float64")) + with pytest.raises(TypeError, match=r"must be in host memory; it is on DLPack device \(2, 0\)"): + io[:] = cast("Any", _DLPackOnlyOnDevice()) + + def test_store_array_subset_refuses_data_that_does_not_fit() -> None: - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(ValueError, match=r"shape \(1, 3\) does not fit"): io[0:2] = [[5, 6, 7]] def test_store_array_subset_refuses_a_memoryview_that_does_not_fit() -> None: - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(ValueError, match=r"shape \(3,\) does not fit"): io[0:2] = memoryview(np.arange(3)) def test_store_chunk_refuses_data_beyond_an_edge_chunk() -> None: - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(5,), chunks=(2,), dtype="int64")) + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(5,), chunks=(2,), dtype="int64")) with pytest.raises(ValueError, match="does not fit"): io.store_chunk([2], [1, 2]) @@ -295,7 +403,7 @@ def test_store_array_subset_writes_what_array_writes(dtype: Any, selection: Any, """`store_array_subset` writes every value `Array` writes for the same selection, structured records included, and stores the same result.""" io_store, array_store = MemoryStore(), MemoryStore() - io = ArrayIO.of(zarr.create_array(io_store, shape=(4,), chunks=(2,), dtype=dtype)) + io = ZarrArrayIO.of(zarr.create_array(io_store, shape=(4,), chunks=(2,), dtype=dtype)) array = zarr.create_array(array_store, shape=(4,), chunks=(2,), dtype=dtype) io[selection] = data @@ -305,52 +413,52 @@ def test_store_array_subset_writes_what_array_writes(dtype: Any, selection: Any, def test_store_array_subset_refuses_an_out_of_range_number() -> None: - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(3,), chunks=(3,), dtype="uint8")) + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(3,), chunks=(3,), dtype="uint8")) with pytest.raises(OverflowError): io[:] = [1, 300, 2] def test_chunk_indices_must_be_non_negative() -> None: - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(ValueError, match="non-negative"): io.erase_chunk([-1]) def test_chunk_indices_need_one_index_for_each_dimension() -> None: - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(ValueError, match="one index for each"): io.erase_chunk([]) def test_chunk_indices_are_not_booleans() -> None: - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(TypeError, match="not booleans"): io.retrieve_chunk([True]) def test_chunk_indices_may_be_any_iterable() -> None: - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) io.store_chunk((index for index in (1,)), [7, 8]) np.testing.assert_array_equal(io.retrieve_chunk(iter([1])), [7, 8]) def test_chunk_reads_need_indices_inside_the_chunk_grid() -> None: - io = ArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(IndexError, match="outside the chunk grid"): io.retrieve_chunk([2]) def test_array_io_is_made_only_by_its_constructors() -> None: - with pytest.raises(TypeError, match="AsyncArrayIO.open"): - AsyncArrayIO() - with pytest.raises(TypeError, match="ArrayIO.open"): - ArrayIO() + with pytest.raises(TypeError, match="AsyncZarrArrayIO.open"): + AsyncZarrArrayIO() + with pytest.raises(TypeError, match="ZarrArrayIO.open"): + ZarrArrayIO() def test_with_shape_rejects_another_number_of_dimensions() -> None: array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") with pytest.raises(ValueError, match="same number of dimensions"): - AsyncArrayIO.of(array).with_shape((4, 4)) + AsyncZarrArrayIO.of(array).with_shape((4, 4)) class _HookedAsyncArray(AsyncArray[Any]): From d0cef561a509656b114df8f3041d90fa967a6704 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 15:07:03 +0100 Subject: [PATCH 21/31] refactor(array): keep ZarrArrayIO's store private The store is an implementation detail of an ArrayIO value: the constructors take one, but neither ZarrArrayIO nor AsyncZarrArrayIO exposes it. The protocols never had a store member; `path` stays. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- src/zarr/core/array.py | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 88c22b44ef..d6e82564e8 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -2171,11 +2171,6 @@ def shape(self) -> tuple[int, ...]: """The shape of the array.""" return self._metadata.shape - @property - def store(self) -> Store: - """The store that holds the array.""" - return self._store_path.store - @property def path(self) -> str: """The array's path in its store.""" @@ -2612,11 +2607,6 @@ def shape(self) -> tuple[int, ...]: """See `AsyncZarrArrayIO.shape`.""" return self._async_io.shape - @property - def store(self) -> Store: - """See `AsyncZarrArrayIO.store`.""" - return self._async_io.store - @property def path(self) -> str: """See `AsyncZarrArrayIO.path`.""" From 4549282b445f306fe1cfd618f6774c3bf3bac4c3 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 15:07:14 +0100 Subject: [PATCH 22/31] feat(array): limit ArrayIO selections to array subsets A selection is now slices with a step of 1 and Ellipsis, and data has the subset's shape. Integers are left out of the interface because implementations differ on them: zarr-python drops an integer's axis as NumPy does, while zarrista keeps it as a range of length 1. ZarrArrayIO refuses an integer or other non-slice selector with TypeError and a step other than 1 with ValueError, so code that runs against it means the same thing against any implementation. NumPy indexing stays in zarr.Array. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- src/zarr/abc/array_io.py | 11 +++++---- src/zarr/core/array.py | 47 ++++++++++++++++++++++++++----------- tests/test_array_io.py | 50 ++++++++++++++++++++++++++-------------- 3 files changed, 74 insertions(+), 34 deletions(-) diff --git a/src/zarr/abc/array_io.py b/src/zarr/abc/array_io.py index e4aef896c6..bff06227c3 100644 --- a/src/zarr/abc/array_io.py +++ b/src/zarr/abc/array_io.py @@ -13,8 +13,11 @@ implementation, such as one built on zarrs, can provide without zarr-python's internals: -- Selections are basic: integers, slices with a step of 1 and `Ellipsis`. An integer - drops its axis, as NumPy basic indexing does. +- A selection is an array subset: slices with a step of 1 and `Ellipsis`, and the + data read or written has the subset's shape. Integers are not selections, because + implementations differ on whether an integer keeps its axis; select one element of + an axis with `slice(i, i + 1)`. NumPy indexing (integers that drop axes, steps, + index arrays) belongs to a layer above, such as `zarr.Array`. - Data read comes back as an array that `numpy.asarray` accepts (`ArrayResult`), which may also export through DLPack, for `numpy.from_dlpack` or another library's `from_dlpack`. Data written is anything that exports through DLPack or the buffer @@ -47,8 +50,8 @@ "SupportsDLPack", ] -type Selection = int | slice | EllipsisType | tuple[int | slice | EllipsisType, ...] -"""A basic selection: integers, slices with a step of 1, and at most one `Ellipsis`.""" +type Selection = slice | EllipsisType | tuple[slice | EllipsisType, ...] +"""An array subset: slices with a step of 1 and at most one `Ellipsis`.""" @runtime_checkable diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index d6e82564e8..a9895b4fe6 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -26,6 +26,7 @@ from typing_extensions import Sentinel, deprecated import zarr +from zarr.abc.array_io import Selection as ArraySubsetSelection from zarr.abc.array_io import SupportsDLPack from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec, Codec from zarr.abc.numcodec import Numcodec, _is_numcodec @@ -2258,6 +2259,21 @@ def _chunk_indices(self, chunk_indices: Iterable[int], *, in_grid: bool) -> tupl raise IndexError(f"Chunk indices {indices} are outside the chunk grid {grid_shape}.") return indices + def _subset_indexer(self, selection: ArraySubsetSelection) -> BasicIndexer: + """The indexer for `selection`, which must hold only slices with a step of 1 and + `Ellipsis`.""" + selectors = selection if isinstance(selection, tuple) else (selection,) + for selector in selectors: + if isinstance(selector, slice): + if selector.step not in (None, 1): + raise ValueError(f"A selection takes slices with a step of 1, not {selector}.") + elif selector is not Ellipsis: + raise TypeError( + f"A selection takes slices and Ellipsis, not {type(selector).__name__} " + f"({selector!r}). For one element of an axis, select slice(i, i + 1)." + ) + return BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) + async def erase_chunk(self, chunk_indices: Iterable[int], /) -> None: """Delete the chunk at `chunk_indices` from the store; it then reads as the fill value. Succeeds if there is none. Indices outside the chunk grid are allowed, @@ -2282,18 +2298,20 @@ async def erase_chunks(self, chunk_indices: Iterable[Iterable[int]], /) -> None: async def retrieve_array_subset( self, - selection: BasicSelection, + selection: ArraySubsetSelection, /, *, read_missing_chunks: bool = True, prototype: BufferPrototype | None = None, ) -> ArrayResult: - """The values at `selection`, by NumPy basic indexing. + """The values in the array subset `selection`: slices with a step of 1 and + `Ellipsis`, with the subset's shape. Raises `TypeError` for any other selector, + integers included, and `ValueError` for another step. A chunk missing from the store reads as the fill value; with `read_missing_chunks=False`, it raises `ChunkNotFoundError` instead, for data known to be complete that is read over a connection that can fail.""" - indexer = BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) + indexer = self._subset_indexer(selection) return await self._retrieve( indexer, prototype=default_buffer_prototype() if prototype is None else prototype, @@ -2302,21 +2320,22 @@ async def retrieve_array_subset( async def store_array_subset( self, - selection: BasicSelection, + selection: ArraySubsetSelection, data: npt.ArrayLike | ArrayData, /, *, store_empty_chunks: bool = False, prototype: BufferPrototype | None = None, ) -> None: - """Write `data` at `selection`, by NumPy basic indexing. + """Write `data` to the array subset `selection`, which is as for + `retrieve_array_subset`. A chunk left holding only the fill value is deleted from the store, unless `store_empty_chunks`. Raises `ValueError` if `data` does not broadcast to the selected region, and `MetadataRepairRequiredError` while `needs_repair` is true; nothing is written when it raises. Values are cast to the array's data type as NumPy casts them.""" - indexer = BasicIndexer(selection, shape=self._metadata.shape, chunk_grid=self._chunk_grid) + indexer = self._subset_indexer(selection) await self._set_selection( indexer, _fitted_data(data, self._metadata.dtype.to_native_dtype(), indexer.shape), @@ -2371,15 +2390,15 @@ async def store_chunk( config=_write_config(store_empty_chunks), ) - async def __getitem__(self, selection: BasicSelection, /) -> ArrayResult: + async def __getitem__(self, selection: ArraySubsetSelection, /) -> ArrayResult: """`retrieve_array_subset(selection)`.""" return await self.retrieve_array_subset(selection) async def _retrieve( self, indexer: Indexer, *, prototype: BufferPrototype, read_missing_chunks: bool ) -> ArrayResult: - """A public read: an array of the prototype's kind, 0-d for a selection of only - integers. That read goes into a 0-d buffer of the array's data type, because + """A public read: an array of the prototype's kind, 0-d for a 0-d array. That + read goes into a 0-d buffer of the array's data type, because `_get_selection` would return a scalar, which loses the data type (a byte order, `StringDType`) and the prototype's kind.""" config = _read_config(read_missing_chunks) @@ -2643,7 +2662,7 @@ def erase_chunks(self, chunk_indices: Iterable[Iterable[int]], /) -> None: def retrieve_array_subset( self, - selection: BasicSelection, + selection: ArraySubsetSelection, /, *, read_missing_chunks: bool = True, @@ -2658,7 +2677,7 @@ def retrieve_array_subset( def store_array_subset( self, - selection: BasicSelection, + selection: ArraySubsetSelection, data: npt.ArrayLike | ArrayData, /, *, @@ -2703,11 +2722,13 @@ def store_chunk( ) ) - def __getitem__(self, selection: BasicSelection, /) -> ArrayResult: + def __getitem__(self, selection: ArraySubsetSelection, /) -> ArrayResult: """`retrieve_array_subset(selection)`.""" return self.retrieve_array_subset(selection) - def __setitem__(self, selection: BasicSelection, data: npt.ArrayLike | ArrayData, /) -> None: + def __setitem__( + self, selection: ArraySubsetSelection, data: npt.ArrayLike | ArrayData, / + ) -> None: """`store_array_subset(selection, data)`.""" self.store_array_subset(selection, data) diff --git a/tests/test_array_io.py b/tests/test_array_io.py index c6cd20fccc..665cfed844 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -286,20 +286,19 @@ def __dlpack_device__(self) -> tuple[int, int]: def test_zarr_array_io_implements_the_interface() -> None: """`ZarrArrayIO` and `AsyncZarrArrayIO` are `ArrayIO` and `AsyncArrayIO`: they - write data that exports only through DLPack, and read `ArrayResult`s, a selection - of only integers included (as a 0-d array), that export numeric data through - DLPack.""" + write data that exports only through DLPack, and read `ArrayResult`s with the + subset's shape that export numeric data through DLPack.""" array = zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64") io: ArrayIO = ZarrArrayIO.of(array) async_io: AsyncArrayIO = AsyncZarrArrayIO.of(array) io[:] = _DLPackOnly(np.arange(4)) - point = io[1] + point = io[1:2] assert isinstance(io, ArrayIO) assert isinstance(async_io, AsyncArrayIO) assert isinstance(point, ArrayResult) - assert np.asarray(point).shape == () + assert np.asarray(point).shape == (1,) numeric = io[:] assert isinstance(numeric, SupportsDLPack) np.testing.assert_array_equal(np.from_dlpack(numeric), [0, 1, 2, 3]) @@ -341,24 +340,22 @@ def __dlpack_device__(self) -> tuple[int, int]: ("int64", 3, 7), ], ) -def test_integer_reads_keep_the_data_type( +def test_zero_dimensional_reads_keep_the_data_type( dtype: str | type, zarr_format: Literal[2, 3], value: object ) -> None: - """A selection of only integers reads as a 0-d array of the same data type a slice - reads as, with the value intact (a string keeps its trailing NULs); writes take - data with `__array__` as `Array` takes it, even when its DLPack export fails.""" - array = zarr.create_array( - MemoryStore(), shape=(2,), chunks=(2,), dtype=dtype, zarr_format=zarr_format - ) + """A 0-d array reads as a 0-d array of its data type, with the value intact (a + string keeps its trailing NULs); writes take data with `__array__` as `Array` + takes it, even when its DLPack export fails.""" + array = zarr.create_array(MemoryStore(), shape=(), dtype=dtype, zarr_format=zarr_format) io = ZarrArrayIO.of(array) - io[:] = np.asarray([value, value], dtype=np.asarray(array[:]).dtype) + io[...] = np.asarray(value, dtype=array.dtype) floats = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(2,), dtype="float64")) floats[:] = _ArrayWithoutDLPackExport([1.0, np.nan]) - point = np.asarray(io[0]) + point = np.asarray(io[...]) assert point.shape == () - assert point.dtype == np.asarray(io[0:1]).dtype + assert point.dtype == array.dtype assert point.item() == value np.testing.assert_array_equal(np.asarray(floats[:]), [1.0, np.nan]) @@ -391,11 +388,11 @@ def test_store_chunk_refuses_data_beyond_an_edge_chunk() -> None: ("dtype", "selection", "data"), [ ([("x", "i4"), ("y", "f8")], slice(None), [(1, 2.0), (3, 4.0), (5, 6.0), (7, 8.0)]), - ([("x", "i4"), ("y", "f8")], 0, (1, 2.0)), + ([("x", "i4"), ("y", "f8")], slice(0, 1), (1, 2.0)), ([("x", "i4"), ("y", "f8")], slice(None), (1, 2.0)), ("uint8", slice(None), np.arange(4)), ("bool", slice(0, 2), [0, 1]), - ("float32", 1, 1.5), + ("float32", slice(1, 2), 1.5), (" None: + """Integers are not selections, for reads or writes: implementations differ on + whether one keeps its axis.""" + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4, 3), dtype="int64")) + with pytest.raises(TypeError, match="takes slices and Ellipsis"): + io.retrieve_array_subset(selection) + with pytest.raises(TypeError, match="takes slices and Ellipsis"): + io.store_array_subset(selection, 0) + + +def test_selections_refuse_slices_with_a_step() -> None: + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), dtype="int64")) + with pytest.raises(ValueError, match="step of 1"): + io.retrieve_array_subset(slice(0, 4, 2)) + with pytest.raises(ValueError, match="step of 1"): + io.store_array_subset(slice(0, 4, 2), 0) + + def test_store_array_subset_refuses_an_out_of_range_number() -> None: io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(3,), chunks=(3,), dtype="uint8")) with pytest.raises(OverflowError): From ae0e3e1f2dcb50927a4011116d0cd7818f39b92a Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 15:13:20 +0100 Subject: [PATCH 23/31] docs(array): state how ArrayIO slice bounds are read Slice bounds mean what they mean to NumPy (negative bounds count from the end, bounds past the end are clipped, a reversed slice is empty), which zarr-python and zarrista already agree on; the type of a refusal's error is not part of the interface. Tests cover the bounds, booleans, nested tuples and steps of 0 and -1. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- src/zarr/abc/array_io.py | 7 ++++++- tests/test_array_io.py | 39 +++++++++++++++++++++++++++++++++++---- 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/src/zarr/abc/array_io.py b/src/zarr/abc/array_io.py index bff06227c3..e4d66594a4 100644 --- a/src/zarr/abc/array_io.py +++ b/src/zarr/abc/array_io.py @@ -14,7 +14,12 @@ internals: - A selection is an array subset: slices with a step of 1 and `Ellipsis`, and the - data read or written has the subset's shape. Integers are not selections, because + data read or written has the subset's shape. Slice bounds mean what they mean to + NumPy: a negative bound counts from the end, a bound past the end is clipped, and a + slice that ends before it starts is empty. A tuple with fewer entries than + dimensions selects all of the trailing ones. The type of the error an + implementation raises for a selection it refuses is not part of the interface. + Integers are not selections, because implementations differ on whether an integer keeps its axis; select one element of an axis with `slice(i, i + 1)`. NumPy indexing (integers that drop axes, steps, index arrays) belongs to a layer above, such as `zarr.Array`. diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 665cfed844..e36152d0f3 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -409,7 +409,9 @@ def test_store_array_subset_writes_what_array_writes(dtype: Any, selection: Any, np.testing.assert_array_equal(io[:], array[:]) -@pytest.mark.parametrize("selection", [1, np.int64(1), (slice(None), 0), None, [0]]) +@pytest.mark.parametrize( + "selection", [1, np.int64(1), True, (slice(None), 0), None, [0], ((slice(None),),)] +) def test_selections_refuse_anything_but_slices_and_ellipsis(selection: Any) -> None: """Integers are not selections, for reads or writes: implementations differ on whether one keeps its axis.""" @@ -420,12 +422,41 @@ def test_selections_refuse_anything_but_slices_and_ellipsis(selection: Any) -> N io.store_array_subset(selection, 0) -def test_selections_refuse_slices_with_a_step() -> None: +@pytest.mark.parametrize("step", [2, 0, -1]) +def test_selections_refuse_slices_with_a_step(step: int) -> None: io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), dtype="int64")) with pytest.raises(ValueError, match="step of 1"): - io.retrieve_array_subset(slice(0, 4, 2)) + io.retrieve_array_subset(slice(0, 4, step)) with pytest.raises(ValueError, match="step of 1"): - io.store_array_subset(slice(0, 4, 2), 0) + io.store_array_subset(slice(0, 4, step), 0) + + +@pytest.mark.parametrize( + "selection", + [ + (slice(-2, None),), + (slice(None, -1), slice(1, 2)), + slice(2, 100), + slice(3, 1), + (Ellipsis, slice(-1, None)), + slice(None, None, 1), + (), + ], +) +def test_slice_bounds_mean_what_they_mean_to_numpy(selection: Any) -> None: + """Negative bounds count from the end, bounds past the end are clipped, a reversed + slice is empty and missing trailing entries select whole dimensions, for reads and + writes alike.""" + expected = np.arange(12).reshape(4, 3) + io = ZarrArrayIO.of( + zarr.create_array(MemoryStore(), shape=(4, 3), chunks=(2, 2), dtype="int64") + ) + io[...] = expected + + np.testing.assert_array_equal(io[selection], expected[selection]) + io[selection] = -1 + expected[selection] = -1 + np.testing.assert_array_equal(io[...], expected) def test_store_array_subset_refuses_an_out_of_range_number() -> None: From 961ba8f4561d9bc088b892b2f5d1298665d19c78 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 15:45:01 +0100 Subject: [PATCH 24/31] refactor(array): drop path from the ArrayIO protocols Implementations format an array's path differently (zarr-python gives '' and 'g/a', zarrista '/' and '/g/a'), and with the store private a path is about where a store holds the array, so it is an implementation attribute. ZarrArrayIO and AsyncZarrArrayIO keep `path`. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- src/zarr/abc/array_io.py | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/zarr/abc/array_io.py b/src/zarr/abc/array_io.py index e4d66594a4..f366a7ac3c 100644 --- a/src/zarr/abc/array_io.py +++ b/src/zarr/abc/array_io.py @@ -117,11 +117,6 @@ def shape(self) -> Sequence[int]: """The shape of the array.""" ... - @property - def path(self) -> str: - """The array's path in its store.""" - ... - @property def needs_repair(self) -> bool: """Whether chunks cannot be stored until `store_metadata` has stored this @@ -211,11 +206,6 @@ def shape(self) -> Sequence[int]: """See `AsyncArrayIO.shape`.""" ... - @property - def path(self) -> str: - """See `AsyncArrayIO.path`.""" - ... - @property def needs_repair(self) -> bool: """See `AsyncArrayIO.needs_repair`.""" From b3145acdbd9dc799362de0b0c1ab203acd837c4d Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 15:45:14 +0100 Subject: [PATCH 25/31] feat(array): write only exact DLPack arrays through ArrayIO ArrayData is now SupportsDLPack alone, with exactly the region's shape and the array's data type. With Buffer in ArrayData, the same call stored different values: b"12" written to a uint8 array was one value to zarr-python and two raw bytes to zarrista. zarr-python also broadcast scalars and cast data types where zarrista refuses them. ZarrArrayIO refuses lists, scalars, byte buffers and other non-DLPack data and other data types with TypeError, and other shapes with ValueError. NumPy arrays of data types DLPack cannot carry (strings, records) are still written when their data type is the array's. zarr.Array keeps broadcasting and casting. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- src/zarr/abc/array_io.py | 28 ++++---- src/zarr/core/array.py | 108 ++++++++++++++-------------- tests/test_array_io.py | 149 ++++++++++++++++++++++----------------- 3 files changed, 148 insertions(+), 137 deletions(-) diff --git a/src/zarr/abc/array_io.py b/src/zarr/abc/array_io.py index f366a7ac3c..b5c55b96db 100644 --- a/src/zarr/abc/array_io.py +++ b/src/zarr/abc/array_io.py @@ -19,16 +19,17 @@ slice that ends before it starts is empty. A tuple with fewer entries than dimensions selects all of the trailing ones. The type of the error an implementation raises for a selection it refuses is not part of the interface. - Integers are not selections, because - implementations differ on whether an integer keeps its axis; select one element of - an axis with `slice(i, i + 1)`. NumPy indexing (integers that drop axes, steps, - index arrays) belongs to a layer above, such as `zarr.Array`. + Integers are not selections, because implementations differ on whether an integer + keeps its axis; select one element of an axis with `slice(i, i + 1)`. NumPy + indexing (integers that drop axes, steps, index arrays) belongs to a layer above, + such as `zarr.Array`. - Data read comes back as an array that `numpy.asarray` accepts (`ArrayResult`), which may also export through DLPack, for `numpy.from_dlpack` or another library's - `from_dlpack`. Data written is anything that exports through DLPack or the buffer - protocol (`ArrayData`); an implementation may refuse data on a device it cannot - read. A `bytes` object is one value of a bytes data type, as NumPy reads it, not a - buffer of elements. + `from_dlpack`. Data written is an array that exports through DLPack (`ArrayData`), + with exactly the selected region's shape and the array's data type: nothing is + broadcast or cast, so that the same data means the same values to every + implementation. An implementation may refuse data on a device it cannot read, or + of a data type it cannot import (DLPack has no strings, for example). - Chunk indices are non-negative integers, one for each dimension. - Runtime choices are per operation: `read_missing_chunks` on reads, `store_empty_chunks` on writes. Implementations may take more keyword options. @@ -36,7 +37,6 @@ from __future__ import annotations -from collections.abc import Buffer from types import EllipsisType from typing import TYPE_CHECKING, Any, Protocol, Self, runtime_checkable @@ -90,11 +90,11 @@ class ArrayResult(Protocol): def __array__(self, dtype: Any = ..., /, *, copy: bool | None = ...) -> Any: ... -type ArrayData = SupportsDLPack | Buffer -"""Data to write to an array: anything that exports through DLPack or the buffer -protocol, such as a NumPy, CuPy, PyTorch or JAX array, or a `memoryview`. An -implementation may refuse data on a device it cannot read; `bytes` is one value, as -NumPy reads it.""" +type ArrayData = SupportsDLPack +"""Data to write to an array: an array that exports through DLPack, such as a NumPy, +CuPy, PyTorch or JAX array, with exactly the selected region's shape and the array's +data type. An implementation may refuse data on a device it cannot read, or of a data +type it cannot import.""" @runtime_checkable diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index a9895b4fe6..2b600ebead 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -1970,48 +1970,42 @@ def _write_config(store_empty_chunks: bool) -> ArrayConfig: """DLPack's device type for host memory (`kDLCPU`).""" -def _fitted_data(data: npt.ArrayLike | ArrayData, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: - """`data` to write to a region of `shape` of an array of `dtype`, refused with - `ValueError` if it does not broadcast there: writing it would drop values. - - It only checks; the write casts and splits the data as it does for `Array`. A - sequence (a list, a tuple) is read as an array of `dtype` first, as the write reads - it, so a tuple is one record of a structured data type. Leading axes of length 1 - beyond the region's are dropped, as NumPy assignment drops them.""" - if isinstance(data, SupportsDLPack) and not hasattr(data, "__array__"): - # Data that exports only through DLPack. Anything with `__array__` (NumPy, CuPy, - # PyTorch, pyarrow) is written as `Array` writes it, since some of those - # (pyarrow with nulls or strings) cannot export through DLPack. - device = data.__dlpack_device__() - if device[0] != _DLPACK_CPU: - raise TypeError( - f"Data that exports only through DLPack must be in host memory; it is on " - f"DLPack device {device}." - ) - # Viewed as NumPy without a copy. - data = np.from_dlpack(cast("Any", data)) - if hasattr(data, "shape"): - given = tuple(data.shape) - elif np.isscalar(data): - given = () +def _exact_data(data: ArrayData, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: + """`data` to write to a region of `shape` of an array of `dtype`: an array that + exports through DLPack, as every NumPy array does, with exactly that shape and data + type. Nothing is broadcast or cast. Raises `TypeError` for other data or another + data type, and `ValueError` for another shape. + + Host data with `__array__` (NumPy, pyarrow) is read with `numpy.asarray`, since some + of it (strings, pyarrow with nulls) cannot export through DLPack; host data without + it is viewed through `numpy.from_dlpack`. Device data with `__array__` (CuPy) is + passed on as it is, for a device prototype to write.""" + if not isinstance(data, SupportsDLPack): + raise TypeError( + f"Data to write must be an array that exports through DLPack, such as a NumPy " + f"array, not {type(data).__name__}." + ) + device = data.__dlpack_device__() + array: Any + if device[0] == _DLPACK_CPU: + array = np.asarray(data) if hasattr(data, "__array__") else np.from_dlpack(data) + elif hasattr(data, "__array__"): + array = data else: - data = np.asarray(data, dtype=dtype) - given = tuple(data.shape) - trimmed = given - while len(trimmed) > len(shape) and trimmed[0] == 1: - trimmed = trimmed[1:] - try: - broadcast = np.broadcast_shapes(trimmed, shape) - except ValueError: - broadcast = None - if broadcast != shape: - raise ValueError(f"Data of shape {given} does not fit a region of shape {shape}.") - if trimmed != given: - # A view with the same values; inputs without `reshape` (a memoryview) are - # read as arrays, without a copy. - reshapable = data if hasattr(data, "reshape") else np.asarray(data) - data = cast("Any", reshapable).reshape(trimmed) - return data + raise TypeError( + f"Data that exports only through DLPack must be in host memory; it is on " + f"DLPack device {device}." + ) + if tuple(array.shape) != shape: + raise ValueError( + f"Data of shape {tuple(array.shape)} does not match the region's shape {shape}." + ) + if np.dtype(array.dtype) != dtype: + raise TypeError( + f"Data of data type {array.dtype} does not match the array's data type " + f"{dtype}; cast it first." + ) + return array @final @@ -2321,7 +2315,7 @@ async def retrieve_array_subset( async def store_array_subset( self, selection: ArraySubsetSelection, - data: npt.ArrayLike | ArrayData, + data: ArrayData, /, *, store_empty_chunks: bool = False, @@ -2330,15 +2324,17 @@ async def store_array_subset( """Write `data` to the array subset `selection`, which is as for `retrieve_array_subset`. - A chunk left holding only the fill value is deleted from the store, unless - `store_empty_chunks`. Raises `ValueError` if `data` does not broadcast to the - selected region, and `MetadataRepairRequiredError` while `needs_repair` is true; - nothing is written when it raises. Values are cast to the array's data type as - NumPy casts them.""" + `data` is an array that exports through DLPack, such as a NumPy array, with + exactly the region's shape and the array's data type (`TypeError` for other data + or another data type, `ValueError` for another shape); nothing is broadcast or + cast, so cast first (`data.astype(...)`). A chunk left holding only the fill + value is deleted from the store, unless `store_empty_chunks`. Raises + `MetadataRepairRequiredError` while `needs_repair` is true. Nothing is written + when it raises.""" indexer = self._subset_indexer(selection) await self._set_selection( indexer, - _fitted_data(data, self._metadata.dtype.to_native_dtype(), indexer.shape), + _exact_data(data, self._metadata.dtype.to_native_dtype(), indexer.shape), prototype=default_buffer_prototype() if prototype is None else prototype, config=_write_config(store_empty_chunks), ) @@ -2368,7 +2364,7 @@ async def retrieve_chunk( async def store_chunk( self, chunk_indices: Iterable[int], - data: npt.ArrayLike | ArrayData, + data: ArrayData, /, *, store_empty_chunks: bool = False, @@ -2376,8 +2372,8 @@ async def store_chunk( ) -> None: """Encode `data` as the chunk at `chunk_indices` and write it. For a chunk at the array's edge, `data` covers only the part inside the array's shape, as - `retrieve_chunk` gives it. `store_empty_chunks` and errors are as for - `store_array_subset`.""" + `retrieve_chunk` gives it. The data's requirements, `store_empty_chunks` and + errors are as for `store_array_subset`.""" indexer = BlockIndexer( self._chunk_indices(chunk_indices, in_grid=True), self._metadata.shape, @@ -2385,7 +2381,7 @@ async def store_chunk( ) await self._set_selection( indexer, - _fitted_data(data, self._metadata.dtype.to_native_dtype(), indexer.shape), + _exact_data(data, self._metadata.dtype.to_native_dtype(), indexer.shape), prototype=default_buffer_prototype() if prototype is None else prototype, config=_write_config(store_empty_chunks), ) @@ -2678,7 +2674,7 @@ def retrieve_array_subset( def store_array_subset( self, selection: ArraySubsetSelection, - data: npt.ArrayLike | ArrayData, + data: ArrayData, /, *, store_empty_chunks: bool = False, @@ -2709,7 +2705,7 @@ def retrieve_chunk( def store_chunk( self, chunk_indices: Iterable[int], - data: npt.ArrayLike | ArrayData, + data: ArrayData, /, *, store_empty_chunks: bool = False, @@ -2726,9 +2722,7 @@ def __getitem__(self, selection: ArraySubsetSelection, /) -> ArrayResult: """`retrieve_array_subset(selection)`.""" return self.retrieve_array_subset(selection) - def __setitem__( - self, selection: ArraySubsetSelection, data: npt.ArrayLike | ArrayData, / - ) -> None: + def __setitem__(self, selection: ArraySubsetSelection, data: ArrayData, /) -> None: """`store_array_subset(selection, data)`.""" self.store_array_subset(selection, data) diff --git a/tests/test_array_io.py b/tests/test_array_io.py index e36152d0f3..a09a1503c9 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -13,7 +13,7 @@ import zarr from zarr.abc.array_io import ArrayIO, ArrayResult, AsyncArrayIO, SupportsDLPack -from zarr.core.array import AsyncArray, AsyncZarrArrayIO, ZarrArrayIO, _fitted_data +from zarr.core.array import AsyncArray, AsyncZarrArrayIO, ZarrArrayIO from zarr.core.sync import SyncContext, sync from zarr.errors import ChunkNotFoundError, MetadataRepairRequiredError, ZarrUserWarning from zarr.storage import LocalStore, MemoryStore, StorePath @@ -82,7 +82,7 @@ def test_array_io_reads_writes_and_changes_metadata( attrs = {"a": [1]} io[:] = np.arange(4) - io.store_chunk([1], [7, 8]) + io.store_chunk([1], np.asarray([7, 8])) grown = io.with_shape((6,)) stored_before = zarr.open_array(store, path="a").shape labeled = grown.store_metadata().with_attrs(attrs).store_metadata() @@ -127,7 +127,7 @@ def test_store_metadata_stores_the_repair(tmp_path: Path, zarr_format: Literal[2 io = ZarrArrayIO.open(LocalStore(path)) repaired = io.store_metadata() - repaired[:] = [1, 2, 3] + repaired[:] = np.asarray([1, 2, 3], dtype="int16") assert (io.needs_repair, repaired.needs_repair) == (True, False) assert _stored_chunks(path, zarr_format) == [1] @@ -147,7 +147,7 @@ def test_chunks_are_refused_until_the_repair_is_stored( before = {p: p.read_bytes() for p in path.rglob("*") if p.is_file()} with pytest.raises(MetadataRepairRequiredError, match=r"store_metadata\(\)"): - io[:] = [1, 2, 3] + io[:] = np.asarray([1, 2, 3], dtype="int16") assert {p: p.read_bytes() for p in path.rglob("*") if p.is_file()} == before @@ -206,32 +206,12 @@ def test_values_not_taken_from_an_array_ignore_the_global_configuration() -> Non with zarr.config.set({"array.write_empty_chunks": True}): opened = ZarrArrayIO.open(store, "a") made = ZarrArrayIO.from_metadata(array.metadata, store, "a") - opened[0:2] = [0, 0] - made[2:4] = [0, 0] + opened[0:2] = np.zeros(2, dtype="int8") + made[2:4] = np.zeros(2, dtype="int8") assert [key for key in sync(_keys(store)) if key.startswith("a/c")] == [] -@pytest.mark.parametrize( - "data", - [np.arange(1, 5)[None, None], [[[1, 2, 3, 4]]], memoryview(np.arange(1, 5)[None, None])], - ids=["array", "list", "memoryview"], -) -def test_store_array_subset_drops_leading_axes_of_length_one(data: Any) -> None: - """Data with leading axes of length 1 beyond the region's writes as NumPy assignment - writes it, across chunks.""" - io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) - io[:] = data - np.testing.assert_array_equal(io[:], [1, 2, 3, 4]) - - -def test_write_data_is_checked_not_broadcast() -> None: - """A 0-d input is handed to the write as it is, not broadcast or cast over the - region: the write casts it once, and sharding keeps its fast path for scalars.""" - data = np.array(2.0) - assert _fitted_data(data, np.dtype("int64"), (10**12,)) is data - - def test_runtime_choices_are_made_per_call() -> None: """Whether an all-fill-value chunk is stored, and whether a missing chunk reads as the fill value, are chosen by each call, whatever the array the value was taken @@ -247,11 +227,12 @@ def test_runtime_choices_are_made_per_call() -> None: ) io = ZarrArrayIO.of(array) - io[:, 0:2] = 0 - io.store_array_subset((slice(None), slice(2, 4)), 0, store_empty_chunks=True) + zeros = np.zeros((2, 2), dtype="int8") + io[:, 0:2] = zeros + io.store_array_subset((slice(None), slice(2, 4)), zeros, store_empty_chunks=True) stored = sorted(key for key in sync(_keys(store)) if key.startswith("a/c")) - io.store_chunk([0, 0], np.zeros((2, 2)), store_empty_chunks=True) - io.store_chunk([0, 1], np.zeros((2, 2))) + io.store_chunk([0, 0], zeros, store_empty_chunks=True) + io.store_chunk([0, 1], zeros) restored = sorted(key for key in sync(_keys(store)) if key.startswith("a/c")) assert (stored, restored) == (["a/c/0/1"], ["a/c/0/0"]) @@ -344,8 +325,8 @@ def test_zero_dimensional_reads_keep_the_data_type( dtype: str | type, zarr_format: Literal[2, 3], value: object ) -> None: """A 0-d array reads as a 0-d array of its data type, with the value intact (a - string keeps its trailing NULs); writes take data with `__array__` as `Array` - takes it, even when its DLPack export fails.""" + string keeps its trailing NULs); writes take host data with `__array__` through it, + even when its DLPack export fails.""" array = zarr.create_array(MemoryStore(), shape=(), dtype=dtype, zarr_format=zarr_format) io = ZarrArrayIO.of(array) io[...] = np.asarray(value, dtype=array.dtype) @@ -366,45 +347,87 @@ def test_store_array_subset_refuses_dlpack_only_data_off_the_host() -> None: io[:] = cast("Any", _DLPackOnlyOnDevice()) -def test_store_array_subset_refuses_data_that_does_not_fit() -> None: - io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) - with pytest.raises(ValueError, match=r"shape \(1, 3\) does not fit"): - io[0:2] = [[5, 6, 7]] - - -def test_store_array_subset_refuses_a_memoryview_that_does_not_fit() -> None: +@pytest.mark.parametrize( + ("region", "data"), + [ + (slice(0, 2), np.asarray([[5, 6]])), + (slice(0, 2), np.arange(3)), + (slice(0, 2), np.asarray(5)), + (slice(0, 1), np.asarray(5)), + ], + ids=["leading-axis", "longer", "scalar", "one-element-scalar"], +) +def test_store_array_subset_refuses_data_of_another_shape(region: slice, data: Any) -> None: + """Data is not broadcast, and leading axes of length 1 are not dropped.""" io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) - with pytest.raises(ValueError, match=r"shape \(3,\) does not fit"): - io[0:2] = memoryview(np.arange(3)) + with pytest.raises(ValueError, match="does not match the region's shape"): + io[region] = data def test_store_chunk_refuses_data_beyond_an_edge_chunk() -> None: io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(5,), chunks=(2,), dtype="int64")) - with pytest.raises(ValueError, match="does not fit"): - io.store_chunk([2], [1, 2]) + with pytest.raises(ValueError, match="does not match the region's shape"): + io.store_chunk([2], np.asarray([1, 2])) @pytest.mark.parametrize( - ("dtype", "selection", "data"), + "data", + [[1, 2], (1, 2), 1, b"12", bytearray(b"12"), memoryview(np.arange(2))], + ids=["list", "tuple", "int", "bytes", "bytearray", "memoryview"], +) +def test_store_array_subset_refuses_data_that_is_not_a_dlpack_array(data: Any) -> None: + """Only arrays are written: what a list, a scalar or a byte buffer means differs + between implementations (`b"12"` is one value to NumPy and two bytes to zarrs).""" + io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(2,), dtype="uint8")) + with pytest.raises(TypeError, match="must be an array that exports through DLPack"): + io[:] = data + with pytest.raises(TypeError, match="must be an array that exports through DLPack"): + io.store_chunk([0], data) + + +@pytest.mark.parametrize( + ("dtype", "zarr_format", "data"), [ - ([("x", "i4"), ("y", "f8")], slice(None), [(1, 2.0), (3, 4.0), (5, 6.0), (7, 8.0)]), - ([("x", "i4"), ("y", "f8")], slice(0, 1), (1, 2.0)), - ([("x", "i4"), ("y", "f8")], slice(None), (1, 2.0)), - ("uint8", slice(None), np.arange(4)), - ("bool", slice(0, 2), [0, 1]), - ("float32", slice(1, 2), 1.5), - ("i4", 2, np.asarray([1, 2], dtype=" None: - """`store_array_subset` writes every value `Array` writes for the same selection, - structured records included, and stores the same result.""" +def test_store_array_subset_refuses_data_of_another_data_type( + dtype: Any, zarr_format: Literal[2, 3], data: Any +) -> None: + """Data is not cast, not even when the cast is safe.""" + io = ZarrArrayIO.of( + zarr.create_array(MemoryStore(), shape=(2,), dtype=dtype, zarr_format=zarr_format) + ) + with pytest.raises(TypeError, match="does not match the array's data type"): + io[:] = data + + +@pytest.mark.parametrize( + ("dtype", "data"), + [ + ([("x", "i4"), ("y", "f8")], [(1, 2.0), (3, 4.0), (5, 6.0), (7, 8.0)]), + ("uint8", [0, 1, 2, 3]), + ("bool", [False, True, True, False]), + ("float32", [1.5, 0.0, -2.0, 3.0]), + (" None: + """An array of the array's own data type is written as `Array` writes it, data types + DLPack cannot carry (records, strings) included, across chunks.""" io_store, array_store = MemoryStore(), MemoryStore() io = ZarrArrayIO.of(zarr.create_array(io_store, shape=(4,), chunks=(2,), dtype=dtype)) array = zarr.create_array(array_store, shape=(4,), chunks=(2,), dtype=dtype) - io[selection] = data - array[selection] = data + io[:] = np.asarray(data, dtype=array.dtype) + io[1:3] = np.asarray(data[:2], dtype=array.dtype) + array[:] = data + array[1:3] = data[:2] np.testing.assert_array_equal(io[:], array[:]) @@ -419,7 +442,7 @@ def test_selections_refuse_anything_but_slices_and_ellipsis(selection: Any) -> N with pytest.raises(TypeError, match="takes slices and Ellipsis"): io.retrieve_array_subset(selection) with pytest.raises(TypeError, match="takes slices and Ellipsis"): - io.store_array_subset(selection, 0) + io.store_array_subset(selection, np.asarray(0)) @pytest.mark.parametrize("step", [2, 0, -1]) @@ -428,7 +451,7 @@ def test_selections_refuse_slices_with_a_step(step: int) -> None: with pytest.raises(ValueError, match="step of 1"): io.retrieve_array_subset(slice(0, 4, step)) with pytest.raises(ValueError, match="step of 1"): - io.store_array_subset(slice(0, 4, step), 0) + io.store_array_subset(slice(0, 4, step), np.asarray(0)) @pytest.mark.parametrize( @@ -454,17 +477,11 @@ def test_slice_bounds_mean_what_they_mean_to_numpy(selection: Any) -> None: io[...] = expected np.testing.assert_array_equal(io[selection], expected[selection]) - io[selection] = -1 + io[selection] = np.full_like(expected[selection], -1) expected[selection] = -1 np.testing.assert_array_equal(io[...], expected) -def test_store_array_subset_refuses_an_out_of_range_number() -> None: - io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(3,), chunks=(3,), dtype="uint8")) - with pytest.raises(OverflowError): - io[:] = [1, 300, 2] - - def test_chunk_indices_must_be_non_negative() -> None: io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) with pytest.raises(ValueError, match="non-negative"): @@ -485,7 +502,7 @@ def test_chunk_indices_are_not_booleans() -> None: def test_chunk_indices_may_be_any_iterable() -> None: io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(4,), chunks=(2,), dtype="int64")) - io.store_chunk((index for index in (1,)), [7, 8]) + io.store_chunk((index for index in (1,)), np.asarray([7, 8])) np.testing.assert_array_equal(io.retrieve_chunk(iter([1])), [7, 8]) From 30a7a76e73c41c127b79774591ed07a492202c2f Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 15:52:08 +0100 Subject: [PATCH 26/31] fix(array): accept ArrayIO write data in either byte order The data-type check compared byte order, so on Zarr format 3 (where byte order belongs to the bytes codec) the accepted order depended on how the value was made: ZarrArrayIO.of(array) refused native data for an array created as ">i4", and ZarrArrayIO.open refused ">i4" data for the same stored array. Byte order changes no value and DLPack carries only native order, so data types now compare in native byte order. A data type NumPy cannot read (a device tensor's) is refused with a clear TypeError. The protocol now also says an implementation may refuse data not in C order, and that chunks outside the chunk grid are not part of the interface. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- src/zarr/abc/array_io.py | 10 +++++++--- src/zarr/core/array.py | 31 +++++++++++++++++++++++-------- tests/test_array_io.py | 34 +++++++++++++++++++++++++++++++++- 3 files changed, 63 insertions(+), 12 deletions(-) diff --git a/src/zarr/abc/array_io.py b/src/zarr/abc/array_io.py index b5c55b96db..0335cf8cb8 100644 --- a/src/zarr/abc/array_io.py +++ b/src/zarr/abc/array_io.py @@ -28,9 +28,13 @@ `from_dlpack`. Data written is an array that exports through DLPack (`ArrayData`), with exactly the selected region's shape and the array's data type: nothing is broadcast or cast, so that the same data means the same values to every - implementation. An implementation may refuse data on a device it cannot read, or - of a data type it cannot import (DLPack has no strings, for example). -- Chunk indices are non-negative integers, one for each dimension. + implementation. Byte order is not part of the data type; DLPack carries native + byte order, which every implementation reads. An implementation may refuse data it + cannot import: on a device it cannot read, of a data type or byte order it does not + take (DLPack has no strings, for example), or not in C order. Refusals differ + between implementations; values written do not. +- Chunk indices are non-negative integers, one for each dimension. Reading or + writing a chunk outside the chunk grid is not part of the interface. - Runtime choices are per operation: `read_missing_chunks` on reads, `store_empty_chunks` on writes. Implementations may take more keyword options. """ diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 2b600ebead..abc4263127 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -1970,16 +1970,24 @@ def _write_config(store_empty_chunks: bool) -> ArrayConfig: """DLPack's device type for host memory (`kDLCPU`).""" +def _in_native_byte_order(dtype: np.dtype[Any]) -> np.dtype[Any]: + """`dtype` in native byte order, fields included.""" + return dtype if dtype.isnative else dtype.newbyteorder("=") + + def _exact_data(data: ArrayData, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: """`data` to write to a region of `shape` of an array of `dtype`: an array that exports through DLPack, as every NumPy array does, with exactly that shape and data - type. Nothing is broadcast or cast. Raises `TypeError` for other data or another - data type, and `ValueError` for another shape. - - Host data with `__array__` (NumPy, pyarrow) is read with `numpy.asarray`, since some - of it (strings, pyarrow with nulls) cannot export through DLPack; host data without - it is viewed through `numpy.from_dlpack`. Device data with `__array__` (CuPy) is - passed on as it is, for a device prototype to write.""" + type. Byte order is not part of the data type: it changes no value, and DLPack + carries only native byte order, so data in either order is written. Nothing is + broadcast or cast. Raises `TypeError` for other data or another data type, and + `ValueError` for another shape. + + Host data with `__array__` is read with `numpy.asarray`, as that data's own NumPy + view, since some of it (NumPy string and record arrays, non-native byte order) + cannot export through DLPack; host data without it is viewed through + `numpy.from_dlpack`. Device data with `__array__` (CuPy) is passed on as it is, for a + device prototype to write.""" if not isinstance(data, SupportsDLPack): raise TypeError( f"Data to write must be an array that exports through DLPack, such as a NumPy " @@ -2000,7 +2008,14 @@ def _exact_data(data: ArrayData, dtype: TBaseDType, shape: tuple[int, ...]) -> A raise ValueError( f"Data of shape {tuple(array.shape)} does not match the region's shape {shape}." ) - if np.dtype(array.dtype) != dtype: + try: + given = np.dtype(array.dtype) + except TypeError: + raise TypeError( + f"Data of data type {array.dtype}, which NumPy cannot read, does not match the " + f"array's data type {dtype}." + ) from None + if _in_native_byte_order(given) != _in_native_byte_order(np.dtype(dtype)): raise TypeError( f"Data of data type {array.dtype} does not match the array's data type " f"{dtype}; cast it first." diff --git a/tests/test_array_io.py b/tests/test_array_io.py index a09a1503c9..2e6c800e46 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -391,7 +391,7 @@ def test_store_array_subset_refuses_data_that_is_not_a_dlpack_array(data: Any) - ("int64", 3, np.asarray([1.0, 2.0])), ("int64", 3, np.asarray([1, 2], dtype="int32")), ("uint8", 3, np.asarray([1, 300])), - (">i4", 2, np.asarray([1, 2], dtype="i4", 2, np.asarray([1, 2], dtype=">i8")), (str, 3, np.asarray(["a", "b"])), ], ) @@ -406,6 +406,38 @@ def test_store_array_subset_refuses_data_of_another_data_type( io[:] = data +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("made_by", ["of", "open"]) +@pytest.mark.parametrize( + ("array_dtype", "data"), + [ + (">i4", np.asarray([1, 2], dtype="i4", np.asarray([1, 2], dtype=">i4")), + (">f8", np.asarray([1.5, 2.5], dtype="U2", np.asarray(["ab", "c"], dtype="i4"), ("y", "f8")]), + ), + ], +) +def test_store_array_subset_writes_data_in_either_byte_order( + zarr_format: Literal[2, 3], made_by: str, array_dtype: Any, data: Any +) -> None: + """Byte order is not part of the data type, however the value was made: data in + either order writes the same values, and what one value reads another writes.""" + store = MemoryStore() + array = zarr.create_array(store, shape=(2,), dtype=array_dtype, zarr_format=zarr_format) + io = ZarrArrayIO.of(array) if made_by == "of" else ZarrArrayIO.open(store) + + io[:] = data + ZarrArrayIO.open(store)[:] = np.asarray(ZarrArrayIO.of(array)[:]) + + np.testing.assert_array_equal(np.asarray(io[:]), data) + np.testing.assert_array_equal(array[:], data) + + @pytest.mark.parametrize( ("dtype", "data"), [ From 928e55ba39595ecaf8b24d76da6712be49d6e4af Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 16:00:38 +0100 Subject: [PATCH 27/31] feat(array): read and write ArrayIO chunks in their full shape A chunk at the array's edge is now read and written in the chunk's full shape, padding included, as zarrs does: retrieve_chunk returns the full chunk with the part past the array's shape read as the fill value, and store_chunk takes the full chunk and stores only the part inside the array. Before, zarr-python gave and took only the part inside, so the same call returned different shapes from ZarrArrayIO and zarrista (for sharded and transposed arrays too). What the padding of a stored chunk reads as is not part of the interface. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- src/zarr/abc/array_io.py | 10 ++++-- src/zarr/core/array.py | 71 +++++++++++++++++++++++++++++----------- tests/test_array_io.py | 47 ++++++++++++++++++++++++-- 3 files changed, 104 insertions(+), 24 deletions(-) diff --git a/src/zarr/abc/array_io.py b/src/zarr/abc/array_io.py index 0335cf8cb8..672829dc7a 100644 --- a/src/zarr/abc/array_io.py +++ b/src/zarr/abc/array_io.py @@ -34,7 +34,11 @@ take (DLPack has no strings, for example), or not in C order. Refusals differ between implementations; values written do not. - Chunk indices are non-negative integers, one for each dimension. Reading or - writing a chunk outside the chunk grid is not part of the interface. + writing a chunk outside the chunk grid is not part of the interface. A chunk is + read and written in its full shape, as zarrs reads and writes it: a chunk at the + array's edge includes the part past the array's shape. What that part reads as + for a stored chunk is not part of the interface (a missing chunk reads as the fill + value there as everywhere). - Runtime choices are per operation: `read_missing_chunks` on reads, `store_empty_chunks` on writes. Implementations may take more keyword options. """ @@ -171,7 +175,7 @@ async def store_array_subset( async def retrieve_chunk( self, chunk_indices: Sequence[int], /, *, read_missing_chunks: bool = True ) -> ArrayResult: - """The values of the chunk at `chunk_indices`.""" + """The values of the chunk at `chunk_indices`, in the chunk's full shape.""" ... async def store_chunk( @@ -182,7 +186,7 @@ async def store_chunk( *, store_empty_chunks: bool = False, ) -> None: - """Write `data` as the chunk at `chunk_indices`.""" + """Write `data`, in the chunk's full shape, as the chunk at `chunk_indices`.""" ... async def __getitem__(self, selection: Selection, /) -> ArrayResult: diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index abc4263127..514a433f21 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -2362,19 +2362,31 @@ async def retrieve_chunk( read_missing_chunks: bool = True, prototype: BufferPrototype | None = None, ) -> ArrayResult: - """The decoded values of the chunk at `chunk_indices`, within the array: a chunk - at the array's edge gives only the part inside the array's shape. A missing - chunk is handled as `retrieve_array_subset` handles it.""" - indexer = BlockIndexer( - self._chunk_indices(chunk_indices, in_grid=True), - self._metadata.shape, - self._chunk_grid, + """The decoded values of the chunk at `chunk_indices`, in the chunk's full shape, + as zarrs reads it: a chunk at the array's edge includes the part past the array's + shape, which reads as the fill value. A missing chunk is handled as + `retrieve_array_subset` handles it.""" + indices = self._chunk_indices(chunk_indices, in_grid=True) + prototype = default_buffer_prototype() if prototype is None else prototype + indexer = BlockIndexer(indices, self._metadata.shape, self._chunk_grid) + inside = self._chunk_inside(indices) + if inside is None: + return await self._retrieve( + indexer, prototype=prototype, read_missing_chunks=read_missing_chunks + ) + full_shape, region = inside + out = prototype.nd_buffer.create( + shape=full_shape, + dtype=self._metadata.dtype.to_native_dtype(), + fill_value=self._fill_value(), ) - return await self._retrieve( + await self._get_selection( indexer, - prototype=default_buffer_prototype() if prototype is None else prototype, - read_missing_chunks=read_missing_chunks, + prototype=prototype, + out=out[region], + config=_read_config(read_missing_chunks), ) + return cast("ArrayResult", out.as_ndarray_like()) async def store_chunk( self, @@ -2385,22 +2397,43 @@ async def store_chunk( store_empty_chunks: bool = False, prototype: BufferPrototype | None = None, ) -> None: - """Encode `data` as the chunk at `chunk_indices` and write it. For a chunk at - the array's edge, `data` covers only the part inside the array's shape, as - `retrieve_chunk` gives it. The data's requirements, `store_empty_chunks` and + """Encode `data` as the chunk at `chunk_indices` and write it. `data` has the + chunk's full shape, as `retrieve_chunk` gives it and as zarrs takes it; for a + chunk at the array's edge, the part past the array's shape is not stored (it + reads as the fill value). The data's requirements, `store_empty_chunks` and errors are as for `store_array_subset`.""" - indexer = BlockIndexer( - self._chunk_indices(chunk_indices, in_grid=True), - self._metadata.shape, - self._chunk_grid, - ) + indices = self._chunk_indices(chunk_indices, in_grid=True) + indexer = BlockIndexer(indices, self._metadata.shape, self._chunk_grid) + inside = self._chunk_inside(indices) + dtype = self._metadata.dtype.to_native_dtype() + if inside is None: + value = _exact_data(data, dtype, indexer.shape) + else: + full_shape, region = inside + value = _exact_data(data, dtype, full_shape)[region] await self._set_selection( indexer, - _exact_data(data, self._metadata.dtype.to_native_dtype(), indexer.shape), + value, prototype=default_buffer_prototype() if prototype is None else prototype, config=_write_config(store_empty_chunks), ) + def _chunk_inside( + self, indices: tuple[int, ...] + ) -> tuple[tuple[int, ...], tuple[slice, ...]] | None: + """For a chunk that extends past the array's shape, its full shape and the + region of it inside the array; `None` for a chunk wholly inside.""" + spec = self._chunk_grid[indices] + if spec is None or not spec.is_boundary: + return None + return spec.codec_shape, tuple(slice(0, extent) for extent in spec.shape) + + def _fill_value(self) -> Any: + """The array's fill value as a scalar of its data type; a Zarr format 2 array + without one reads as the data type's default.""" + fill_value = self._metadata.fill_value + return self._metadata.dtype.default_scalar() if fill_value is None else fill_value + async def __getitem__(self, selection: ArraySubsetSelection, /) -> ArrayResult: """`retrieve_array_subset(selection)`.""" return await self.retrieve_array_subset(selection) diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 2e6c800e46..889d1081c1 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -364,10 +364,53 @@ def test_store_array_subset_refuses_data_of_another_shape(region: slice, data: A io[region] = data -def test_store_chunk_refuses_data_beyond_an_edge_chunk() -> None: +def test_store_chunk_refuses_data_of_only_the_inside_of_an_edge_chunk() -> None: io = ZarrArrayIO.of(zarr.create_array(MemoryStore(), shape=(5,), chunks=(2,), dtype="int64")) with pytest.raises(ValueError, match="does not match the region's shape"): - io.store_chunk([2], np.asarray([1, 2])) + io.store_chunk([2], np.asarray([1])) + + +@pytest.mark.parametrize( + ("layout", "chunk", "full_shape"), + [ + ({"chunks": (2, 2)}, (2, 1), (2, 2)), + ({"chunks": (2, 2)}, (1, 0), (2, 2)), + ({"shards": (4, 4), "chunks": (2, 2)}, (1, 0), (4, 4)), + ( + { + "chunks": (2, 2), + "filters": [{"name": "transpose", "configuration": {"order": [1, 0]}}], + }, + (2, 1), + (2, 2), + ), + ], + ids=["edge", "inside", "sharded-edge", "transposed-edge"], +) +def test_chunks_are_read_and_written_in_their_full_shape( + layout: dict[str, Any], chunk: tuple[int, int], full_shape: tuple[int, int] +) -> None: + """A chunk has its full shape, as zarrs gives it: past the array's edge it reads as + the fill value, and data written there is not stored.""" + io = ZarrArrayIO.of( + zarr.create_array(MemoryStore(), shape=(5, 3), dtype="int64", fill_value=-1, **layout) + ) + io[...] = np.arange(15).reshape(5, 3) + region = tuple( + slice(i * n, min((i + 1) * n, extent)) + for i, n, extent in zip(chunk, full_shape, (5, 3), strict=True) + ) + expected = np.full(full_shape, -1) + inside = tuple(slice(0, s.stop - s.start) for s in region) + expected[inside] = np.arange(15).reshape(5, 3)[region] + + read = np.asarray(io.retrieve_chunk(chunk)) + io.store_chunk(chunk, np.full(full_shape, 7)) + + np.testing.assert_array_equal(read, expected) + np.testing.assert_array_equal(np.asarray(io[region]), np.full(expected[inside].shape, 7)) + expected[inside] = 7 + np.testing.assert_array_equal(np.asarray(io.retrieve_chunk(chunk)), expected) @pytest.mark.parametrize( From 65221197427d3015f521148f982224c591932e1d Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 16:00:50 +0100 Subject: [PATCH 28/31] test(array): check ZarrArrayIO against zarrista The same ArrayIO calls on the same stored array, through ZarrArrayIO and zarrista, must read the same values, subsets and chunks, store the same chunk keys, and refuse the same data: 7 data types across regular, big-endian, transposed and sharded layouts, with whole, partial, clipped and empty writes, a full edge chunk, an all-fill chunk and an erase. zarrista 0.1.0 joins the test dependency group on platforms it has wheels for; the test is skipped where it is absent. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 2 + tests/test_array_io_zarrista.py | 194 ++++++++++++++++++++++++++++++++ uv.lock | 45 ++++++++ 3 files changed, 241 insertions(+) create mode 100644 tests/test_array_io_zarrista.py diff --git a/pyproject.toml b/pyproject.toml index 839b5fdef8..44c548f5d9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -122,6 +122,8 @@ test = [ "pytest-benchmark==5.3.1", "pytest-codspeed==5.0.4", "uv==0.13.7", + # tests/test_array_io_zarrista.py checks ZarrArrayIO against it; wheels only. + "zarrista==0.1.0; platform_machine in 'x86_64 AMD64 arm64 aarch64'", ] remote-tests = [ {include-group = "test"}, diff --git a/tests/test_array_io_zarrista.py b/tests/test_array_io_zarrista.py new file mode 100644 index 0000000000..0b1495b556 --- /dev/null +++ b/tests/test_array_io_zarrista.py @@ -0,0 +1,194 @@ +"""`ZarrArrayIO` against zarrista, a zarrs-based implementation of the same interface. + +The same calls on the same stored array must give the same values, store the same +chunk keys, and refuse the same data. zarrista's `store_chunk` takes `ArrayBytes` +and its chunk indices are lists, so the test translates those two; everything else +is called as the interface has it. +""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +from zarr.core.array import ZarrArrayIO +from zarr.storage import LocalStore + +if TYPE_CHECKING: + from pathlib import Path + +zarrista = pytest.importorskip("zarrista") + +_SHAPE = (5, 3) +_BYTES = {"name": "bytes", "configuration": {"endian": "little"}} +_LAYOUTS: dict[str, tuple[list[int], list[dict[str, Any]]]] = { + "regular": ([2, 2], [_BYTES]), + "big-endian": ([2, 2], [{"name": "bytes", "configuration": {"endian": "big"}}]), + "transposed": ( + [2, 2], + [{"name": "transpose", "configuration": {"order": [1, 0]}}, _BYTES], + ), + "sharded": ( + [4, 4], + [ + { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": [2, 2], + "codecs": [_BYTES], + "index_codecs": [_BYTES, {"name": "crc32c"}], + "index_location": "end", + }, + } + ], + ), +} +_DATA_TYPES = [ + ("int8", -1), + ("uint16", 0), + ("int32", 7), + ("int64", 0), + ("float32", 0.5), + ("float64", 0.0), + ("bool", False), +] + + +class _Zarrista: + """A zarrista array with zarr-python's spelling of `store_chunk` and chunk indices.""" + + def __init__(self, array: Any) -> None: + self._array = array + + def __getitem__(self, selection: Any) -> Any: + return self._array[selection] + + def __setitem__(self, selection: Any, data: Any) -> None: + self._array[selection] = data + + def retrieve_chunk(self, indices: tuple[int, ...]) -> Any: + return self._array.retrieve_chunk(list(indices)) + + def store_chunk(self, indices: tuple[int, ...], data: np.ndarray[Any, Any]) -> None: + self._array.store_chunk(list(indices), zarrista.ArrayBytes(data.tobytes())) + + def erase_chunk(self, indices: tuple[int, ...]) -> None: + self._array.erase_chunk(list(indices)) + + +def _metadata(dtype: str, fill_value: Any, layout: str) -> dict[str, Any]: + chunk_shape, codecs = _LAYOUTS[layout] + return { + "zarr_format": 3, + "node_type": "array", + "shape": list(_SHAPE), + "data_type": dtype, + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": chunk_shape}}, + "chunk_key_encoding": {"name": "default", "configuration": {"separator": "/"}}, + "fill_value": fill_value, + "codecs": codecs, + "attributes": {}, + } + + +def _open_both(tmp_path: Path, metadata: dict[str, Any]) -> tuple[Any, Any, Path, Path]: + roots = (tmp_path / "zarr-python", tmp_path / "zarrista") + for root in roots: + (root / "a").mkdir(parents=True) + (root / "a" / "zarr.json").write_text(json.dumps(metadata)) + ours = ZarrArrayIO.open(LocalStore(roots[0]), "a") + theirs = _Zarrista(zarrista.Array.open(zarrista.store.FilesystemStore(str(roots[1])), "/a")) + return ours, theirs, *roots + + +def _chunk_keys(root: Path) -> list[str]: + return sorted( + str(path.relative_to(root)) + for path in root.rglob("*") + if path.is_file() and path.name != "zarr.json" + ) + + +def _values(rng: np.random.Generator, dtype: str, shape: tuple[int, ...]) -> np.ndarray[Any, Any]: + if dtype == "bool": + return rng.integers(0, 2, size=shape).astype(bool) + info = np.iinfo(dtype) if np.dtype(dtype).kind in "iu" else None + if info is None: + return rng.normal(size=shape).astype(dtype) + return rng.integers(info.min, info.max, size=shape, dtype=dtype, endpoint=True) + + +def _assert_same(ours: Any, theirs: Any, roots: tuple[Path, Path], grid: tuple[int, ...]) -> None: + np.testing.assert_array_equal(np.asarray(ours[...]), np.asarray(theirs[...]), strict=True) + for selection in [(slice(1, 3), slice(-2, None)), (slice(3, 100),), (slice(2, 2),), ()]: + np.testing.assert_array_equal( + np.asarray(ours[selection]), np.asarray(theirs[selection]), strict=True + ) + for indices in np.ndindex(*grid): + np.testing.assert_array_equal( + np.asarray(ours.retrieve_chunk(indices)), + np.asarray(theirs.retrieve_chunk(indices)), + strict=True, + ) + assert _chunk_keys(roots[0]) == _chunk_keys(roots[1]) + + +@pytest.mark.parametrize("layout", list(_LAYOUTS)) +@pytest.mark.parametrize(("dtype", "fill_value"), _DATA_TYPES) +def test_writes_and_reads_match_zarrista( + tmp_path: Path, layout: str, dtype: str, fill_value: Any +) -> None: + """After each write (whole array, partial, clipped and empty subsets, a full edge + chunk, an all-fill chunk, an erase), both read the same values, subsets and chunks, + and store the same chunk keys.""" + ours, theirs, *roots = _open_both(tmp_path, _metadata(dtype, fill_value, layout)) + chunk_shape = tuple(_LAYOUTS[layout][0]) + grid = tuple(-(-extent // size) for extent, size in zip(_SHAPE, chunk_shape, strict=True)) + edge = tuple(n - 1 for n in grid) + edge_inside = tuple( + extent - index * size for extent, index, size in zip(_SHAPE, edge, chunk_shape, strict=True) + ) + fill = np.full((), fill_value, dtype=dtype) + rng = np.random.default_rng(0) + + def write_subset(selection: Any, shape: tuple[int, ...]) -> None: + data = _values(rng, dtype, shape) + ours[selection] = data + theirs[selection] = data + + def write_chunk(indices: tuple[int, ...], data: np.ndarray[Any, Any]) -> None: + ours.store_chunk(indices, data) + theirs.store_chunk(indices, data) + + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + write_subset(..., _SHAPE) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + write_subset((slice(1, 3), slice(-2, None)), (2, 2)) + write_subset((slice(3, 100),), (2, 3)) + write_subset((slice(2, 2),), (0, 3)) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + # A full edge chunk whose part past the array's edge holds the fill value. + edge_chunk = np.full(chunk_shape, fill, dtype=dtype) + edge_chunk[tuple(slice(0, n) for n in edge_inside)] = _values(rng, dtype, edge_inside) + write_chunk(edge, edge_chunk) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + write_chunk((0,) * len(grid), np.full(chunk_shape, fill, dtype=dtype)) + ours.erase_chunk(edge) + theirs.erase_chunk(edge) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + + +@pytest.mark.parametrize( + "data", + [np.zeros((5, 3), dtype="int32"), np.zeros((5, 2), dtype="int64"), np.zeros((), "int64")], + ids=["data-type", "shape", "scalar"], +) +def test_both_refuse_data_that_is_not_exactly_the_region(tmp_path: Path, data: Any) -> None: + ours, theirs, *_ = _open_both(tmp_path, _metadata("int64", 0, "regular")) + with pytest.raises((TypeError, ValueError)): + ours[...] = data + with pytest.raises(Exception): # noqa: B017 + theirs[...] = data diff --git a/uv.lock b/uv.lock index 7efabdf939..22acbded6f 100644 --- a/uv.lock +++ b/uv.lock @@ -3862,6 +3862,7 @@ dev = [ { name = "towncrier" }, { name = "universal-pathlib" }, { name = "uv" }, + { name = "zarrista", marker = "platform_machine in 'x86_64 AMD64 arm64 aarch64'" }, ] docs = [ { name = "astroid" }, @@ -3900,6 +3901,7 @@ remote-tests = [ { name = "requests" }, { name = "s3fs" }, { name = "uv" }, + { name = "zarrista", marker = "platform_machine in 'x86_64 AMD64 arm64 aarch64'" }, ] test = [ { name = "coverage" }, @@ -3913,6 +3915,7 @@ test = [ { name = "pytest-reportlog" }, { name = "pytest-xdist" }, { name = "uv" }, + { name = "zarrista", marker = "platform_machine in 'x86_64 AMD64 arm64 aarch64'" }, ] [package.metadata] @@ -3966,6 +3969,7 @@ dev = [ { name = "towncrier", specifier = "==26.9.0" }, { name = "universal-pathlib" }, { name = "uv", specifier = "==0.13.7" }, + { name = "zarrista", marker = "platform_machine in 'x86_64 AMD64 arm64 aarch64'", specifier = "==0.1.0" }, ] docs = [ { name = "astroid", specifier = "==4.3.4" }, @@ -4002,6 +4006,7 @@ remote-tests = [ { name = "requests", specifier = "==2.34.2" }, { name = "s3fs", specifier = ">=2023.10.0" }, { name = "uv", specifier = "==0.13.7" }, + { name = "zarrista", marker = "platform_machine in 'x86_64 AMD64 arm64 aarch64'", specifier = "==0.1.0" }, ] test = [ { name = "coverage", specifier = "==7.17.2" }, @@ -4015,4 +4020,44 @@ test = [ { name = "pytest-reportlog", specifier = "==1.0.0" }, { name = "pytest-xdist", specifier = "==3.8.0" }, { name = "uv", specifier = "==0.13.7" }, + { name = "zarrista", marker = "platform_machine in 'x86_64 AMD64 arm64 aarch64'", specifier = "==0.1.0" }, +] + +[[package]] +name = "zarr-metadata" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7f/5d/5f1778697e0022d5cf7b215554a96827949a1d065b51913059b83b770ab3/zarr_metadata-0.9.0.tar.gz", hash = "sha256:7c7612ccb0177f2d1abb05cc38cdb89a54f31558edccf78d848a1c68d95415f7", size = 616077, upload-time = "2026-11-16T13:12:44.238Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/35/26/c1eb0a10cbbe9cc7d759ee66261f2461f09e964359dd4d3e6a0c74824bba/zarr_metadata-0.9.0-py3-none-any.whl", hash = "sha256:61714b08a7eacd4bef4e1ccc485e331de2ac5b7afda624094a711e474641338a", size = 339074, upload-time = "2026-11-16T13:12:42.616Z" }, +] + +[[package]] +name = "zarrista" +version = "0.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "zarr-metadata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d7/c8/0f2c439bf922685b7febd3add98093e778d9f00f53bc03a1d9fdcc906ce3/zarrista-0.1.0.tar.gz", hash = "sha256:6b2a7a05a4abb062824cee8fad023c6b34041b73b600733ea4c1404fd243a669", size = 375969, upload-time = "2026-08-13T14:44:45.517Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/8a/d2d3a23d19168d8d034cdda5b512344558e8c667bcce1b75473effa1f550/zarrista-0.1.0-cp311-abi3-macosx_10_12_x86_64.whl", hash = "sha256:13791ea7aa09e6b928b735c098c6e233e722543c9e60393ffc9d9db2992d093b", size = 17062569, upload-time = "2026-08-13T14:44:03.419Z" }, + { url = "https://files.pythonhosted.org/packages/41/d8/f37480ebc669af91ebab0b01ab649413446bd5cce365f3f50b71d05be2af/zarrista-0.1.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:28ea1359ec791e84e1438e38e3047a964a3e7d59f56f122255a44ec2b368f33f", size = 15493396, upload-time = "2026-08-13T14:44:06.36Z" }, + { url = "https://files.pythonhosted.org/packages/03/99/3ab5bb73c926b00a11369786ff064c4976c8b31c696c072f9a7c8a585eab/zarrista-0.1.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:68f8a795ddb58a8ce1a19b401ce1bfae8acd3925edcd68f29e1a355ba495dced", size = 16911884, upload-time = "2026-08-13T14:44:08.875Z" }, + { url = "https://files.pythonhosted.org/packages/f0/48/3d07340e3256b2cdf441b883da4fd2f7ab89d4894da94a4c627ba8b2f9eb/zarrista-0.1.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:a2840000a75fc8367bf44e751c0ef2200138c31c6d859ad03a1dc27059293153", size = 17647323, upload-time = "2026-08-13T14:44:11.705Z" }, + { url = "https://files.pythonhosted.org/packages/ce/0f/54ac44214733a8a1f566466506da006941f53aff0dd6ba53f0e09b6173ce/zarrista-0.1.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b4962e0b3ff39021be8ca6d49ca53e1cffc72e116bf5769d8930c9206341c2c0", size = 23404364, upload-time = "2026-08-13T14:44:14.684Z" }, + { url = "https://files.pythonhosted.org/packages/b9/3c/b362387ddf18e5adbce335f0ad1c9ec5935a66cf2e92d032e58e6e0327b7/zarrista-0.1.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85a5a4f719e0ba5c093a7a427748bd2eaf89bbe1e3e1146f2017d41baff7a2d2", size = 24328123, upload-time = "2026-08-13T14:44:17.651Z" }, + { url = "https://files.pythonhosted.org/packages/af/2e/59f3ab896f5a8c76a3d009c40015a32660b1b05b0ff055efcee3aa977caa/zarrista-0.1.0-cp311-abi3-win_amd64.whl", hash = "sha256:5723fc1a4960392ba220ae17dcf8830805c653f86e9f1933396175062af0cb3d", size = 17155852, upload-time = "2026-08-13T14:44:20.224Z" }, + { url = "https://files.pythonhosted.org/packages/0f/fd/4cd858a7095e43e8fd8cefe4850b6caab3573ea5ad46a101c2dc4f331365/zarrista-0.1.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:73ea2e4944d4c5e02159d49ac1bf0d5c35d42022d3a274435e9059cec4d42105", size = 3394236, upload-time = "2026-08-13T14:44:22.67Z" }, + { url = "https://files.pythonhosted.org/packages/af/85/932c0802c4074f1aa3853f446232130324cab20f1ef2b561ecc45c897e1b/zarrista-0.1.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:2f6d47e268c8a4b0bdbed408b90634ecaa46a4f17b101eb41f8502f4a681e682", size = 17105288, upload-time = "2026-08-13T14:44:24.621Z" }, + { url = "https://files.pythonhosted.org/packages/8c/56/c0a18f2958572391eaee9334ae1f613aef61779ac1cfd8f91b962f295bf0/zarrista-0.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e4d86ad3c3f25179ed9187522d529fe41c78baef9d3d714526a4f8f737c37e64", size = 15452920, upload-time = "2026-08-13T14:44:28.012Z" }, + { url = "https://files.pythonhosted.org/packages/c8/86/0e4621fc185475de7fece084e3288733bfcc9d50a2e6690b189be739b3b3/zarrista-0.1.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:c60d98070920173e239bdd4ac2c21cb53807e8672b16e97674b6b843b48af0bc", size = 16894574, upload-time = "2026-08-13T14:44:31.03Z" }, + { url = "https://files.pythonhosted.org/packages/af/29/fbd4773a316cc6e3a222f0a549c5cae563a6cc72c2a67b492592c2eb3836/zarrista-0.1.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:2d4e8ed028a016b88a680e37476436d89bc044a65cc6052b7a3847ea360dd676", size = 17634738, upload-time = "2026-08-13T14:44:33.816Z" }, + { url = "https://files.pythonhosted.org/packages/47/3f/4202f4b11d2629c100ca5801dcf806826779db4eb925ff9e4d05658529a2/zarrista-0.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:96706a3acb1c1e623c85f08cc325ab74ade02a9bf6397a644040d50e1033d414", size = 23388185, upload-time = "2026-08-13T14:44:36.867Z" }, + { url = "https://files.pythonhosted.org/packages/e8/96/f2eb1d63d32efa2d11237e9ba3ca7b1b93f87c987bc6dce90d75657a7d55/zarrista-0.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5c2c29591f49ace61e54721a921ee957ba463a6d22848df32c901cd45df1bc70", size = 24315851, upload-time = "2026-08-13T14:44:40.01Z" }, + { url = "https://files.pythonhosted.org/packages/a2/b2/f8029969d8db3ffc886cc4fbda5eca01dec7b78a6cc8e44af3103c3c30c1/zarrista-0.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:58b15682404c61bb53e10c8a17202762b43702c3fe99c9b6ea05be256113bfdd", size = 17122744, upload-time = "2026-08-13T14:44:43.036Z" }, ] From 5fc05be5b8e5cbb1261a6f4801443273287ccc40 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 16:22:54 +0100 Subject: [PATCH 29/31] fix(array): convert ArrayIO write data to the array's byte order Data that differs from the array's data type only in byte order reached the codecs unconverted (the write casts only when the dtype name differs), and numcodecs filters such as Delta read its bytes as the array's data type, so every value was stored byte-swapped. It is now converted in _exact_data. The native-order comparison also covers subarray fields, and an edge chunk of a Zarr format 2 array reads in the order its metadata declares, as other chunks do. The interface now says whether data past the array's edge counts toward an all-fill chunk is not part of it. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- src/zarr/abc/array_io.py | 7 ++++--- src/zarr/core/array.py | 19 +++++++++++++------ tests/test_array_io.py | 33 ++++++++++++++++++++++++--------- 3 files changed, 41 insertions(+), 18 deletions(-) diff --git a/src/zarr/abc/array_io.py b/src/zarr/abc/array_io.py index 672829dc7a..fcdce31e8a 100644 --- a/src/zarr/abc/array_io.py +++ b/src/zarr/abc/array_io.py @@ -36,9 +36,10 @@ - Chunk indices are non-negative integers, one for each dimension. Reading or writing a chunk outside the chunk grid is not part of the interface. A chunk is read and written in its full shape, as zarrs reads and writes it: a chunk at the - array's edge includes the part past the array's shape. What that part reads as - for a stored chunk is not part of the interface (a missing chunk reads as the fill - value there as everywhere). + array's edge includes the part past the array's shape. That part's values are not + part of the interface: what it reads as for a stored chunk, and whether data + written there counts when deciding if a chunk holds only the fill value and is not + stored (a missing chunk reads as the fill value there as everywhere). - Runtime choices are per operation: `read_missing_chunks` on reads, `store_empty_chunks` on writes. Implementations may take more keyword options. """ diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 514a433f21..d9285306f0 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -1971,17 +1971,23 @@ def _write_config(store_empty_chunks: bool) -> ArrayConfig: def _in_native_byte_order(dtype: np.dtype[Any]) -> np.dtype[Any]: - """`dtype` in native byte order, fields included.""" - return dtype if dtype.isnative else dtype.newbyteorder("=") + """`dtype` in native byte order, fields and subarrays included; a data type without + a byte order (`StringDType`) as it is.""" + try: + return dtype.newbyteorder("=") + except TypeError: + return dtype def _exact_data(data: ArrayData, dtype: TBaseDType, shape: tuple[int, ...]) -> Any: """`data` to write to a region of `shape` of an array of `dtype`: an array that exports through DLPack, as every NumPy array does, with exactly that shape and data type. Byte order is not part of the data type: it changes no value, and DLPack - carries only native byte order, so data in either order is written. Nothing is - broadcast or cast. Raises `TypeError` for other data or another data type, and - `ValueError` for another shape. + carries only native byte order, so data in either order is written, converted to + the array's byte order here (codecs such as numcodecs filters read the bytes of + the data as the array's data type). Nothing is broadcast or cast. Raises + `TypeError` for other data or another data type, and `ValueError` for another + shape. Host data with `__array__` is read with `numpy.asarray`, as that data's own NumPy view, since some of it (NumPy string and record arrays, non-native byte order) @@ -2020,7 +2026,7 @@ def _exact_data(data: ArrayData, dtype: TBaseDType, shape: tuple[int, ...]) -> A f"Data of data type {array.dtype} does not match the array's data type " f"{dtype}; cast it first." ) - return array + return array if given == dtype else array.astype(dtype) @final @@ -2378,6 +2384,7 @@ async def retrieve_chunk( out = prototype.nd_buffer.create( shape=full_shape, dtype=self._metadata.dtype.to_native_dtype(), + order=self._metadata.order if isinstance(self._metadata, ArrayV2Metadata) else "C", fill_value=self._fill_value(), ) await self._get_selection( diff --git a/tests/test_array_io.py b/tests/test_array_io.py index 889d1081c1..5aaa9b52e0 100644 --- a/tests/test_array_io.py +++ b/tests/test_array_io.py @@ -7,12 +7,14 @@ from types import MappingProxyType from typing import TYPE_CHECKING, Any, Literal, cast +import numcodecs import numpy as np import pytest from typing_extensions import CapsuleType import zarr from zarr.abc.array_io import ArrayIO, ArrayResult, AsyncArrayIO, SupportsDLPack +from zarr.codecs.numcodecs import Delta as NumcodecsDelta from zarr.core.array import AsyncArray, AsyncZarrArrayIO, ZarrArrayIO from zarr.core.sync import SyncContext, sync from zarr.errors import ChunkNotFoundError, MetadataRepairRequiredError, ZarrUserWarning @@ -452,26 +454,39 @@ def test_store_array_subset_refuses_data_of_another_data_type( @pytest.mark.parametrize("zarr_format", [2, 3]) @pytest.mark.parametrize("made_by", ["of", "open"]) @pytest.mark.parametrize( - ("array_dtype", "data"), + ("array_dtype", "data", "delta"), [ - (">i4", np.asarray([1, 2], dtype="i4", np.asarray([1, 2], dtype=">i4")), - (">f8", np.asarray([1.5, 2.5], dtype="U2", np.asarray(["ab", "c"], dtype="i4", np.asarray([1, 2], dtype="i4", np.asarray([1, 2], dtype=">i4"), False), + (">f8", np.asarray([1.5, 2.5], dtype="U2", np.asarray(["ab", "c"], dtype="i4"), ("y", "f8")]), + False, ), ], ) def test_store_array_subset_writes_data_in_either_byte_order( - zarr_format: Literal[2, 3], made_by: str, array_dtype: Any, data: Any + zarr_format: Literal[2, 3], made_by: str, array_dtype: Any, data: Any, delta: bool ) -> None: """Byte order is not part of the data type, however the value was made: data in - either order writes the same values, and what one value reads another writes.""" + either order writes the same values, through filters that read the data's bytes + as the array's data type (numcodecs' `Delta`) too, and what one value reads + another writes.""" store = MemoryStore() - array = zarr.create_array(store, shape=(2,), dtype=array_dtype, zarr_format=zarr_format) + filters: Any = "auto" + if delta: + filters = ( + [numcodecs.Delta(dtype=array_dtype)] + if zarr_format == 2 + else [NumcodecsDelta(dtype=array_dtype)] + ) + array = zarr.create_array( + store, shape=(2,), dtype=array_dtype, zarr_format=zarr_format, filters=filters + ) io = ZarrArrayIO.of(array) if made_by == "of" else ZarrArrayIO.open(store) io[:] = data From 4e99606efe94e1aed746c6f58b631aafd1353750 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 16:23:01 +0100 Subject: [PATCH 30/31] test(array): cross-read stores and compare bits against zarrista zarrista moves to its own zarrista-tests dependency group, installed by the optional rows of the test matrix only: in the test group it made min_deps unresolvable (zarrista needs typing_extensions>=4.16) and it cannot run on NumPy 2.0, so the module also skips below NumPy 2.1. The comparison now has each implementation read the other's store, so a codec bug that is wrong the same way on write and read is caught; compares bytes, so -0.0 and NaN payloads are not equated; and covers all-fill chunk and subset writes with and without store_empty_chunks. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 9 +++- tests/test_array_io_zarrista.py | 91 +++++++++++++++++++++++++-------- uv.lock | 10 ++-- 3 files changed, 80 insertions(+), 30 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 44c548f5d9..3a1df533d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -122,8 +122,12 @@ test = [ "pytest-benchmark==5.3.1", "pytest-codspeed==5.0.4", "uv==0.13.7", - # tests/test_array_io_zarrista.py checks ZarrArrayIO against it; wheels only. - "zarrista==0.1.0; platform_machine in 'x86_64 AMD64 arm64 aarch64'", +] +# tests/test_array_io_zarrista.py checks ZarrArrayIO against zarrista. Only machines +# with zarrista wheels (elsewhere it builds from source, in Rust); not in min_deps, +# whose NumPy 2.0 and typing_extensions 4.14 zarrista does not support. +zarrista-tests = [ + "zarrista==0.1.0; platform_machine == 'x86_64' or platform_machine == 'AMD64' or platform_machine == 'arm64' or platform_machine == 'aarch64'", ] remote-tests = [ {include-group = "test"}, @@ -207,6 +211,7 @@ matrix.deps.features = [ ] matrix.deps.dependency-groups = [ {value = "remote-tests", if = ["optional"]}, + {value = "zarrista-tests", if = ["optional"]}, ] [tool.hatch.envs.gputest] diff --git a/tests/test_array_io_zarrista.py b/tests/test_array_io_zarrista.py index 0b1495b556..ba82d91dcf 100644 --- a/tests/test_array_io_zarrista.py +++ b/tests/test_array_io_zarrista.py @@ -1,9 +1,11 @@ """`ZarrArrayIO` against zarrista, a zarrs-based implementation of the same interface. -The same calls on the same stored array must give the same values, store the same -chunk keys, and refuse the same data. zarrista's `store_chunk` takes `ArrayBytes` -and its chunk indices are lists, so the test translates those two; everything else -is called as the interface has it. +The same reads and writes on the same stored array must give bit-identical values, +store the same chunk keys and chunks each can read, and refuse the same data. It +covers subset and chunk reads and writes, `store_empty_chunks` and `erase_chunk`; +the metadata members differ between the two (see the PR's table) and are not +compared. zarrista's `store_chunk` takes `ArrayBytes` and its chunk indices are +lists, so the test translates those two. """ from __future__ import annotations @@ -21,6 +23,8 @@ from pathlib import Path zarrista = pytest.importorskip("zarrista") +if np.lib.NumpyVersion(np.__version__) < "2.1.0": + pytest.skip("zarrista exports through DLPack 1.0, from NumPy 2.1", allow_module_level=True) _SHAPE = (5, 3) _BYTES = {"name": "bytes", "configuration": {"endian": "little"}} @@ -69,11 +73,24 @@ def __getitem__(self, selection: Any) -> Any: def __setitem__(self, selection: Any, data: Any) -> None: self._array[selection] = data + def store_array_subset(self, selection: Any, data: Any, *, store_empty_chunks: bool) -> None: + self._array.store_array_subset(selection, data, store_empty_chunks=store_empty_chunks) + def retrieve_chunk(self, indices: tuple[int, ...]) -> Any: return self._array.retrieve_chunk(list(indices)) - def store_chunk(self, indices: tuple[int, ...], data: np.ndarray[Any, Any]) -> None: - self._array.store_chunk(list(indices), zarrista.ArrayBytes(data.tobytes())) + def store_chunk( + self, + indices: tuple[int, ...], + data: np.ndarray[Any, Any], + *, + store_empty_chunks: bool = False, + ) -> None: + self._array.store_chunk( + list(indices), + zarrista.ArrayBytes(data.tobytes()), + store_empty_chunks=store_empty_chunks, + ) def erase_chunk(self, indices: tuple[int, ...]) -> None: self._array.erase_chunk(list(indices)) @@ -94,14 +111,20 @@ def _metadata(dtype: str, fill_value: Any, layout: str) -> dict[str, Any]: } +def _ours(root: Path) -> ZarrArrayIO: + return ZarrArrayIO.open(LocalStore(root), "a") + + +def _theirs(root: Path) -> _Zarrista: + return _Zarrista(zarrista.Array.open(zarrista.store.FilesystemStore(str(root)), "/a")) + + def _open_both(tmp_path: Path, metadata: dict[str, Any]) -> tuple[Any, Any, Path, Path]: roots = (tmp_path / "zarr-python", tmp_path / "zarrista") for root in roots: (root / "a").mkdir(parents=True) (root / "a" / "zarr.json").write_text(json.dumps(metadata)) - ours = ZarrArrayIO.open(LocalStore(roots[0]), "a") - theirs = _Zarrista(zarrista.Array.open(zarrista.store.FilesystemStore(str(roots[1])), "/a")) - return ours, theirs, *roots + return _ours(roots[0]), _theirs(roots[1]), *roots def _chunk_keys(root: Path) -> list[str]: @@ -121,18 +144,25 @@ def _values(rng: np.random.Generator, dtype: str, shape: tuple[int, ...]) -> np. return rng.integers(info.min, info.max, size=shape, dtype=dtype, endpoint=True) +def _assert_bits_equal(first: Any, second: Any) -> None: + """Equal data types, shapes and bytes: `-0.0` is not `0.0`, nor one NaN another.""" + first, second = np.ascontiguousarray(first), np.ascontiguousarray(second) + assert (first.dtype, first.shape) == (second.dtype, second.shape) + assert first.tobytes() == second.tobytes() + + def _assert_same(ours: Any, theirs: Any, roots: tuple[Path, Path], grid: tuple[int, ...]) -> None: - np.testing.assert_array_equal(np.asarray(ours[...]), np.asarray(theirs[...]), strict=True) - for selection in [(slice(1, 3), slice(-2, None)), (slice(3, 100),), (slice(2, 2),), ()]: - np.testing.assert_array_equal( - np.asarray(ours[selection]), np.asarray(theirs[selection]), strict=True - ) + """Both read the same values, subsets and chunks from their own stores, each reads + the other's store the same way, and both stored the same chunk keys.""" + readers = [ours, theirs, _theirs(roots[0]), _ours(roots[1])] + for selection in [..., (slice(1, 3), slice(-2, None)), (slice(3, 100),), (slice(2, 2),), ()]: + expected = np.asarray(ours[selection]) + for reader in readers[1:]: + _assert_bits_equal(expected, np.asarray(reader[selection])) for indices in np.ndindex(*grid): - np.testing.assert_array_equal( - np.asarray(ours.retrieve_chunk(indices)), - np.asarray(theirs.retrieve_chunk(indices)), - strict=True, - ) + expected = np.asarray(ours.retrieve_chunk(indices)) + for reader in readers[1:]: + _assert_bits_equal(expected, np.asarray(reader.retrieve_chunk(indices))) assert _chunk_keys(roots[0]) == _chunk_keys(roots[1]) @@ -142,8 +172,9 @@ def test_writes_and_reads_match_zarrista( tmp_path: Path, layout: str, dtype: str, fill_value: Any ) -> None: """After each write (whole array, partial, clipped and empty subsets, a full edge - chunk, an all-fill chunk, an erase), both read the same values, subsets and chunks, - and store the same chunk keys.""" + chunk, all-fill chunks with and without `store_empty_chunks`, an erase), both read + the same values, subsets and chunks, read each other's stores, and store the same + chunk keys.""" ours, theirs, *roots = _open_both(tmp_path, _metadata(dtype, fill_value, layout)) chunk_shape = tuple(_LAYOUTS[layout][0]) grid = tuple(-(-extent // size) for extent, size in zip(_SHAPE, chunk_shape, strict=True)) @@ -175,7 +206,23 @@ def write_chunk(indices: tuple[int, ...], data: np.ndarray[Any, Any]) -> None: edge_chunk[tuple(slice(0, n) for n in edge_inside)] = _values(rng, dtype, edge_inside) write_chunk(edge, edge_chunk) _assert_same(ours, theirs, (roots[0], roots[1]), grid) - write_chunk((0,) * len(grid), np.full(chunk_shape, fill, dtype=dtype)) + first = (0,) * len(grid) + write_chunk(first, np.full(chunk_shape, fill, dtype=dtype)) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + for target in (ours, theirs): + target.store_chunk(first, np.full(chunk_shape, fill, dtype=dtype), store_empty_chunks=True) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) + # The whole of the first chunk, through a subset, with and without the option. + region = tuple(slice(0, n) for n in chunk_shape) + region_shape = tuple(min(n, extent) for n, extent in zip(chunk_shape, _SHAPE, strict=True)) + for store_empty_chunks in (False, True): + for target in (ours, theirs): + target.store_array_subset( + region, + np.full(region_shape, fill, dtype=dtype), + store_empty_chunks=store_empty_chunks, + ) + _assert_same(ours, theirs, (roots[0], roots[1]), grid) ours.erase_chunk(edge) theirs.erase_chunk(edge) _assert_same(ours, theirs, (roots[0], roots[1]), grid) diff --git a/uv.lock b/uv.lock index 22acbded6f..6259bd37c5 100644 --- a/uv.lock +++ b/uv.lock @@ -3862,7 +3862,6 @@ dev = [ { name = "towncrier" }, { name = "universal-pathlib" }, { name = "uv" }, - { name = "zarrista", marker = "platform_machine in 'x86_64 AMD64 arm64 aarch64'" }, ] docs = [ { name = "astroid" }, @@ -3901,7 +3900,6 @@ remote-tests = [ { name = "requests" }, { name = "s3fs" }, { name = "uv" }, - { name = "zarrista", marker = "platform_machine in 'x86_64 AMD64 arm64 aarch64'" }, ] test = [ { name = "coverage" }, @@ -3915,7 +3913,9 @@ test = [ { name = "pytest-reportlog" }, { name = "pytest-xdist" }, { name = "uv" }, - { name = "zarrista", marker = "platform_machine in 'x86_64 AMD64 arm64 aarch64'" }, +] +zarrista-tests = [ + { name = "zarrista", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, ] [package.metadata] @@ -3969,7 +3969,6 @@ dev = [ { name = "towncrier", specifier = "==26.9.0" }, { name = "universal-pathlib" }, { name = "uv", specifier = "==0.13.7" }, - { name = "zarrista", marker = "platform_machine in 'x86_64 AMD64 arm64 aarch64'", specifier = "==0.1.0" }, ] docs = [ { name = "astroid", specifier = "==4.3.4" }, @@ -4006,7 +4005,6 @@ remote-tests = [ { name = "requests", specifier = "==2.34.2" }, { name = "s3fs", specifier = ">=2023.10.0" }, { name = "uv", specifier = "==0.13.7" }, - { name = "zarrista", marker = "platform_machine in 'x86_64 AMD64 arm64 aarch64'", specifier = "==0.1.0" }, ] test = [ { name = "coverage", specifier = "==7.17.2" }, @@ -4020,8 +4018,8 @@ test = [ { name = "pytest-reportlog", specifier = "==1.0.0" }, { name = "pytest-xdist", specifier = "==3.8.0" }, { name = "uv", specifier = "==0.13.7" }, - { name = "zarrista", marker = "platform_machine in 'x86_64 AMD64 arm64 aarch64'", specifier = "==0.1.0" }, ] +zarrista-tests = [{ name = "zarrista", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'x86_64'", specifier = "==0.1.0" }] [[package]] name = "zarr-metadata" From 15d853b46ff8018dbf4552602f2a4ed43fabcaa3 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 16:29:44 +0100 Subject: [PATCH 31/31] build: include zarrista-tests in the dev dependency group A plain `uv sync` installs the dev group, which lost zarrista when it moved to its own group, so tests/test_array_io_zarrista.py was skipped locally without notice. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 1 + uv.lock | 2 ++ 2 files changed, 3 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 3a1df533d4..dcb20c3fd9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -163,6 +163,7 @@ docs = [ dev = [ {include-group = "test"}, {include-group = "remote-tests"}, + {include-group = "zarrista-tests"}, {include-group = "docs"}, "universal-pathlib", "mypy==2.4.1", diff --git a/uv.lock b/uv.lock index 6259bd37c5..19c44d745e 100644 --- a/uv.lock +++ b/uv.lock @@ -3862,6 +3862,7 @@ dev = [ { name = "towncrier" }, { name = "universal-pathlib" }, { name = "uv" }, + { name = "zarrista", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, ] docs = [ { name = "astroid" }, @@ -3969,6 +3970,7 @@ dev = [ { name = "towncrier", specifier = "==26.9.0" }, { name = "universal-pathlib" }, { name = "uv", specifier = "==0.13.7" }, + { name = "zarrista", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'x86_64'", specifier = "==0.1.0" }, ] docs = [ { name = "astroid", specifier = "==4.3.4" },