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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/4692.bugfix.md
Original file line number Diff line number Diff line change
@@ -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.
11 changes: 11 additions & 0 deletions docs/user-guide/groups.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
90 changes: 77 additions & 13 deletions src/zarr/core/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
NodeType,
ShapeLike,
ZarrFormat,
concurrent_map,
parse_shapelike,
)
from zarr.core.config import config
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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]:
Expand All @@ -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(
Expand Down Expand Up @@ -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
--------
Expand Down Expand Up @@ -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
--------
Expand All @@ -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.
Expand Down Expand Up @@ -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
--------
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down
185 changes: 185 additions & 0 deletions tests/test_group_keys.py
Original file line number Diff line number Diff line change
@@ -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())