From df27bfe988279904f77461356b7a8668a6aa16f8 Mon Sep 17 00:00:00 2001 From: Griff Tatarsky Date: Thu, 3 Dec 2026 18:15:40 -0500 Subject: [PATCH] fix(group): list member names without resolving array codecs --- changes/4692.bugfix.md | 1 + docs/user-guide/groups.md | 11 +++ src/zarr/core/group.py | 90 ++++++++++++++++--- tests/test_group_keys.py | 185 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 274 insertions(+), 13 deletions(-) create mode 100644 changes/4692.bugfix.md create mode 100644 tests/test_group_keys.py diff --git a/changes/4692.bugfix.md b/changes/4692.bugfix.md new file mode 100644 index 0000000000..482a21fcf0 --- /dev/null +++ b/changes/4692.bugfix.md @@ -0,0 +1 @@ +List group member names without constructing child arrays or requiring their codec implementations. This fixes `Group.keys()`, `array_keys()`, `group_keys()`, iteration, and immediate member counts for groups containing arrays whose codecs are unavailable, including the corresponding async methods. diff --git a/docs/user-guide/groups.md b/docs/user-guide/groups.md index ada5c5ec84..74a7485d78 100644 --- a/docs/user-guide/groups.md +++ b/docs/user-guide/groups.md @@ -108,6 +108,17 @@ print(list(root.keys())) print('foo' in root) ``` +To list only array names or only subgroup names, use [`zarr.Group.array_keys`][] +or [`zarr.Group.group_keys`][]. These methods and `keys()` inspect node metadata +without opening child arrays, so listing names does not require their codec +implementations. Listing names does not fully validate array configurations. +Retrieving arrays with `[]`, `arrays()`, or `array_values()` +still requires those implementations. + +Opening a group with consolidated metadata still parses its array metadata and +can require codecs. To inspect names when a codec is unavailable, open the group +with `use_consolidated=False` and use a store that supports directory listing. + The [`zarr.Group.members`][] method returns `(name, member)` pairs for the arrays and groups contained in a group: diff --git a/src/zarr/core/group.py b/src/zarr/core/group.py index 561a2be8c0..deb0f4d08f 100644 --- a/src/zarr/core/group.py +++ b/src/zarr/core/group.py @@ -43,6 +43,7 @@ NodeType, ShapeLike, ZarrFormat, + concurrent_map, parse_shapelike, ) from zarr.core.config import config @@ -1424,6 +1425,8 @@ async def nmembers( ) # TODO: consider using aioitertools.builtins.sum for this # return await aioitertools.builtins.sum((1 async for _ in self.members()), start=0) + if max_depth == 0: + return len([key async for key in self.keys()]) n = 0 async for _ in self.members(max_depth=max_depth): n += 1 @@ -1610,9 +1613,50 @@ async def create_hierarchy( out_key = key.removeprefix(prefix + "/") yield out_key, node + async def _member_keys(self, node_type: NodeType | None = None) -> AsyncGenerator[str, None]: + """List immediate children without constructing arrays or resolving their codecs.""" + consolidated = self.metadata.consolidated_metadata + if consolidated is not None: + for key, metadata in consolidated.metadata.items(): + consolidated_kind = "group" if isinstance(metadata, GroupMetadata) else "array" + if node_type is None or consolidated_kind == node_type: + yield key + return + + if not self.store.supports_listing: + msg = ( + f"The store associated with this group ({type(self.store)}) " + "does not support listing, " + "specifically via the `list_dir` method. " + "This function requires a store that supports listing." + ) + raise ValueError(msg) + + zarr_format = self.metadata.zarr_format + skip_keys = ( + (ZARRAY_JSON, ZGROUP_JSON, ZATTRS_JSON, ZMETADATA_V2_JSON) + if zarr_format == 2 + else (ZARR_JSON,) + ) + keys = [key async for key in self.store.list_dir(self.path) if key not in skip_keys] + kinds = await concurrent_map( + [(self.store_path / key, zarr_format) for key in keys], + _read_node_type, + limit=config.get("async.concurrency"), + ) + for key, kind in zip(keys, kinds, strict=True): + if kind is None: + warnings.warn( + f"Object at {key} is not recognized as a component of a Zarr hierarchy.", + ZarrUserWarning, + stacklevel=1, + ) + elif node_type is None or kind == node_type: + yield key + async def keys(self) -> AsyncGenerator[str, None]: - """Iterate over member names.""" - async for key, _ in self.members(): + """Iterate over member names without opening the members.""" + async for key in self._member_keys(): yield key async def contains(self, member: str) -> bool: @@ -1642,8 +1686,8 @@ async def groups(self) -> AsyncGenerator[tuple[str, AsyncGroup], None]: yield name, value async def group_keys(self) -> AsyncGenerator[str, None]: - """Iterate over group names.""" - async for key, _ in self.groups(): + """Iterate over group names without opening the members.""" + async for key in self._member_keys("group"): yield key async def group_values(self) -> AsyncGenerator[AsyncGroup, None]: @@ -1660,8 +1704,8 @@ async def arrays( yield key, value async def array_keys(self) -> AsyncGenerator[str, None]: - """Iterate over array names.""" - async for key, _ in self.arrays(): + """Iterate over array names without opening the members.""" + async for key in self._member_keys("array"): yield key async def array_values( @@ -2463,7 +2507,7 @@ def create_hierarchy( yield (key, _parse_async_node(node)) def keys(self) -> Generator[str]: - """Return an iterator over group member names. + """Return an iterator over member names without opening the members. Examples -------- @@ -2511,7 +2555,7 @@ def groups(self) -> Generator[tuple[str, Group], None]: yield name, Group(async_group) def group_keys(self) -> Generator[str, None]: - """Return an iterator over group member names. + """Return an iterator over group names without opening the members. Examples -------- @@ -2521,8 +2565,7 @@ def group_keys(self) -> Generator[str, None]: >>> list(group.group_keys()) ['subgroup'] """ - for name, _ in self.groups(): - yield name + yield from self._sync_iter(self._async_group.group_keys()) def group_values(self) -> Generator[Group, None]: """Return an iterator over group members. @@ -2553,7 +2596,7 @@ def arrays(self) -> Generator[tuple[str, AnyArray], None]: yield name, Array(async_array) def array_keys(self) -> Generator[str, None]: - """Return an iterator over group member names. + """Return an iterator over array names without opening the members. Examples -------- @@ -2564,8 +2607,7 @@ def array_keys(self) -> Generator[str, None]: ['subarray'] """ - for name, _ in self.arrays(): - yield name + yield from self._sync_iter(self._async_group.array_keys()) def array_values(self) -> Generator[AnyArray, None]: """Return an iterator over group members. @@ -3700,6 +3742,28 @@ async def _iter_members_deep( yield key, node +async def _read_node_type(store_path: StorePath, zarr_format: ZarrFormat) -> NodeType | None: + """Read only the metadata needed to identify a node, without parsing codec pipelines.""" + if zarr_format == 2: + # Match get_node's precedence when both metadata documents are present. + for filename, kind in ((ZARRAY_JSON, "array"), (ZGROUP_JSON, "group")): + buffer = await (store_path / filename).get() + if buffer is not None: + metadata = buffer_to_json_object(buffer) + if parse_zarr_format(metadata.get("zarr_format")) != 2: + raise MetadataValidationError("Expected zarr_format 2") + return cast("NodeType", kind) + return None + + buffer = await (store_path / ZARR_JSON).get() + if buffer is None: + return None + metadata = buffer_to_json_object(buffer) + if parse_zarr_format(metadata.get("zarr_format")) != 3: + raise MetadataValidationError("Expected zarr_format 3") + return parse_node_type(metadata.get("node_type")) + + async def _read_metadata_v3(store: Store, path: str) -> ArrayV3Metadata | GroupMetadata: """ Given a store_path, return ArrayV3Metadata or GroupMetadata defined by the metadata diff --git a/tests/test_group_keys.py b/tests/test_group_keys.py new file mode 100644 index 0000000000..5dcf7d12ca --- /dev/null +++ b/tests/test_group_keys.py @@ -0,0 +1,185 @@ +"""Name-only traversal must not require array codec implementations.""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +from typing import TYPE_CHECKING +from unittest.mock import patch + +import numpy as np +import pytest + +import zarr +from zarr import AsyncArray, Group +from zarr.core.buffer import default_buffer_prototype +from zarr.core.sync import sync +from zarr.errors import MetadataValidationError, UnknownCodecError, ZarrUserWarning +from zarr.storage import LocalStore, MemoryStore + +if TYPE_CHECKING: + from pathlib import Path + from typing import Any + + from zarr.core.buffer import Buffer + from zarr.core.common import ZarrFormat + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("path", ["", "nested/group"]) +@pytest.mark.parametrize("local", [False, True]) +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("method", ["keys", "array_keys", "group_keys"]) +async def test_keys_without_codec( + tmp_path: Path, + zarr_format: ZarrFormat, + path: str, + local: bool, + asynchronous: bool, + method: str, +) -> None: + store = LocalStore(tmp_path) if local else MemoryStore() + group = await zarr.api.asynchronous.create_group( + store=store, path=path, zarr_format=zarr_format + ) + readable = await group.create_array("readable", data=np.array([7], dtype="i4")) + await group.create_array("plugin_array", shape=(1,), dtype="i4") + subgroup = await group.create_group("subgroup") + await subgroup.create_array("nested_array", shape=(1,), dtype="i4") + key = "plugin_array/" + (".zarray" if zarr_format == 2 else "zarr.json") + metadata_path = group.store_path / key + buffer = await metadata_path.get() + assert buffer is not None + metadata = json.loads(buffer.to_bytes()) + if zarr_format == 2: + metadata["compressor"] = {"id": "example.uninstalled"} + else: + metadata["codecs"].append({"name": "example.uninstalled", "configuration": {}}) + await metadata_path.set( + default_buffer_prototype().buffer.from_bytes(json.dumps(metadata).encode()) + ) + + np.testing.assert_array_equal(await readable.getitem(slice(None)), [7]) + expected = { + "keys": ["plugin_array", "readable", "subgroup"], + "array_keys": ["plugin_array", "readable"], + "group_keys": ["subgroup"], + }[method] + if asynchronous: + result = [key async for key in getattr(group, method)()] + else: + result = list(getattr(Group(group), method)()) + assert sorted(result) == expected + assert await group.nmembers() == 3 + assert len(Group(group)) == 3 + assert sorted(Group(group)) == ["plugin_array", "readable", "subgroup"] + with pytest.raises(UnknownCodecError, match="example.uninstalled"): + await group.getitem("plugin_array") + with pytest.raises(UnknownCodecError, match="example.uninstalled"): + [item async for item in group.arrays()] + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("method", ["keys", "array_keys", "group_keys"]) +def test_keys_consolidated_without_array_construction(zarr_format: ZarrFormat, method: str) -> None: + group = zarr.group(zarr_format=zarr_format) + group.create_array("array", shape=(1,), dtype="i4") + group.create_group("group").create_array("nested", shape=(1,), dtype="i4") + with pytest.warns(ZarrUserWarning) if zarr_format == 3 else contextlib.nullcontext(): + consolidated = zarr.consolidate_metadata(group.store) + # The consolidated view must remain authoritative, even if storage has changed. + group.create_array("unconsolidated", shape=(1,), dtype="i4") + with ( + patch.object(AsyncArray, "__init__", side_effect=AssertionError("opened an array")), + patch.object(type(group.store), "supports_listing", False), + patch.object(group.store, "get", side_effect=AssertionError("read from storage")), + patch.object(group.store, "list_dir", side_effect=AssertionError("listed storage")), + ): + assert ( + sorted(getattr(consolidated, method)()) + == { + "keys": ["array", "group"], + "array_keys": ["array"], + "group_keys": ["group"], + }[method] + ) + + +@pytest.mark.parametrize("method", ["keys", "array_keys", "group_keys"]) +@pytest.mark.parametrize( + "metadata", [b"not json", b'{"zarr_format":3}', b'{"zarr_format":3,"node_type":"invalid"}'] +) +def test_keys_invalid_node_metadata(method: str, metadata: bytes) -> None: + group = zarr.group() + sync( + (group.store_path / "broken/zarr.json").set( + default_buffer_prototype().buffer.from_bytes(metadata) + ) + ) + with pytest.raises((ValueError, MetadataValidationError)): + list(getattr(group, method)()) + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("method", ["keys", "array_keys", "group_keys"]) +def test_keys_skip_non_nodes(zarr_format: ZarrFormat, method: str) -> None: + group = zarr.group(zarr_format=zarr_format) + sync((group.store_path / "extra").set(default_buffer_prototype().buffer.from_bytes(b"extra"))) + with pytest.warns(ZarrUserWarning, match="Object at extra is not recognized"): + assert list(getattr(group, method)()) == [] + + +@pytest.mark.parametrize("method", ["keys", "array_keys", "group_keys"]) +async def test_keys_concurrency_and_store_errors(method: str) -> None: + group = await zarr.api.asynchronous.create_group(store=MemoryStore()) + for i in range(5): + await group.create_array(str(i), shape=(1,), dtype="i4") + original_get = group.store.get + active = peak = 0 + + async def get(*args: Any, **kwargs: Any) -> Buffer | None: + nonlocal active, peak + active += 1 + peak = max(active, peak) + try: + await asyncio.sleep(0.01) + return await original_get(*args, **kwargs) + finally: + active -= 1 + + with zarr.config.set({"async.concurrency": 2}), patch.object(group.store, "get", get): + [key async for key in getattr(group, method)()] + assert peak == 2 + with patch.object(group.store, "get", side_effect=OSError("storage unavailable")): + with pytest.raises(OSError, match="storage unavailable"): + [key async for key in getattr(group, method)()] + + +@pytest.mark.parametrize("method", ["keys", "array_keys", "group_keys"]) +def test_keys_without_listing(method: str) -> None: + group = zarr.group() + with patch.object(type(group.store), "supports_listing", False): + with pytest.raises(ValueError, match="does not support listing"): + list(getattr(group, method)()) + + +@pytest.mark.parametrize( + ("zarr_format", "filename", "metadata"), + [ + (2, ".zarray", b"not json"), + (2, ".zgroup", b"not json"), + (2, ".zarray", b'{"zarr_format":3}'), + (2, ".zgroup", b'{"zarr_format":3}'), + (3, "zarr.json", b'{"zarr_format":2,"node_type":"array"}'), + ], +) +def test_keys_invalid_format(zarr_format: ZarrFormat, filename: str, metadata: bytes) -> None: + group = zarr.group(zarr_format=zarr_format) + sync( + (group.store_path / f"broken/{filename}").set( + default_buffer_prototype().buffer.from_bytes(metadata) + ) + ) + with pytest.raises((ValueError, MetadataValidationError)): + list(group.keys())