|
| 1 | +"""One document in, one canonical document or one report of why not. |
| 2 | +
|
| 3 | +`canonicalize_array_metadata_v3` takes a *syntactically* valid document — |
| 4 | +one the model layer has already accepted, so every member is present and |
| 5 | +typed as its TypedDict declares — and answers with `Canonical[T] | Invalid`: either the same document in |
| 6 | +canonical form or every reason it is not semantically valid. Testing the |
| 7 | +literal `valid` field narrows to one or the other. |
| 8 | +
|
| 9 | +Canonical means the simplest spelling with the same meaning, decided per |
| 10 | +metadata variety: |
| 11 | +
|
| 12 | +- an entity whose configuration carries nothing collapses to its bare |
| 13 | + name, and a `must_understand` of `true` (the default) is dropped while |
| 14 | + an explicit `false` is kept, because that one says something. This part |
| 15 | + the model layer already performs, so it is delegated rather than |
| 16 | + reimplemented. |
| 17 | +- `blosc` drops a `typesize` that `shuffle: "noshuffle"` renders ignored. |
| 18 | +- a rectilinear dimension's chunk sizes run-length encode, because that |
| 19 | + is the spelling that does not grow with the number of chunks. |
| 20 | +- `dimension_names` of nothing but nulls says what omitting the field |
| 21 | + says. |
| 22 | +
|
| 23 | +Two properties are worth holding on to, and |
| 24 | +`tests/rules/test_canonical.py` asserts both: canonicalizing twice |
| 25 | +changes nothing further, and canonicalizing never changes a verdict. |
| 26 | +""" |
| 27 | + |
| 28 | +from __future__ import annotations |
| 29 | + |
| 30 | +from collections.abc import Mapping |
| 31 | +from dataclasses import dataclass |
| 32 | +from typing import TYPE_CHECKING, Generic, Literal, TypeVar, cast |
| 33 | + |
| 34 | +from zarr_metadata.model._array import ZarrV3ArrayMetadata |
| 35 | +from zarr_metadata.rules._documents import validate_array_metadata_v3 |
| 36 | +from zarr_metadata.v3._shape import entity_name |
| 37 | +from zarr_metadata.v3.chunk_grid.rectilinear import ( |
| 38 | + RECTILINEAR_CHUNK_GRID_NAME, |
| 39 | + canonical_chunk_shapes, |
| 40 | +) |
| 41 | +from zarr_metadata.v3.codec.blosc import BLOSC_CODEC_NAME |
| 42 | +from zarr_metadata.v3.codec.blosc import canonical_configuration as canonical_blosc |
| 43 | + |
| 44 | +if TYPE_CHECKING: |
| 45 | + from zarr_metadata.model._validation import ValidationProblem |
| 46 | + from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON |
| 47 | + from zarr_metadata.v3.chunk_grid.rectilinear import RectilinearDimSpec |
| 48 | + |
| 49 | +DocumentT = TypeVar("DocumentT") |
| 50 | + |
| 51 | + |
| 52 | +@dataclass(frozen=True, slots=True) |
| 53 | +class Canonical(Generic[DocumentT]): |
| 54 | + """A semantically valid document, in its simplest equivalent spelling.""" |
| 55 | + |
| 56 | + document: DocumentT |
| 57 | + valid: Literal[True] = True |
| 58 | + |
| 59 | + |
| 60 | +@dataclass(frozen=True, slots=True) |
| 61 | +class Invalid: |
| 62 | + """Every reason a document is not semantically valid; never empty.""" |
| 63 | + |
| 64 | + problems: tuple[ValidationProblem, ...] |
| 65 | + valid: Literal[False] = False |
| 66 | + |
| 67 | + def __post_init__(self) -> None: |
| 68 | + if len(self.problems) == 0: |
| 69 | + msg = "Invalid requires at least one validation problem" |
| 70 | + raise ValueError(msg) |
| 71 | + |
| 72 | + |
| 73 | +def _canonical_entity(value: object) -> object: |
| 74 | + """One entity's configuration in its simplest equivalent form. |
| 75 | +
|
| 76 | + Only varieties with something to say appear here; everything else is |
| 77 | + handed to the generic collapse unchanged. |
| 78 | + """ |
| 79 | + original: object = value |
| 80 | + name = entity_name(value) |
| 81 | + if name is None or not isinstance(value, Mapping): |
| 82 | + return original |
| 83 | + entry: Mapping[str, object] = cast("Mapping[str, object]", value) |
| 84 | + configuration = entry.get("configuration") |
| 85 | + if not isinstance(configuration, Mapping): |
| 86 | + return original |
| 87 | + members: Mapping[str, object] = cast("Mapping[str, object]", configuration) |
| 88 | + if name == BLOSC_CODEC_NAME: |
| 89 | + members = canonical_blosc(members) |
| 90 | + elif name == RECTILINEAR_CHUNK_GRID_NAME: |
| 91 | + shapes = members.get("chunk_shapes") |
| 92 | + if isinstance(shapes, tuple): |
| 93 | + specs = cast("tuple[RectilinearDimSpec, ...]", shapes) |
| 94 | + members = {**members, "chunk_shapes": canonical_chunk_shapes(specs)} |
| 95 | + if members is configuration: |
| 96 | + return original |
| 97 | + return {**entry, "configuration": members} |
| 98 | + |
| 99 | + |
| 100 | +def _canonical_document(document: Mapping[str, object]) -> dict[str, object]: |
| 101 | + """Per-variety canonicalization, before the generic collapse.""" |
| 102 | + out = dict(document) |
| 103 | + for field in ("chunk_grid", "chunk_key_encoding", "data_type"): |
| 104 | + if field in out: |
| 105 | + out[field] = _canonical_entity(out[field]) |
| 106 | + codecs = out.get("codecs") |
| 107 | + if isinstance(codecs, tuple): |
| 108 | + entries = cast("tuple[object, ...]", codecs) |
| 109 | + out["codecs"] = tuple(_canonical_entity(codec) for codec in entries) |
| 110 | + names = out.get("dimension_names") |
| 111 | + if isinstance(names, tuple) and all( |
| 112 | + entry is None for entry in cast("tuple[object, ...]", names) |
| 113 | + ): |
| 114 | + # Every dimension unnamed says what saying nothing says. |
| 115 | + del out["dimension_names"] |
| 116 | + return out |
| 117 | + |
| 118 | + |
| 119 | +def canonicalize_array_metadata_v3( |
| 120 | + document: ZarrV3ArrayMetadataJSON, |
| 121 | +) -> Canonical[ZarrV3ArrayMetadataJSON] | Invalid: |
| 122 | + """`document` in canonical form, or every reason it is not valid. |
| 123 | +
|
| 124 | + Expects a document the model layer has already accepted. Passing one |
| 125 | + it has not is not an error — the composition problems are reported the |
| 126 | + same way — but the structural problems come back too, and the result |
| 127 | + is `Invalid` rather than a canonical document. |
| 128 | + """ |
| 129 | + problems = validate_array_metadata_v3(document) |
| 130 | + if len(problems) != 0: |
| 131 | + return Invalid(problems) |
| 132 | + canonical = _canonical_document(document) |
| 133 | + # The generic collapse — shorthand names, defaulted `must_understand` — |
| 134 | + # is what the model layer's round trip already performs. |
| 135 | + return Canonical(ZarrV3ArrayMetadata.from_json(canonical).to_json()) |
| 136 | + |
| 137 | + |
| 138 | +__all__ = [ |
| 139 | + "Canonical", |
| 140 | + "Invalid", |
| 141 | + "canonicalize_array_metadata_v3", |
| 142 | +] |
0 commit comments