Skip to content
Closed
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
1 change: 1 addition & 0 deletions packages/zarr-metadata/changes/396.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Zarr v2 array metadata is now read against a scope, as v3 metadata is. `zarr_metadata.v2.definition` defines the data types zarr-python 2.x writes (one definition per NumPy family) and 21 of the codecs numcodecs 0.16 configures, files them in `CORE_V2`, and reads one `dtype` or codec with `resolve_dtype_v2` and `resolve_codec_v2`. `validate_array_metadata_v2` now reports a dtype string that is not a NumPy typestr or that its family does not take, a codec parameter outside what numcodecs accepts, and a fill value its dtype does not take; a dtype or codec id the package does not model is left unjudged as before. `ZarrV2ArrayMetadata.create_default` given a dtype whose family does not take `0` as a fill value, such as `|b1` or `|S3`, now sets `fill_value` to `null` unless one is given.
4 changes: 3 additions & 1 deletion packages/zarr-metadata/docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ The package is organized to mirror the structure of the Zarr specifications:
typing spec defines them, with every problem located, and
`json_schema`, which writes what `check` reads as a JSON Schema
- [`zarr_metadata.v2`](v2.md) — `TypedDict` shapes for Zarr v2 documents
(`.zarray`, `.zgroup`, `.zattrs`, `.zmetadata`)
(`.zarray`, `.zgroup`, `.zattrs`, `.zmetadata`), and
`zarr_metadata.v2.definition`: the v2 dtypes and numcodecs codecs as
definitions, `CORE_V2`, and the readers of one `dtype` or codec
- [`zarr_metadata.v3`](v3/index.md) — `TypedDict` shapes for Zarr v3
documents, with subpackages for [chunk grids](v3/chunk_grid.md),
[chunk key encodings](v3/chunk_key_encoding.md), [codecs](v3/codec.md),
Expand Down
7 changes: 7 additions & 0 deletions packages/zarr-metadata/docs/api/v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,10 @@ title: v2
::: zarr_metadata.v2.codec

::: zarr_metadata.v2.consolidated

::: zarr_metadata.v2.definition
options:
inherited_members: false
show_if_no_docstring: false

::: zarr_metadata.v2.data_type
8 changes: 8 additions & 0 deletions packages/zarr-metadata/src/zarr_metadata/model/_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
)
from zarr_metadata.v2.array import ZARR_V2_ARRAY_METADATA_STORE_KEY
from zarr_metadata.v2.attributes import ZARR_V2_ATTRIBUTES_STORE_KEY
from zarr_metadata.v2.definition import resolve_dtype_v2
from zarr_metadata.v3._definition import (
ChunkGridDefinition,
ChunkKeyEncodingDefinition,
Expand Down Expand Up @@ -612,6 +613,13 @@ def create_default(cls, **overrides: Unpack[ZarrV2ArrayMetadataPartial]) -> Zarr
filters=None,
attributes=UNSET,
)
# The default fill value, `0`, is a value of the numeric families
# only: a dtype of another family given without a fill value takes
# `null`, which every family takes.
if "dtype" in overrides and "fill_value" not in overrides:
dtype, _ = resolve_dtype_v2(overrides["dtype"])
if len(fill_value_problems(dtype, 0)) != 0:
overrides["fill_value"] = None
return default.update(**overrides)

def __eq__(self, other: object) -> bool:
Expand Down
102 changes: 28 additions & 74 deletions packages/zarr-metadata/src/zarr_metadata/model/_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,14 @@
refine_json,
refine_user_data,
shown_key,
validate_json,
with_input,
within,
)
from zarr_metadata._json import is_canonical_json as _is_canonical_json
from zarr_metadata._sentinel import UNSET
from zarr_metadata._typed_json import typeddict_keys
from zarr_metadata.v2.array import ZarrV2ArrayMetadataJSON
from zarr_metadata.v2.definition import resolve_codec_v2, resolve_dtype_v2
from zarr_metadata.v2.group import ZarrV2GroupMetadataJSON
from zarr_metadata.v3._definition import (
Chunk,
Expand Down Expand Up @@ -236,30 +236,6 @@ def dimension_lengths(
return tuple(value), ()


def _is_dtype_v2(value: object) -> bool:
"""Whether `value` is shaped like a v2 dtype: a string or field records.

A field record is a `(name, dtype)` or `(name, dtype, shape)` sequence,
where `dtype` is itself a string or nested field records and `shape` is a
sequence of int. The string content is NOT interpreted — whether the
string names a real dtype is domain validity, not structure.
"""
if isinstance(value, str):
return True
if not _is_array(value):
return False
for record in value:
if not _is_array(record) or len(record) not in (2, 3):
return False
if not isinstance(record[0], str):
return False
if not _is_dtype_v2(record[1]):
return False
if len(record) == 3 and not _is_int_sequence(record[2]):
return False
return True


def _is_canonical_dtype_v2(value: object) -> bool:
"""Whether a validated v2 dtype uses the tuple-backed public representation."""
if isinstance(value, str):
Expand Down Expand Up @@ -324,24 +300,6 @@ def _is_canonical_array_metadata_v2(value: object) -> bool:
)


def _is_codec_v2(value: object) -> bool:
"""Whether `value` is shaped like a v2 codec config: a mapping with a string `id`."""
return isinstance(value, Mapping) and isinstance(
cast("Mapping[object, object]", value).get("id"), str
)


def _validate_codec_v2(value: object, loc: tuple[str | int, ...]) -> tuple[ValidationProblem, ...]:
"""Validate a v2 codec's required shape and JSON-valued configuration, `value` sitting at `loc`."""
if not _is_codec_v2(value):
return (
ValidationProblem(
loc, "expected a codec configuration with a string 'id'", "invalid_type"
),
)
return validate_json(value, loc)


def validate_attributes(value: object) -> tuple[ValidationProblem, ...]:
"""Validate an `attributes` value: a mapping with string keys.

Expand Down Expand Up @@ -693,10 +651,10 @@ def parse_array_metadata_v3(
def validate_array_metadata_v2(value: object) -> tuple[ValidationProblem, ...]:
"""Return every reason `value` is not a structurally-valid v2 array doc.

Checks structure, not domain validity: `dtype` must be a string or field
records, but the string content is not interpreted; `compressor` and
`filters` are required keys that may be `None`, and otherwise must be
codec configurations (mappings with a string `id`).
`dtype`, `compressor` and `filters` are read in `CORE_V2`: a dtype or
codec the scope refuses is a problem, one it does not claim is not;
`fill_value` is judged by the dtype the scope read. `compressor` and
`filters` are required keys that may be `None`.
"""
if not isinstance(value, Mapping):
return not_an_object(value)
Expand All @@ -722,48 +680,44 @@ def validate_array_metadata_v2(value: object) -> tuple[ValidationProblem, ...]:
"invalid_value",
)
)
dtype = None
if "dtype" in doc:
# JSON first, nested no deeper than a reader walks, then its shape:
# field records nest a dtype two levels a record, without bound.
found = validate_json(doc["dtype"], ("dtype",))
# Read in CORE_V2: a typestr by its family, field records as a struct.
dtype, found = resolve_dtype_v2(doc["dtype"], loc=("dtype",))
problems.extend(found)
if len(found) == 0 and not _is_dtype_v2(doc["dtype"]):
problems.append(
ValidationProblem(
("dtype",),
"expected a v2 dtype string or an array of field records",
"invalid_type",
)
)
if "order" in doc and doc["order"] not in ("C", "F"):
problems.append(outside_of(("order",), doc["order"], ("C", "F")))
if "compressor" in doc:
compressor = doc["compressor"]
if compressor is not None:
problems.extend(_validate_codec_v2(compressor, ("compressor",)))
problems.extend(resolve_codec_v2(compressor, loc=("compressor",))[1])
if "filters" in doc:
filters = doc["filters"]
if filters is not None and (
not _is_array(filters) or not all(_is_codec_v2(item) for item in filters)
):
problems.append(
ValidationProblem(
("filters",),
"expected null or an array of codec configurations, each with a string 'id'",
"invalid_type",
if filters is not None:
if not _is_array(filters):
problems.append(
ValidationProblem(
("filters",),
"expected null or an array of codec configurations",
"invalid_type",
)
)
)
elif _is_array(filters):
# "A list of JSON objects providing codec configurations, or
# null" (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L76-L79): an empty list is a list.
for index, item in enumerate(filters):
problems.extend(validate_json(item, ("filters", index)))
else:
# "A list of JSON objects providing codec configurations, or
# null" (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L76-L79): an empty list is a list.
for index, item in enumerate(filters):
problems.extend(resolve_codec_v2(item, loc=("filters", index))[1])
if "dimension_separator" in doc and doc["dimension_separator"] not in (".", "/"):
problems.append(
outside_of(("dimension_separator",), doc["dimension_separator"], (".", "/"))
)
if "fill_value" in doc:
problems.extend(validate_json(doc["fill_value"], ("fill_value",)))
# JSON, judged by the dtype the scope read, when there is one: a
# dtype nothing in scope claims leaves it unjudged.
fill_value, found = refine_json(doc["fill_value"], ("fill_value",))
problems.extend(found)
if len(found) == 0 and dtype is not None:
problems.extend(fill_value_problems(dtype, fill_value, ("fill_value",)))
if "attributes" in doc:
problems.extend(validate_attributes(doc["attributes"]))
return with_input(problems, doc)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
"""
Zarr v2 codec configuration shape.

In v2, compressors and filters are numcodecs configuration dicts: a required
`id` field naming the codec, plus arbitrary codec-specific extra fields.
"""
"""The JSON shape of a v2 codec, in a module of its own so the array document and the codec definitions can both import it."""

from typing_extensions import TypedDict

Expand All @@ -24,6 +19,4 @@ class ZarrV2CodecMetadata(TypedDict, extra_items=JSONValue):
id: str


__all__ = [
"ZarrV2CodecMetadata",
]
__all__ = ["ZarrV2CodecMetadata"]
Loading
Loading