Skip to content

Commit 3bc802f

Browse files
d-v-bclaude
andcommitted
perf(metadata): read each upgraded member once, concurrently, and adopt it
A group handle kept the consolidated copies of upgraded members flagged, so every later group write re-read every such member, one after another, and read each twice on the first write (once to parse, once to diff). - `save_metadata` returns the metadata it stored; `AsyncGroup._save_metadata` (attrs, `update_attributes`, `delitem`, `consolidate_metadata`) and `Group.update_attributes_async` adopt it, so later writes read no member. - The refresh visits only nested groups and flagged members, and reads them with one `asyncio.gather`. The documents it reads are the ones the upsert diffs against (`read_documents` + `upsert_metadata(..., stored)`), and the array write path does the same. - `parse_stored_array` (documents -> silently marked metadata) replaces `read_stored_array`'s `(metadata, bool)` tuple, and is the one "read, mark, don't warn" path, also for code-built metadata. - A flagged member whose own document is gone or cannot be read (invalid, replaced by a group) keeps its consolidated copy instead of failing every group write. - `parse_array_metadata` of a metadata object reads it as a stored document only when `ArrayV2Metadata.chunks` holds a 0, the one chunk size that constructors still accept and the upgrades change. This removes the per-construction `to_dict` + upgrade (AsyncArray() back to 3.4.0 speed) and building arrays from codec configurations holding NumPy scalars works again, as in 3.4.0. - `create_hierarchy` documents that it stores a group's consolidated metadata as given. - Tests: second group write reads no member; nested member refresh; member without a readable document; NumPy-scalar codec configuration; stale handle whose inner chunk shape alone changed (kills `_chunk_layout` returning only the outer grid). Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent bc306aa commit 3bc802f

6 files changed

Lines changed: 254 additions & 109 deletions

File tree

‎src/zarr/core/_json.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def buffer_to_json(buffer: Buffer) -> JSON:
4141
return cast("JSON", json.loads(buffer.to_bytes()))
4242

4343

44-
def json_equal(a: object, b: object) -> bool:
44+
def json_equal(a: JSON, b: JSON) -> bool:
4545
"""Whether two JSON values have the same JSON encoding. Python compares `True` and
4646
`1`, or `1.0` and `1`, as equal; JSON does not."""
4747
return json.dumps(a) == json.dumps(b)

‎src/zarr/core/array.py‎

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,13 @@
118118
ArrayV2MetadataDict,
119119
ArrayV3Metadata,
120120
)
121-
from zarr.core.metadata.io import read_stored_array, save_metadata, upsert_metadata
122-
from zarr.core.metadata.upgrades import mark_upgraded, upgrade_array_document
121+
from zarr.core.metadata.io import (
122+
ARRAY_DOCUMENTS,
123+
parse_stored_array,
124+
read_documents,
125+
save_metadata,
126+
upsert_metadata,
127+
)
123128
from zarr.core.metadata.v2 import (
124129
CompressorLikev2,
125130
get_object_codec_id,
@@ -202,29 +207,18 @@ def _chunk_sizes_from_shape(
202207
return tuple(result)
203208

204209

205-
def _as_json(value: Any) -> Any:
206-
"""`value`, as `to_dict` returns it, with its tuples as JSON arrays."""
207-
match value:
208-
case tuple() | list():
209-
return [_as_json(item) for item in value]
210-
case dict():
211-
return {key: _as_json(item) for key, item in value.items()}
212-
return value
213-
214-
215210
def parse_array_metadata(data: Any, path: str | None = None) -> ArrayMetadata:
216211
"""Array metadata from a metadata object or a metadata document, naming the array at
217212
`path` in warnings about how an invalid document was read.
218213
219-
The metadata constructors accept chunk sizes that only an invalid document holds
220-
(such as 0), as they always have; such metadata is read as its document is (see
221-
`zarr.core.metadata.upgrades`), so an array can be built from it. No data was read
222-
or written under those chunk sizes, so none of its readings is a warning."""
214+
`ArrayV2Metadata` accepts a chunk size of 0, as it always has, though only an
215+
invalid document holds one: such metadata is read as the documents it would store
216+
are (see `zarr.core.metadata.upgrades`), so an array can be built from it. No data
217+
was read or written under that chunk size, so the reading is silent."""
218+
if isinstance(data, ArrayV2Metadata) and 0 in data.chunks:
219+
return parse_stored_array(data.to_buffer_dict(default_buffer_prototype()), 2)
223220
if isinstance(data, ArrayMetadata):
224-
document, readings = upgrade_array_document(_as_json(data.to_dict()), data.zarr_format)
225-
if not readings:
226-
return data
227-
return mark_upgraded(parse_array_metadata(dict(document)), [None for _ in readings], path)
221+
return data
228222
if isinstance(data, dict):
229223
zarr_format = data.get("zarr_format")
230224
if zarr_format == 3:
@@ -1652,16 +1646,20 @@ async def _store_upgraded_document(self) -> None:
16521646
"""
16531647
if not self.metadata._stored_document_upgraded:
16541648
return
1655-
read = await read_stored_array(self.store_path, self.metadata.zarr_format)
1656-
if read is not None:
1657-
current, upgraded = read
1649+
zarr_format = self.metadata.zarr_format
1650+
documents = await read_documents(self.store_path, ARRAY_DOCUMENTS[zarr_format])
1651+
try:
1652+
current = parse_stored_array(documents, zarr_format)
1653+
except ArrayNotFoundError:
1654+
pass
1655+
else:
16581656
if _chunk_layout(current) != _chunk_layout(self.metadata):
16591657
raise ValueError(
16601658
f"The metadata stored for the array at {str(self.store_path)!r} has "
16611659
"changed since this array was opened: reopen the array to write to it."
16621660
)
1663-
if upgraded:
1664-
await upsert_metadata(self.store_path, current)
1661+
if current._stored_document_upgraded:
1662+
await upsert_metadata(self.store_path, current, documents)
16651663
object.__setattr__(self.metadata, "_stored_document_upgraded", False)
16661664

16671665
async def _set_selection(
@@ -4893,7 +4891,9 @@ async def create_array(
48934891
)
48944892

48954893

4896-
def _chunk_layout(metadata: ArrayMetadata) -> tuple[object, tuple[int, ...] | None]:
4894+
def _chunk_layout(
4895+
metadata: ArrayMetadata,
4896+
) -> tuple[tuple[int, ...] | ChunkGridMetadata, tuple[int, ...] | None]:
48974897
"""How an array's chunks are laid out: its chunk grid and, if it is sharded, the
48984898
inner chunk shape."""
48994899
grid = metadata.chunks if isinstance(metadata, ArrayV2Metadata) else metadata.chunk_grid

‎src/zarr/core/group.py‎

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

901901
async def _save_metadata(self, ensure_parents: bool = False) -> None:
902-
await save_metadata(self.store_path, self.metadata, ensure_parents=ensure_parents)
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)
903905

904906
@property
905907
def path(self) -> str:
@@ -2115,7 +2117,7 @@ async def update_attributes_async(self, new_attributes: dict[str, Any]) -> Group
21152117
new_metadata = replace(self.metadata, attributes=new_attributes)
21162118

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

21202122
async_group = replace(self._async_group, metadata=new_metadata)
21212123
return replace(self, _async_group=async_group)
@@ -3032,6 +3034,8 @@ async def create_hierarchy(
30323034
```{'': GroupMetadata, 'a': GroupMetadata, 'b': Groupmetadata}```
30333035
30343036
After input parsing, this function then creates all the nodes in the hierarchy concurrently.
3037+
The metadata of each node is stored as given: the consolidated metadata of a group is
3038+
stored as it is, without reading the documents of its members.
30353039
30363040
Arrays and Groups are yielded in the order they are created. This order is not stable and
30373041
should not be relied on.

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

Lines changed: 86 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@
1010
from zarr.core._json import buffer_to_json_object, json_equal
1111
from zarr.core.buffer.core import default_buffer_prototype
1212
from zarr.core.buffer.cpu import buffer_prototype as cpu_buffer_prototype
13-
from zarr.core.metadata.upgrades import upgrade_array_document
13+
from zarr.core.common import ZARR_JSON, ZARRAY_JSON, ZATTRS_JSON
14+
from zarr.core.metadata.upgrades import mark_upgraded, upgrade_array_document
1415
from zarr.errors import ArrayNotFoundError, ContainsArrayError
1516
from zarr.storage._common import StorePath, ensure_no_existing_node
1617

1718
if TYPE_CHECKING:
18-
from collections.abc import Iterator, Mapping
19+
from collections.abc import Iterable, Iterator, Mapping
1920

2021
from zarr.core.buffer import Buffer
2122
from zarr.core.common import JSON, ZarrFormat
@@ -66,7 +67,7 @@ def _diff(
6667
case list(), list():
6768
for index, pair in enumerate(zip_longest(stored, new, fillvalue=ABSENT)):
6869
yield from _diff((*path, index), *pair)
69-
case _ if ABSENT in (stored, new) or not json_equal(stored, new):
70+
case _ if stored is ABSENT or new is ABSENT or not json_equal(stored, new):
7071
yield DocumentChange(path, stored, new)
7172

7273

@@ -77,73 +78,107 @@ async def store_documents(store_path: StorePath, documents: Mapping[str, Buffer]
7778
)
7879

7980

81+
async def read_documents(store_path: StorePath, keys: Iterable[str]) -> dict[str, Buffer]:
82+
"""The documents stored under `store_path` at `keys`, read concurrently, by key; a
83+
key with no document is left out."""
84+
keys = tuple(keys)
85+
buffers = await asyncio.gather(
86+
*((store_path / key).get(prototype=cpu_buffer_prototype) for key in keys)
87+
)
88+
return {key: buf for key, buf in zip(keys, buffers, strict=True) if buf is not None}
89+
90+
8091
async def upsert_metadata(
81-
store_path: StorePath, metadata: ArrayMetadata | GroupMetadata
92+
store_path: StorePath, metadata: ArrayMetadata | GroupMetadata, stored: Mapping[str, Buffer]
8293
) -> tuple[DocumentChange, ...]:
83-
"""Store the documents of `metadata` under `store_path` that differ from the stored
84-
ones, and return how they differed (see `diff_documents`): empty if nothing was
85-
stored.
94+
"""Store the documents of `metadata` under `store_path` that differ from `stored`,
95+
the documents `read_documents` read there, and return how they differed (see
96+
`diff_documents`): empty if nothing was stored.
8697
87-
The documents are encoded before the store is read, so metadata that cannot be
88-
stored fails with the store untouched.
98+
The documents are encoded before any is stored, so metadata that cannot be stored
99+
fails with the store untouched.
89100
"""
90101
documents = metadata.to_buffer_dict(default_buffer_prototype())
91-
stored = await asyncio.gather(
92-
*((store_path / key).get(prototype=cpu_buffer_prototype) for key in documents)
93-
)
94102
changes = diff_documents(
95-
{
96-
key: buffer_to_json_object(buf)
97-
for key, buf in zip(documents, stored, strict=True)
98-
if buf is not None
99-
},
103+
{key: buffer_to_json_object(buf) for key, buf in stored.items() if key in documents},
100104
{key: buffer_to_json_object(buf) for key, buf in documents.items()},
101105
)
102106
changed = {change.path[0] for change in changes}
103107
await store_documents(store_path, {k: v for k, v in documents.items() if k in changed})
104108
return changes
105109

106110

107-
async def read_stored_array(
108-
store_path: StorePath, zarr_format: ZarrFormat
109-
) -> tuple[ArrayMetadata, bool] | None:
110-
"""The metadata of the array document stored at `store_path` as it now is, read with
111-
the upgrades but without their warnings (the handle that asks has warned), and
112-
whether the document had to be upgraded; `None` if no array document is stored
113-
there."""
114-
from zarr.core.array import get_array_metadata, parse_array_metadata
111+
ARRAY_DOCUMENTS: Final[Mapping[ZarrFormat, tuple[str, ...]]] = {
112+
2: (ZARRAY_JSON, ZATTRS_JSON),
113+
3: (ZARR_JSON,),
114+
}
115+
"""The store keys of the metadata documents of an array of each Zarr format."""
115116

116-
try:
117-
stored = await get_array_metadata(store_path, zarr_format=zarr_format)
118-
except ArrayNotFoundError:
119-
return None
117+
118+
def parse_stored_array(documents: Mapping[str, Buffer], zarr_format: ZarrFormat) -> ArrayMetadata:
119+
"""The metadata of an array from its documents (by store key, see `ARRAY_DOCUMENTS`),
120+
read with the upgrades but without their warnings (whoever asks has warned, or reads
121+
metadata built in code), and marked (see `mark_upgraded`) if they had to be
122+
upgraded. Raises `ArrayNotFoundError` if there is no array document among them."""
123+
from zarr.core.array import (
124+
_array_metadata_dict_v2,
125+
_array_metadata_dict_v3,
126+
parse_array_metadata,
127+
)
128+
129+
if zarr_format == 2 and ZARRAY_JSON in documents:
130+
stored = _array_metadata_dict_v2(documents[ZARRAY_JSON], documents.get(ZATTRS_JSON))
131+
elif zarr_format == 3 and ZARR_JSON in documents:
132+
stored = _array_metadata_dict_v3(documents[ZARR_JSON])
133+
else:
134+
raise ArrayNotFoundError(f"No Zarr format {zarr_format} array metadata document.")
120135
upgraded, readings = upgrade_array_document(stored, zarr_format)
121-
return parse_array_metadata(upgraded, str(store_path)), bool(readings)
136+
return mark_upgraded(parse_array_metadata(dict(upgraded)), [None] * len(readings), None)
137+
138+
139+
async def _refresh_array(store_path: StorePath, member: ArrayMetadata) -> ArrayMetadata:
140+
"""The metadata of the array document stored at `store_path` as it now is, after
141+
storing its upgrade if it needs one, for `member`, a member of consolidated metadata
142+
that was read from a document that had to be upgraded; `member` itself if no array
143+
document that can be read is stored there (it was deleted, or replaced by a group)."""
144+
documents = await read_documents(store_path, ARRAY_DOCUMENTS[member.zarr_format])
145+
try:
146+
current = parse_stored_array(documents, member.zarr_format)
147+
except (KeyError, TypeError, ValueError):
148+
return member
149+
if current._stored_document_upgraded:
150+
await upsert_metadata(store_path, current, documents)
151+
object.__setattr__(current, "_stored_document_upgraded", False)
152+
return current
122153

123154

124155
async def _refresh_consolidated(store_path: StorePath, metadata: GroupMetadata) -> GroupMetadata:
125156
"""`metadata` with each member of its consolidated metadata that was read from a
126157
document that had to be upgraded replaced by the metadata of the member's own
127-
document as it now is, after storing that document's upgrade if it needs one: the
128-
member document may have changed since, so the consolidated copy is never stored
129-
as if it were valid."""
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."""
130161
from zarr.core.group import GroupMetadata
131162

132163
consolidated = metadata.consolidated_metadata
133164
if consolidated is None:
134165
return metadata
135-
members = dict(consolidated.metadata)
136-
for name, member in consolidated.metadata.items():
137-
if isinstance(member, GroupMetadata):
138-
members[name] = await _refresh_consolidated(store_path / name, member)
139-
elif member._stored_document_upgraded:
140-
read = await read_stored_array(store_path / name, member.zarr_format)
141-
if read is not None:
142-
members[name], upgraded = read
143-
if upgraded:
144-
await upsert_metadata(store_path / name, members[name])
145-
if all(members[name] is member for name, member in consolidated.metadata.items()):
166+
stale = {
167+
name: member
168+
for name, member in consolidated.metadata.items()
169+
if isinstance(member, GroupMetadata) or member._stored_document_upgraded
170+
}
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+
)
178+
)
179+
if all(new is old for new, old in zip(refreshed, stale.values(), strict=True)):
146180
return metadata
181+
members = {**consolidated.metadata, **dict(zip(stale, refreshed, strict=True))}
147182
return replace(metadata, consolidated_metadata=replace(consolidated, metadata=members))
148183

149184

@@ -166,10 +201,12 @@ def _build_parents(store_path: StorePath, zarr_format: ZarrFormat) -> dict[str,
166201
return parents
167202

168203

169-
async def save_metadata(
170-
store_path: StorePath, metadata: ArrayMetadata | GroupMetadata, ensure_parents: bool = False
171-
) -> None:
172-
"""Asynchronously save the array or group metadata.
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.
173210
174211
Parameters
175212
----------
@@ -228,3 +265,4 @@ async def save_metadata(
228265
) from e
229266

230267
await asyncio.gather(*set_awaitables)
268+
return metadata

‎tests/test_metadata/test_io.py‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,14 @@
1111
import zarr
1212
from zarr.core.buffer import cpu
1313
from zarr.core.metadata import ArrayV2Metadata, ArrayV3Metadata
14-
from zarr.core.metadata.io import ABSENT, DocumentChange, diff_documents, upsert_metadata
14+
from zarr.core.metadata.io import (
15+
ABSENT,
16+
ARRAY_DOCUMENTS,
17+
DocumentChange,
18+
diff_documents,
19+
read_documents,
20+
upsert_metadata,
21+
)
1522
from zarr.core.sync import sync
1623
from zarr.storage import MemoryStore, StorePath
1724

@@ -143,6 +150,14 @@ def _legacy(zarr_format: Literal[2, 3]) -> tuple[StorePath, ArrayV2Metadata | Ar
143150
return StorePath(store), array.metadata
144151

145152

153+
def _upsert(
154+
store_path: StorePath, metadata: ArrayV2Metadata | ArrayV3Metadata
155+
) -> tuple[DocumentChange, ...]:
156+
"""Upsert `metadata` against the documents stored at `store_path`."""
157+
stored = sync(read_documents(store_path, ARRAY_DOCUMENTS[metadata.zarr_format]))
158+
return sync(upsert_metadata(store_path, metadata, stored))
159+
160+
146161
@pytest.mark.parametrize("zarr_format", [2, 3])
147162
def test_upsert_metadata_stores_documents_that_differ(zarr_format: Literal[2, 3]) -> None:
148163
"""The documents that differ from the stored ones are stored, and the changes are
@@ -155,7 +170,7 @@ def test_upsert_metadata_stores_documents_that_differ(zarr_format: Literal[2, 3]
155170
("chunks", 0) if zarr_format == 2 else ("chunk_grid", "configuration", "chunk_shape", 0)
156171
)
157172

158-
changes = sync(upsert_metadata(store_path, metadata))
173+
changes = _upsert(store_path, metadata)
159174

160175
assert changes == (DocumentChange((key, *chunk_path), 0, 3),)
161176
assert store_path.store.sets == 1
@@ -172,12 +187,12 @@ def test_upsert_metadata_identical_stores_nothing(zarr_format: Literal[2, 3]) ->
172187
)
173188
store.sets = 0
174189

175-
assert sync(upsert_metadata(StorePath(store), array.metadata)) == ()
190+
assert _upsert(StorePath(store), array.metadata) == ()
176191
assert store.sets == 0
177192

178193

179194
def test_upsert_metadata_unstorable_leaves_store_untouched(monkeypatch: pytest.MonkeyPatch) -> None:
180-
"""Metadata that cannot be encoded fails before the store is read or written."""
195+
"""Metadata that cannot be encoded fails before the store is written."""
181196
store_path, metadata = _legacy(3)
182197
before = _documents(store_path.store)
183198

@@ -186,7 +201,7 @@ def refuse(*args: object) -> None:
186201

187202
monkeypatch.setattr(ArrayV3Metadata, "to_buffer_dict", refuse)
188203
with pytest.raises(ValueError, match="cannot be stored"):
189-
sync(upsert_metadata(store_path, metadata))
204+
_upsert(store_path, metadata)
190205
assert _documents(store_path.store) == before
191206

192207

@@ -195,5 +210,5 @@ def test_upsert_metadata_stored_document_not_an_object() -> None:
195210
store_path, metadata = _legacy(3)
196211
sync(store_path.store.set("zarr.json", cpu.Buffer.from_bytes(b"[]")))
197212
with pytest.raises(TypeError, match="Expected a JSON object, got list"):
198-
sync(upsert_metadata(store_path, metadata))
213+
_upsert(store_path, metadata)
199214
assert _documents(store_path.store) == {"zarr.json": []}

0 commit comments

Comments
 (0)