Skip to content

Commit dc50ec6

Browse files
d-v-bclaude
andcommitted
fix(group): adopt refreshed consolidated members in place
A group write replaced the handle's metadata with a copy holding the consolidated members it read again, so the handle no longer shared its consolidated dicts with subgroup handles taken earlier: an array deleted through such a subgroup was stored again by the parent's next write, and reappeared on reopen. `_refresh_consolidated` now returns, along with the copy it encodes, the members it replaced (with the consolidated dict that holds each), and `save_metadata` writes them back into those dicts once the store succeeds, unless the member was deleted or replaced meanwhile. `save_metadata` returns nothing again, and the group callers keep their metadata objects. A failed store leaves the members flagged, so a retry reads them again. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3bc802f commit dc50ec6

3 files changed

Lines changed: 91 additions & 31 deletions

File tree

‎src/zarr/core/group.py‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -899,9 +899,7 @@ async def get_group(self, path: str) -> AsyncGroup:
899899
return node
900900

901901
async def _save_metadata(self, ensure_parents: bool = False) -> None:
902-
# Adopt the metadata stored: its consolidated members may be newer.
903-
stored = await save_metadata(self.store_path, self.metadata, ensure_parents=ensure_parents)
904-
object.__setattr__(self, "metadata", stored)
902+
await save_metadata(self.store_path, self.metadata, ensure_parents=ensure_parents)
905903

906904
@property
907905
def path(self) -> str:
@@ -2117,7 +2115,7 @@ async def update_attributes_async(self, new_attributes: dict[str, Any]) -> Group
21172115
new_metadata = replace(self.metadata, attributes=new_attributes)
21182116

21192117
# Write new metadata
2120-
new_metadata = await save_metadata(self.store_path, new_metadata)
2118+
await save_metadata(self.store_path, new_metadata)
21212119

21222120
async_group = replace(self._async_group, metadata=new_metadata)
21232121
return replace(self, _async_group=async_group)

‎src/zarr/core/metadata/io.py‎

Lines changed: 62 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -152,34 +152,66 @@ async def _refresh_array(store_path: StorePath, member: ArrayMetadata) -> ArrayM
152152
return current
153153

154154

155-
async def _refresh_consolidated(store_path: StorePath, metadata: GroupMetadata) -> GroupMetadata:
155+
class _Refreshed(NamedTuple):
156+
"""A member of consolidated metadata that `_refresh_consolidated` read again from the
157+
member's own document."""
158+
159+
members: dict[str, ArrayMetadata | GroupMetadata]
160+
"""The consolidated metadata that holds the member, by member name."""
161+
name: str
162+
stale: ArrayMetadata
163+
current: ArrayMetadata
164+
165+
def adopt(self) -> None:
166+
"""Replace the stale member with the current one in place, so every handle that
167+
shares this consolidated metadata sees it; unless the member was deleted or
168+
replaced since it was read."""
169+
if self.members.get(self.name) is self.stale:
170+
self.members[self.name] = self.current
171+
172+
173+
async def _refresh_consolidated(
174+
store_path: StorePath, metadata: GroupMetadata
175+
) -> tuple[GroupMetadata, list[_Refreshed]]:
156176
"""`metadata` with each member of its consolidated metadata that was read from a
157-
document that had to be upgraded replaced by the metadata of the member's own
158-
document as it now is (see `_refresh_array`), read concurrently: the member document
159-
may have changed since, so the consolidated copy is never stored as if it were
160-
valid."""
177+
document that had to be upgraded, at any depth, replaced by the metadata of the
178+
member's own document as it now is (see `_refresh_array`), read concurrently, and
179+
the members it replaced: the member document may have changed since, so the
180+
consolidated copy is never stored as if it were valid. `metadata` is left as it is,
181+
for the group to adopt the members (see `_Refreshed.adopt`) once they are stored."""
161182
from zarr.core.group import GroupMetadata
162183

163184
consolidated = metadata.consolidated_metadata
164185
if consolidated is None:
165-
return metadata
166-
stale = {
186+
return metadata, []
187+
groups = {
167188
name: member
168189
for name, member in consolidated.metadata.items()
169-
if isinstance(member, GroupMetadata) or member._stored_document_upgraded
190+
if isinstance(member, GroupMetadata)
170191
}
171-
refreshed = await asyncio.gather(
172-
*(
173-
_refresh_consolidated(store_path / name, member)
174-
if isinstance(member, GroupMetadata)
175-
else _refresh_array(store_path / name, member)
176-
for name, member in stale.items()
177-
)
192+
arrays = {
193+
name: member
194+
for name, member in consolidated.metadata.items()
195+
if not isinstance(member, GroupMetadata) and member._stored_document_upgraded
196+
}
197+
nested, current = await asyncio.gather(
198+
asyncio.gather(*(_refresh_consolidated(store_path / n, m) for n, m in groups.items())),
199+
asyncio.gather(*(_refresh_array(store_path / n, m) for n, m in arrays.items())),
178200
)
179-
if all(new is old for new, old in zip(refreshed, stale.values(), strict=True)):
180-
return metadata
181-
members = {**consolidated.metadata, **dict(zip(stale, refreshed, strict=True))}
182-
return replace(metadata, consolidated_metadata=replace(consolidated, metadata=members))
201+
refreshed = [
202+
_Refreshed(consolidated.metadata, name, stale, new)
203+
for (name, stale), new in zip(arrays.items(), current, strict=True)
204+
if new is not stale
205+
]
206+
members = dict(consolidated.metadata)
207+
members.update({member.name: member.current for member in refreshed})
208+
for name, (group, inner) in zip(groups, nested, strict=True):
209+
members[name] = group
210+
refreshed.extend(inner)
211+
if not refreshed:
212+
return metadata, []
213+
consolidated = replace(consolidated, metadata=members)
214+
return replace(metadata, consolidated_metadata=consolidated), refreshed
183215

184216

185217
def _build_parents(store_path: StorePath, zarr_format: ZarrFormat) -> dict[str, GroupMetadata]:
@@ -201,12 +233,12 @@ def _build_parents(store_path: StorePath, zarr_format: ZarrFormat) -> dict[str,
201233
return parents
202234

203235

204-
async def save_metadata[M: (ArrayMetadata, GroupMetadata)](
205-
store_path: StorePath, metadata: M, ensure_parents: bool = False
206-
) -> M:
207-
"""Asynchronously save the array or group metadata, and return the metadata saved:
208-
`metadata`, but for a group, with the consolidated members it stored (see
209-
`_refresh_consolidated`), for the group to adopt.
236+
async def save_metadata(
237+
store_path: StorePath, metadata: ArrayMetadata | GroupMetadata, ensure_parents: bool = False
238+
) -> None:
239+
"""Asynchronously save the array or group metadata. A group adopts, in place, the
240+
members of its consolidated metadata that had to be read again to store it (see
241+
`_refresh_consolidated`), once they are stored.
210242
211243
Parameters
212244
----------
@@ -223,9 +255,10 @@ async def save_metadata[M: (ArrayMetadata, GroupMetadata)](
223255
"""
224256
from zarr.core.group import GroupMetadata
225257

258+
refreshed: list[_Refreshed] = []
226259
if isinstance(metadata, GroupMetadata):
227260
# The one place group metadata is stored, and with it consolidated metadata.
228-
metadata = await _refresh_consolidated(store_path, metadata)
261+
metadata, refreshed = await _refresh_consolidated(store_path, metadata)
229262
to_save = metadata.to_buffer_dict(default_buffer_prototype())
230263
set_awaitables = [store_documents(store_path, to_save)]
231264

@@ -265,4 +298,6 @@ async def save_metadata[M: (ArrayMetadata, GroupMetadata)](
265298
) from e
266299

267300
await asyncio.gather(*set_awaitables)
268-
return metadata
301+
# Only once stored: a group whose store failed keeps the members flagged, to read again.
302+
for member in refreshed:
303+
member.adopt()

‎tests/test_metadata/test_upgrades.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -920,6 +920,33 @@ async def recording_get(self: LocalStore, key: str, *args: Any, **kwargs: Any) -
920920
assert reads == []
921921

922922

923+
@pytest.mark.filterwarnings("ignore:Consolidated metadata is currently not part:UserWarning")
924+
@pytest.mark.parametrize("zarr_format", [2, 3])
925+
def test_group_write_keeps_consolidated_metadata_shared_with_subgroups(
926+
tmp_path: Path, zarr_format: Literal[2, 3]
927+
) -> None:
928+
"""A subgroup handle taken from a group shares the group's consolidated metadata, also
929+
once the group has adopted the upgraded members its first write stored: an array
930+
deleted through the subgroup is gone from what the group stores next."""
931+
path = tmp_path / "group.zarr"
932+
created = zarr.open_group(path, mode="w", zarr_format=zarr_format).create_group("g")
933+
for name in ("a", "c"):
934+
created.create_array(name, shape=(3,), chunks=(3,), dtype="int16")
935+
zarr.consolidate_metadata(path)
936+
_rewrite_consolidated(path, zarr_format, "g/a", _store_zero)
937+
with pytest.warns(ZarrUserWarning, match="is read as"):
938+
group = zarr.open_group(path, mode="r+", use_consolidated=True)
939+
subgroup = group["g"]
940+
assert isinstance(subgroup, zarr.Group)
941+
942+
group.attrs["x"] = 1
943+
del subgroup["c"]
944+
group.attrs["y"] = 2
945+
946+
reopened = zarr.open_group(path, mode="r", use_consolidated=True)
947+
assert sorted(dict(reopened.members(max_depth=None))) == ["g", "g/a"]
948+
949+
923950
@pytest.mark.filterwarnings("ignore:Consolidated metadata is currently not part:UserWarning")
924951
@pytest.mark.parametrize("zarr_format", [2, 3])
925952
@pytest.mark.parametrize("replacement", ["group", "invalid", "none"])

0 commit comments

Comments
 (0)