Skip to content
Open
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/4484.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Creating a node now raises `MetadataValidationError` when a name segment is `zarr.json`, begins with `__`, or is `.` or `..`. Previously `create_group("a/zarr.json")` wrote a directory named `zarr.json` that shadowed the group's metadata document and left the subtree unreachable. `create_group("__a")` likewise wrote a reserved name. Both are refused before anything is stored. Covered are `AsyncGroup.create_group`, `AsyncGroup.create_array`, and the `name`/`path` arguments of the module-level `create_array` and `create_group`.
3 changes: 3 additions & 0 deletions src/zarr/api/asynchronous.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
MemoryOrder,
ZarrFormat,
_default_zarr_format,
_validate_node_name,
_warn_write_empty_chunks_kwarg,
)
from zarr.core.dtype import ZDTypeLike, get_data_type_from_native_dtype
Expand Down Expand Up @@ -794,6 +795,8 @@ async def create_group(

mode: Literal["a"] = "a"

if path:
_validate_node_name(path)
store_path = await make_store_path(store, path=path, mode=mode, storage_options=storage_options)

return await AsyncGroup.from_store(
Expand Down
3 changes: 3 additions & 0 deletions src/zarr/core/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
ShapeLike,
ZarrFormat,
_default_zarr_format,
_validate_node_name,
_warn_order_kwarg,
ceildiv_int,
concurrent_foreach,
Expand Down Expand Up @@ -4895,6 +4896,8 @@ async def create_array(
mode: Literal["a"] = "a"

zarr_format = resolve_zarr_format(store, zarr_format)
if name:
_validate_node_name(name)
store_path = await make_store_path(
store, path=name, mode=mode, storage_options=storage_options
)
Expand Down
18 changes: 17 additions & 1 deletion src/zarr/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

from zarr.core.config import config as zarr_config
from zarr.core.json_parse import convert, parse_field
from zarr.errors import ZarrRuntimeWarning
from zarr.errors import MetadataValidationError, ZarrRuntimeWarning

if TYPE_CHECKING:
from collections.abc import Awaitable, Callable, Iterator
Expand Down Expand Up @@ -353,6 +353,22 @@ def _default_zarr_format() -> ZarrFormat:
return cast("ZarrFormat", int(zarr_config.get("default_zarr_format", 3)))


def _validate_node_name(name: str) -> None:
"""Reject a node name the Zarr format reserves or that cannot be addressed.

Node names may not be ``zarr.json`` or start with ``__``, and no path
segment may be ``.`` or ``..``. Without this check,
``create_group("a/zarr.json")`` writes a directory named ``zarr.json`` and
``create_group("__a")`` writes a reserved name; both produce stores other
readers cannot interpret. Empty segments are skipped because leading and
repeated slashes have long been normalized away by path joining.
"""
for segment in name.split("/"):
if segment in (".", "..", ZARR_JSON) or segment.startswith("__"):
msg = f"Invalid node name {name!r}: {segment!r} is not a permitted node name."
raise MetadataValidationError(msg)


def _subject(name: str, axis: int | None) -> str:
"""`name` as the subject of an error message, prefixed by the dimension `axis`."""
return name[0].upper() + name[1:] if axis is None else f"Dimension {axis}: {name}"
Expand Down
3 changes: 3 additions & 0 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,
_validate_node_name,
parse_shapelike,
)
from zarr.core.config import config
Expand Down Expand Up @@ -1090,6 +1091,7 @@ async def create_group(
g : AsyncGroup
"""
attributes = attributes or {}
_validate_node_name(name)
return await type(self).from_store(
self.store_path / name,
attributes=attributes,
Expand Down Expand Up @@ -1280,6 +1282,7 @@ async def create_array(
compressors = _parse_deprecated_compressor(
compressor, compressors, zarr_format=self.metadata.zarr_format
)
_validate_node_name(name)
return await create_array(
store=self.store_path,
name=name,
Expand Down
30 changes: 30 additions & 0 deletions tests/test_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -2647,3 +2647,33 @@ def test_open_array_as_group():
z = zarr.create_array(shape=(40, 50), chunks=(10, 10), dtype="f8", store={})
with pytest.raises(ContainsArrayError):
zarr.open_group(z.store)


@pytest.mark.parametrize("store", ["local", "memory"], indirect=True)
@pytest.mark.parametrize("bad", ["__a", "zarr.json", "a/zarr.json", "a/../b", "."])
def test_create_group_reserved_names_rejected(store: Store, bad: str) -> None:
"""Reserved or unaddressable node names are refused before anything is
written. `zarr.json` as a final segment writes a directory that shadows
the parent's metadata document, orphaning the whole subtree."""
group = zarr.group(store=store)
with pytest.raises(MetadataValidationError, match="not a permitted node name"):
group.create_group(bad)
with pytest.raises(MetadataValidationError, match="not a permitted node name"):
group.create_array(bad, shape=(2,), dtype="i4")
assert list(group.members()) == []


def test_create_node_reserved_names_rejected_module_level(store: Store) -> None:
"""The same check applies to `name`/`path` on the module-level creators."""
with pytest.raises(MetadataValidationError, match="not a permitted node name"):
zarr.create_array(store, name="x/zarr.json", shape=(2,), dtype="i4")
with pytest.raises(MetadataValidationError, match="not a permitted node name"):
zarr.create_group(store, path="g/__x")


def test_create_group_reserved_names_allowed_siblings(store: Store) -> None:
"""Names that merely contain a `__` infix or `.` infix are permitted."""
group = zarr.group(store=store)
group.create_group("a__b")
group.create_array("x.y", shape=(2,), dtype="i4")
assert sorted(n for n, _ in group.members()) == ["a__b", "x.y"]