Skip to content
Merged
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
5 changes: 5 additions & 0 deletions packages/zarr-metadata/changes/4426.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
A model read by `from_json` or `from_key_value` shares no mutable state
with the document it was read from, as a document from `to_json` already
shares none with its model. A frozen model held the caller's own
dictionaries, so editing the input after reading it changed the model,
and could make `to_key_value` fail.
15 changes: 6 additions & 9 deletions packages/zarr-metadata/src/zarr_metadata/model/_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
MetadataValidationError,
StoreKey,
ValidationProblem,
arrays_to_tuples,
dump_store_json,
load_store_json,
parse_array_metadata_v2,
Expand Down Expand Up @@ -79,12 +78,8 @@ def from_json(cls, data: object) -> ZarrV3NamedConfig:
field = parse_metadata_field_v3(data)
if isinstance(field, str):
return cls(name=field, configuration={}, must_understand=True)
# Sound cast: parse_metadata_field_v3 checked the configuration is a
# string-keyed mapping of JSON values; arrays_to_tuples only converts
# lists to tuples within that shape.
configuration = cast(
"dict[str, JSONValue]", arrays_to_tuples(dict(field.get("configuration", {})))
)
# A read model shares no mutable state with what it read.
configuration = copy.deepcopy(dict(field.get("configuration", {})))
return cls(
name=field["name"],
configuration=configuration,
Expand Down Expand Up @@ -287,7 +282,8 @@ def to_json(self) -> ZarrV3ArrayMetadataJSON:

@classmethod
def from_json(cls, data: object) -> ZarrV3ArrayMetadata:
parsed = parse_array_metadata_v3(arrays_to_tuples(data))
# A read model shares no mutable state with what it read.
parsed = copy.deepcopy(parse_array_metadata_v3(data))
# Sound cast: the TypedDict types all non-standard keys as its
# `extra_items` (`ZarrV3ExtensionField`); the comprehension's inferred value
# type is the union over ALL keys because the key filter cannot narrow it.
Expand Down Expand Up @@ -458,7 +454,8 @@ def to_json(self) -> ZarrV2ArrayMetadataJSON:

@classmethod
def from_json(cls, data: object) -> ZarrV2ArrayMetadata:
parsed = parse_array_metadata_v2(arrays_to_tuples(data))
# A read model shares no mutable state with what it read.
parsed = copy.deepcopy(parse_array_metadata_v2(data))
return cls(
shape=parsed["shape"],
dtype=parsed["dtype"],
Expand Down
6 changes: 4 additions & 2 deletions packages/zarr-metadata/src/zarr_metadata/model/_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,8 @@ def to_json(self) -> ZarrV3GroupMetadataJSON:

@classmethod
def from_json(cls, data: object) -> ZarrV3GroupMetadata:
parsed = parse_group_metadata_v3(arrays_to_tuples(data))
# A read model shares no mutable state with what it read.
parsed = copy.deepcopy(parse_group_metadata_v3(data))
# Cast for narrowing across standard and arbitrary extra TypedDict items.
consolidated_raw = cast("object", parsed.get(ZARR_V3_CONSOLIDATED_METADATA_KEY, UNSET))
consolidated: ZarrV3ConsolidatedMetadata | UNSET
Expand Down Expand Up @@ -315,7 +316,8 @@ def to_json(self) -> ZarrV2GroupMetadataJSON:

@classmethod
def from_json(cls, data: object) -> ZarrV2GroupMetadata:
parsed = parse_group_metadata_v2(arrays_to_tuples(data))
# A read model shares no mutable state with what it read.
parsed = copy.deepcopy(parse_group_metadata_v2(data))
return cls(attributes=(dict(parsed["attributes"]) if "attributes" in parsed else UNSET))

@classmethod
Expand Down
14 changes: 14 additions & 0 deletions packages/zarr-metadata/tests/model/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,20 @@ def test_to_json_shares_no_mutable_state_with_model(
assert model.to_json() == baseline


@pytest.mark.parametrize("model", TO_JSON_NO_ALIASING_PARAMS)
def test_from_json_shares_no_mutable_state_with_its_input(
model: ZarrV3ArrayMetadata | ZarrV2ArrayMetadata,
) -> None:
"""Mutating the document a model was read from leaves the model unchanged."""
# Arrays as tuples: the reader has nothing to rebuild, so only a copy
# keeps the model apart from its input.
document = arrays_to_tuples(model.to_json())
read = type(model).from_json(document)
baseline = copy.deepcopy(read.to_json())
mutate_nested_containers(document)
assert read.to_json() == baseline


def test_v3_parser_accepts_bare_string_data_type() -> None:
"""V3 from_json accepts a bare-string data_type and re-serializes it canonically."""
doc = ZarrV3ArrayMetadata.create_default().to_json()
Expand Down
18 changes: 18 additions & 0 deletions packages/zarr-metadata/tests/model/test_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from zarr_metadata.model._validation import (
MetadataValidationError,
ValidationProblem,
arrays_to_tuples,
is_group_metadata_v2,
is_group_metadata_v3,
parse_group_metadata_v2,
Expand Down Expand Up @@ -602,3 +603,20 @@ def test_to_json_shares_no_mutable_state_with_model(
baseline = copy.deepcopy(model.to_json())
mutate_nested_containers(model.to_json())
assert model.to_json() == baseline


@pytest.mark.parametrize("model", TO_JSON_NO_ALIASING_PARAMS)
def test_from_json_shares_no_mutable_state_with_its_input(
model: ZarrV3GroupMetadata
| ZarrV2GroupMetadata
| ZarrV3ConsolidatedMetadata
| ZarrV2ConsolidatedMetadata,
) -> None:
"""Mutating the document a model was read from leaves the model unchanged."""
# Arrays as tuples: the reader has nothing to rebuild, so only a copy
# keeps the model apart from its input.
document = arrays_to_tuples(model.to_json())
read = type(model).from_json(document)
baseline = copy.deepcopy(read.to_json())
mutate_nested_containers(document)
assert read.to_json() == baseline
Loading