Skip to content

Commit b0ea125

Browse files
d-v-bclaude
andcommitted
fix(group): build every node before create_hierarchy deletes or stores anything
A node whose metadata no array or group can be built from now fails with the store untouched, even with overwrite=True. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6fde402 commit b0ea125

2 files changed

Lines changed: 52 additions & 10 deletions

File tree

‎src/zarr/core/group.py‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3085,6 +3085,7 @@ async def create_hierarchy(
30853085
# ensure that all nodes have the same zarr_format, and add implicit groups as needed
30863086
nodes_parsed = _parse_hierarchy_dict(data=nodes_normed_keys)
30873087
redundant_implicit_groups = []
3088+
to_delete_keys: list[str] = []
30883089

30893090
# empty hierarchies should be a no-op
30903091
if len(nodes_parsed) > 0:
@@ -3117,13 +3118,7 @@ async def create_hierarchy(
31173118
if overwrite:
31183119
# we will remove any nodes that collide with arrays and non-implicit groups defined in
31193120
# nodes
3120-
3121-
# track the keys of nodes we need to delete
3122-
to_delete_keys = []
3123-
to_delete_keys.extend(
3124-
[k for k, v in nodes_parsed.items() if k not in implicit_group_keys]
3125-
)
3126-
await asyncio.gather(*(store.delete_dir(key) for key in to_delete_keys))
3121+
to_delete_keys = [k for k in nodes_parsed if k not in implicit_group_keys]
31273122
else:
31283123
# This type is long.
31293124
coros: (
@@ -3183,7 +3178,11 @@ async def create_hierarchy(
31833178
else:
31843179
nodes_explicit[k] = v
31853180

3186-
async for key, node in create_nodes(store=store, nodes=nodes_explicit):
3181+
# Build every node before deleting or storing anything: metadata that no array or
3182+
# group can be built from then fails with the store untouched.
3183+
built = _build_nodes(store, nodes_explicit)
3184+
await asyncio.gather(*(store.delete_dir(key) for key in to_delete_keys))
3185+
async for key, node in _store_nodes(store, nodes_explicit, built):
31873186
yield key, node
31883187

31893188

@@ -3213,7 +3212,26 @@ async def create_nodes(
32133212
AsyncGroup | AsyncArray
32143213
The created nodes in the order they are created.
32153214
"""
3215+
async for key, node in _store_nodes(store, nodes, _build_nodes(store, nodes)):
3216+
yield key, node
3217+
32163218

3219+
def _build_nodes(
3220+
store: Store, nodes: Mapping[str, GroupMetadata | ArrayV2Metadata | ArrayV3Metadata]
3221+
) -> dict[str, AsyncGroup | AnyAsyncArray]:
3222+
"""The array or group each of `nodes` describes, at its path in `store`."""
3223+
return {
3224+
path: _build_node(store=store, path=path, metadata=meta) for path, meta in nodes.items()
3225+
}
3226+
3227+
3228+
async def _store_nodes(
3229+
store: Store,
3230+
nodes: Mapping[str, GroupMetadata | ArrayV2Metadata | ArrayV3Metadata],
3231+
built: Mapping[str, AsyncGroup | AnyAsyncArray],
3232+
) -> AsyncIterator[tuple[str, AsyncGroup | AnyAsyncArray]]:
3233+
"""Store the metadata of `nodes` and yield the nodes `_build_nodes` built from them
3234+
(see `create_nodes`)."""
32173235
# Note: the only way to alter this value is via the config. If that's undesirable for some reason,
32183236
# then we should consider adding a keyword argument to this function
32193237
semaphore = asyncio.Semaphore(config.get("async.concurrency"))
@@ -3241,7 +3259,7 @@ async def create_nodes(
32413259
node_name = created_key[: created_key.rfind("/")]
32423260
meta_out = nodes[node_name]
32433261
if meta_out.zarr_format == 3:
3244-
yield node_name, _build_node(store=store, path=node_name, metadata=meta_out)
3262+
yield node_name, built[node_name]
32453263
else:
32463264
# For zarr v2
32473265
# we only want to yield when both the metadata and attributes are created
@@ -3256,7 +3274,7 @@ async def create_nodes(
32563274
meta_done = _join_paths([node_name, ZARRAY_JSON]) in created_object_keys
32573275

32583276
if meta_done and attrs_done:
3259-
yield node_name, _build_node(store=store, path=node_name, metadata=meta_out)
3277+
yield node_name, built[node_name]
32603278

32613279
continue
32623280

‎tests/test_group.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1919,6 +1919,30 @@ async def test_create_hierarchy(
19191919
assert expected_meta == {k: v.metadata for k, v in created.items()}
19201920

19211921

1922+
@pytest.mark.parametrize("zarr_format", [2, 3])
1923+
def test_create_hierarchy_unbuildable_node_leaves_store_untouched(
1924+
monkeypatch: pytest.MonkeyPatch, zarr_format: ZarrFormat
1925+
) -> None:
1926+
"""`create_hierarchy` builds every node before it deletes or stores anything, so a
1927+
node that cannot be built fails with the store untouched, even when overwriting."""
1928+
store = MemoryStore()
1929+
group = zarr.create_group(store, zarr_format=zarr_format)
1930+
group.create_array("a", shape=(2,), chunks=(1,), dtype="int8")[:] = [1, 2]
1931+
before = dict(store._store_dict)
1932+
1933+
def unbuildable(**kwargs: object) -> None:
1934+
raise RuntimeError("cannot build this node")
1935+
1936+
monkeypatch.setattr(zarr.core.group, "_build_node", unbuildable)
1937+
with pytest.raises(RuntimeError, match="cannot build this node"):
1938+
dict(
1939+
zarr.create_hierarchy(
1940+
store=store, nodes={"a": GroupMetadata(zarr_format=zarr_format)}, overwrite=True
1941+
)
1942+
)
1943+
assert store._store_dict == before
1944+
1945+
19221946
@pytest.mark.parametrize("store", ["memory"], indirect=True)
19231947
@pytest.mark.parametrize("extant_node", ["array", "group"])
19241948
@pytest.mark.parametrize("impl", ["async", "sync"])

0 commit comments

Comments
 (0)