diff --git a/changes/4484.bugfix.md b/changes/4484.bugfix.md new file mode 100644 index 0000000000..a6b2c4d7df --- /dev/null +++ b/changes/4484.bugfix.md @@ -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`. diff --git a/src/zarr/api/asynchronous.py b/src/zarr/api/asynchronous.py index 3993ce35cc..701af6d281 100644 --- a/src/zarr/api/asynchronous.py +++ b/src/zarr/api/asynchronous.py @@ -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 @@ -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( diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 3735a4da18..cc52511bc8 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -68,6 +68,7 @@ ShapeLike, ZarrFormat, _default_zarr_format, + _validate_node_name, _warn_order_kwarg, ceildiv_int, concurrent_foreach, @@ -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 ) diff --git a/src/zarr/core/common.py b/src/zarr/core/common.py index 47f79b2e72..68addb2adb 100644 --- a/src/zarr/core/common.py +++ b/src/zarr/core/common.py @@ -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 @@ -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}" diff --git a/src/zarr/core/group.py b/src/zarr/core/group.py index 561a2be8c0..9e149494f1 100644 --- a/src/zarr/core/group.py +++ b/src/zarr/core/group.py @@ -43,6 +43,7 @@ NodeType, ShapeLike, ZarrFormat, + _validate_node_name, parse_shapelike, ) from zarr.core.config import config @@ -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, @@ -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, diff --git a/tests/test_group.py b/tests/test_group.py index 6976ef536c..5da09e4691 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -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"]