diff --git a/packages/zarr-metadata/changes/498.bugfix.md b/packages/zarr-metadata/changes/498.bugfix.md new file mode 100644 index 0000000000..b84a1bf0c8 --- /dev/null +++ b/packages/zarr-metadata/changes/498.bugfix.md @@ -0,0 +1 @@ +Array models that describe the same array are now equal in three more cases. A v2 fill value is compared as the value NumPy stores for the dtype: for ` _TimeConfiguration: + """Return the configuration of a numpy time type with the unit `μs` written as `us`, as NumPy writes it. + + NumPy reads both as microseconds: `np.dtype(" NumpyTimeTicks | Literal["NaT"]: @@ -76,6 +101,39 @@ def base64_bytes(value: str) -> Base64Bytes: return Base64Bytes(value) +def base64_problems(value: str) -> Iterator[ValidationProblem]: + """Check that a fill value written as a string is standard-alphabet base64.""" + try: + base64_bytes(value) + except ValueError: + yield ValidationProblem( + (), f"expected standard-alphabet base64, got {shown(value)}", "invalid_value" + ) + + +def base64_decoded(value: str) -> bytes | None: + """The bytes that `value` encodes in standard-alphabet base64; None when it is not such base64.""" + try: + return base64.b64decode(base64_bytes(value)) + except ValueError: + return None + + +def base64_spelling(data: bytes) -> str: + """`data` in the single spelling of a base64 fill value, standard-alphabet base64: `"QR=="` decodes to the byte that `"QQ=="` spells.""" + return base64.b64encode(data).decode("ascii") + + +def null_padded_bytes_spelling(value: str) -> str: + """Return the bytes that the base64 `value` holds, without their trailing null bytes, in base64 again: one spelling for each value of NumPy's `S`. + + NumPy pads a value of `S` with null bytes to the type's size, and + reads it back without them, so `"QQ=="` and `"QQAA"` are the same + value. `"QR=="` decodes to the same byte as `"QQ=="`. + """ + return base64_spelling(base64.b64decode(value).rstrip(b"\x00")) + + __all__ = [ "NOT_A_TIME_TICKS", "NUMPY_TIME_MAX_SCALE_FACTOR", @@ -84,5 +142,10 @@ def base64_bytes(value: str) -> Base64Bytes: "NumpyTimeScaleFactor", "NumpyTimeTicks", "base64_bytes", + "base64_decoded", + "base64_problems", + "base64_spelling", + "null_padded_bytes_spelling", + "numpy_time_canonical", "numpy_time_fill_value_canonical", ] diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index 2015d53645..1a63c50865 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -41,7 +41,7 @@ import dataclasses import functools from collections.abc import Callable, Iterable, Iterator, Mapping -from dataclasses import dataclass +from dataclasses import dataclass, field from types import MappingProxyType from typing import ( TYPE_CHECKING, @@ -175,6 +175,79 @@ def __hash__(self) -> int: return hash(json_text(self.value)) +def _scalar_defaults( + what: str, defaults: Mapping[str, JSONValue] +) -> tuple[tuple[str, JSONValue], ...]: + """`defaults` as pairs, in the order given, after checking that each default is a JSON scalar. Raises `TypeError` for any other value.""" + for key, value in defaults.items(): + if not (value is None or type(value) in (str, int, float, bool)): + msg = f"{what} takes a string, a number, a boolean or null for {key!r}, got {value!r}" + raise TypeError(msg) + return tuple(defaults.items()) + + +@dataclass(frozen=True, slots=True) +class _Defaults: + """What an absent member of a configuration means, by key. It is a value and not a closure, as `ConstantFillValue` is. Two of the same class compare equal, and hash equal, when their defaults are written the same way and in the same order, so `0` and `False` are two defaults. Two equal values therefore give the same result for a configuration, down to the order of its members.""" + + defaults: tuple[tuple[str, JSONValue], ...] = field(compare=False) + texts: tuple[tuple[str, str], ...] = field(init=False) + """Each key with its default as JSON text, in the order of `defaults`. It is derived from `defaults` when the value is built, so it always agrees with them, and comparing, hashing or calling the value does not encode a default again.""" + + def __post_init__(self) -> None: + """Write each default as JSON text.""" + texts = tuple((key, json_text(value)) for key, value in self.defaults) + object.__setattr__(self, "texts", texts) + + +class _WithoutDefaults(_Defaults): + __slots__ = () + + def __call__(self, configuration: T) -> T: + """Return `configuration` without each member that is written with its default.""" + written = cast("Mapping[str, JSONValue]", configuration) + redundant = [ + key for key, text in self.texts if key in written and json_text(written[key]) == text + ] + if len(redundant) == 0: + return configuration + return cast("T", {key: value for key, value in written.items() if key not in redundant}) + + +class _WithDefaults(_Defaults): + __slots__ = () + + def __call__(self, configuration: T) -> T: + """Return `configuration` with each absent member written with its default.""" + return cast("T", {**dict(self.defaults), **cast("Mapping[str, JSONValue]", configuration)}) + + +def without_defaults(**defaults: JSONValue) -> Callable[[T], T]: + """Return a `canonical` that removes each member written with the value its absence means. + + Each keyword names a member of the configuration and gives the value + that an absent member means. A configuration that writes that value + and one that leaves the member out describe the same thing, so the + canonical form leaves it out: `without_defaults(checksum=False)` reads + `{"level": 3, "checksum": False}` as `{"level": 3}`. A value is + compared as JSON, so `0` is not `False`. A default is a string, a + number, a boolean or null. + """ + return _WithoutDefaults(_scalar_defaults("without_defaults", defaults)) + + +def with_defaults(**defaults: JSONValue) -> Callable[[T], T]: + """Return a `canonical` that writes each absent member with the value its absence means. + + This is `without_defaults` the other way round, for a format whose + writers write every member: `with_defaults(level=1)` reads `{}` as + `{"level": 1}`. The members that have a default come first, in the + order the defaults are given, and then every other member as written. + A default is a string, a number, a boolean or null. + """ + return _WithDefaults(_scalar_defaults("with_defaults", defaults)) + + _DECLARATION_KINDS: Final[dict[TypeAliasType, type[Definition[Any]]]] = {} """Maps each declaration alias to the kind that a member annotated with it is read as. Each kind adds its aliases when its class is built.""" @@ -2238,6 +2311,8 @@ def _replaced(value: JSONValue, path: Loc, new: JSONValue) -> JSONValue: "spelled_canonically", "typed_document", "unchanged", + "with_defaults", "with_problems", + "without_defaults", "written_json", ] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/_types/data_type.py b/packages/zarr-metadata/src/zarr_metadata/v2/_types/data_type.py index 7e779ca4ec..53c4553fd4 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/_types/data_type.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/_types/data_type.py @@ -49,7 +49,7 @@ class ZarrV2ScalarConfiguration(TypedDict, closed=True): # fixed_width ZarrV2Base64FillValue = str | None -"""A fill value that the v2 spec encodes as base64, for a fixed-length byte string, void, or a structured type (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L191-L193), or null.""" +"""A fill value that the v2 spec encodes as base64, for a fixed-length byte string, void, or a structured type (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L192-L194), or null.""" # object diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/codec/compression.py b/packages/zarr-metadata/src/zarr_metadata/v2/codec/compression.py index 3e3ee16295..48a2870ba0 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/codec/compression.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/codec/compression.py @@ -3,13 +3,16 @@ Each parameter that numcodecs gives a default is optional. numcodecs writes the full object with `get_config()`. The canonical form of each codec fills in those defaults, so a configuration that leaves out a -parameter and one that writes its default are one codec. +parameter and one that writes its default are one codec. The defaults +of each codec but `blosc` are the keywords of its `with_defaults`, as +numcodecs writes them. `blosc` has a canonical form of its own. """ from __future__ import annotations from typing import Final +from zarr_metadata.definition._definition import with_defaults from zarr_metadata.v2._definition import ZarrV2CodecDefinition from zarr_metadata.v2._types.codec import ( ZarrV2BloscCName, @@ -24,26 +27,6 @@ ) -def _zlib_canonical(configuration: ZarrV2ZlibParameters) -> ZarrV2ZlibParameters: - """Fill in the default `level`, 1, as numcodecs writes it.""" - return {"level": 1, **configuration} - - -def _gzip_canonical(configuration: ZarrV2GzipParameters) -> ZarrV2GzipParameters: - """Fill in the default `level`, 1, as numcodecs writes it.""" - return {"level": 1, **configuration} - - -def _bz2_canonical(configuration: ZarrV2Bz2Parameters) -> ZarrV2Bz2Parameters: - """Fill in the default `level`, 1, as numcodecs writes it.""" - return {"level": 1, **configuration} - - -def _lzma_canonical(configuration: ZarrV2LzmaParameters) -> ZarrV2LzmaParameters: - """Fill in the defaults, as numcodecs writes them: `format` 1 (`lzma.FORMAT_XZ`), `check` -1 (the format's own check), and null `preset` and `filters`.""" - return {"format": 1, "check": -1, "preset": None, "filters": None, **configuration} - - def _blosc_canonical(configuration: ZarrV2BloscParameters) -> ZarrV2BloscParameters: """Fill in the defaults, as numcodecs writes them, and write a `shuffle` of `true` or `false` as 1 or 0, which numcodecs reads it as. @@ -66,42 +49,36 @@ def _blosc_canonical(configuration: ZarrV2BloscParameters) -> ZarrV2BloscParamet return {**filled, "typesize": typesize} -def _zstd_canonical(configuration: ZarrV2ZstdParameters) -> ZarrV2ZstdParameters: - """Fill in the defaults, `level` 0 and `checksum` false, as numcodecs writes them.""" - return {"level": 0, "checksum": False, **configuration} - - -def _lz4_canonical(configuration: ZarrV2Lz4Parameters) -> ZarrV2Lz4Parameters: - """Fill in the default `acceleration`, 1, as numcodecs writes it.""" - return {"acceleration": 1, **configuration} - - ZLIB_CODEC_V2: Final = ZarrV2CodecDefinition( - name="zlib", configuration=ZarrV2ZlibParameters, canonical=_zlib_canonical + name="zlib", configuration=ZarrV2ZlibParameters, canonical=with_defaults(level=1) ) """`numcodecs.Zlib`.""" GZIP_CODEC_V2: Final = ZarrV2CodecDefinition( - name="gzip", configuration=ZarrV2GzipParameters, canonical=_gzip_canonical + name="gzip", configuration=ZarrV2GzipParameters, canonical=with_defaults(level=1) ) """`numcodecs.GZip`.""" BZ2_CODEC_V2: Final = ZarrV2CodecDefinition( - name="bz2", configuration=ZarrV2Bz2Parameters, canonical=_bz2_canonical + name="bz2", configuration=ZarrV2Bz2Parameters, canonical=with_defaults(level=1) ) """`numcodecs.BZ2`.""" LZMA_CODEC_V2: Final = ZarrV2CodecDefinition( - name="lzma", configuration=ZarrV2LzmaParameters, canonical=_lzma_canonical + name="lzma", + configuration=ZarrV2LzmaParameters, + canonical=with_defaults(format=1, check=-1, preset=None, filters=None), ) -"""`numcodecs.LZMA`.""" +"""`numcodecs.LZMA`. Its defaults are `format` 1 (`lzma.FORMAT_XZ`), `check` -1 (the format's own check), and null `preset` and `filters`.""" BLOSC_CODEC_V2: Final = ZarrV2CodecDefinition( name="blosc", configuration=ZarrV2BloscParameters, canonical=_blosc_canonical ) """`numcodecs.Blosc`.""" ZSTD_CODEC_V2: Final = ZarrV2CodecDefinition( - name="zstd", configuration=ZarrV2ZstdParameters, canonical=_zstd_canonical + name="zstd", + configuration=ZarrV2ZstdParameters, + canonical=with_defaults(level=0, checksum=False), ) """`numcodecs.Zstd`.""" LZ4_CODEC_V2: Final = ZarrV2CodecDefinition( - name="lz4", configuration=ZarrV2Lz4Parameters, canonical=_lz4_canonical + name="lz4", configuration=ZarrV2Lz4Parameters, canonical=with_defaults(acceleration=1) ) """`numcodecs.LZ4`.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/codec/filters.py b/packages/zarr-metadata/src/zarr_metadata/v2/codec/filters.py index f69b7cbe41..261cc043ca 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/codec/filters.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/codec/filters.py @@ -12,6 +12,7 @@ from typing import Final from zarr_metadata._common import EmptyConfiguration +from zarr_metadata.definition._definition import with_defaults from zarr_metadata.v2._definition import ZarrV2CodecDefinition from zarr_metadata.v2._types.codec import ( ZarrV2AsTypeParameters, @@ -24,11 +25,6 @@ from zarr_metadata.v2.codec._dtype import canonical_typestr, dtype_parameter -def _shuffle_canonical(configuration: ZarrV2ShuffleParameters) -> ZarrV2ShuffleParameters: - """Fill in the default `elementsize`, 4, as numcodecs writes it.""" - return {"elementsize": 4, **configuration} - - def _typestrs(dtype: str, astype: str | None) -> tuple[str, str]: """`dtype` and `astype` as NumPy spells them, with an `astype` that is omitted or null filled in with the `dtype`, as numcodecs writes them.""" canonical = canonical_typestr(dtype) @@ -70,7 +66,7 @@ def _astype_canonical(configuration: ZarrV2AsTypeParameters) -> ZarrV2AsTypePara SHUFFLE_CODEC_V2: Final = ZarrV2CodecDefinition( - name="shuffle", configuration=ZarrV2ShuffleParameters, canonical=_shuffle_canonical + name="shuffle", configuration=ZarrV2ShuffleParameters, canonical=with_defaults(elementsize=4) ) """`numcodecs.Shuffle`.""" DELTA_CODEC_V2: Final = ZarrV2CodecDefinition( diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/_rules.py b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/_rules.py index dde5fbe924..845927a91c 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/_rules.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/_rules.py @@ -2,12 +2,11 @@ from __future__ import annotations -import base64 from dataclasses import dataclass from typing import TYPE_CHECKING, Literal -from zarr_metadata._json import ValidationProblem, shown -from zarr_metadata._numpy import NUMPY_TIME_UNITS, base64_bytes +from zarr_metadata._json import ValidationProblem +from zarr_metadata._numpy import NUMPY_TIME_UNITS, base64_decoded, base64_problems if TYPE_CHECKING: from collections.abc import Iterator @@ -141,16 +140,10 @@ def sized_base64_rules( """Check that a fill value that is not null is standard-alphabet base64 of exactly `size` bytes, or of at most `size` bytes when `exact` is False. Any size passes when `size` is None, which happens only when the item size is unknown.""" if value is None: return - try: - base64_bytes(value) - except ValueError: - yield ValidationProblem( - (), f"expected standard-alphabet base64, got {shown(value)}", "invalid_value" - ) - return - if size is None: + yield from base64_problems(value) + held = base64_decoded(value) + if held is None or size is None: return - held = base64.b64decode(value) if (len(held) != size) if exact else (len(held) > size): bound = "" if exact else "at most " yield ValidationProblem( diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/fixed_width.py b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/fixed_width.py index 58812d4857..5a4d5ae2ba 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/fixed_width.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/fixed_width.py @@ -5,6 +5,7 @@ import base64 from typing import TYPE_CHECKING, Final +from zarr_metadata._numpy import base64_spelling, null_padded_bytes_spelling from zarr_metadata.definition._definition import ConstantFillValue from zarr_metadata.v2._definition import CODE_POINT_BYTES, ZarrV2DataTypeDefinition from zarr_metadata.v2._types.data_type import ZarrV2Base64FillValue, ZarrV2ScalarConfiguration @@ -33,7 +34,47 @@ def _bytes_fill_value_rules( def _void_fill_value_default(configuration: ZarrV2ScalarConfiguration, nested: Nested) -> str: """Return the item's size in null bytes, in base64.""" - return base64.b64encode(bytes(configuration["itemsize"])).decode("ascii") + return base64_spelling(bytes(configuration["itemsize"])) + + +def _bytes_fill_value_canonical( + configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2Base64FillValue +) -> ZarrV2Base64FillValue: + """Return the bytes without their trailing null bytes, in base64 again. NumPy pads a value of `S` with null bytes and reads it back without them, so `"QQ=="` and `"QQAA"` are one value. zarr-python 2 writes this spelling.""" + return None if value is None else null_padded_bytes_spelling(value) + + +def _void_fill_value_canonical( + configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2Base64FillValue +) -> ZarrV2Base64FillValue: + """Return the bytes in base64 again, so `"QR=="` and `"QQ=="`, which decode to the same byte, are one value. zarr-python 2 writes this spelling.""" + return None if value is None else base64_spelling(base64.b64decode(value)) + + +def _str_fill_value_canonical( + configuration: ZarrV2ScalarConfiguration, nested: Nested, value: str | None +) -> str | None: + """Return the string as NumPy holds it in an item of `U`: its first `n` code points, without trailing `U+0000` code points. + + The v2 spec says nothing about a string fill value, and gives the + dtype as a NumPy typestr + (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L130-L132). + NumPy pads a shorter string with `U+0000`, so `"a"` and `"a\\u0000"` + are one value. NumPy cuts a longer string to `n` code points, and + zarr-python 2 reads such a fill value without complaint, so for + ``: byte strings of `n` bytes. The fill value is base64 of at most `n` bytes.""" @@ -53,8 +95,9 @@ def _void_fill_value_default(configuration: ZarrV2ScalarConfiguration, nested: N rules=sized(None, frozenset(), unit=CODE_POINT_BYTES), fill_value=str | None, fill_value_default=ConstantFillValue(""), + fill_value_canonical=_str_fill_value_canonical, ) -"""``: strings of `n` code points. Each code point takes four bytes, in the written byte order. The fill value is a string.""" +"""``: strings of `n` code points. Each code point takes four bytes, in the written byte order. The fill value is a string. An item filled with it holds its first `n` code points. Where `n` is 0, NumPy allocates items of one code point, which hold its first code point.""" VOID_DATA_TYPE_V2: Final = ZarrV2DataTypeDefinition( name="void", @@ -64,6 +107,7 @@ def _void_fill_value_default(configuration: ZarrV2ScalarConfiguration, nested: N fill_value=ZarrV2Base64FillValue, fill_value_default=_void_fill_value_default, fill_value_rules=_void_fill_value_rules, + fill_value_canonical=_void_fill_value_canonical, ) """`|V`: `n` untyped bytes. The fill value is base64 of exactly `n` bytes.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py index dd00b474fb..a4ba27d622 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py @@ -115,31 +115,47 @@ def _named(value: ZarrV2FloatFillValue) -> ZarrV2FloatSpecial | None: def _float_canonical( configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2FloatFillValue ) -> ZarrV2FloatFillValue: - """Return the canonical spelling of a float fill value. An integer written for a float becomes the float, so `0` and `0.0` are one value. A number past the largest float of the dtype's width becomes the infinity of its sign. This matches how the v3 float types read a number and how NumPy stores it.""" + """Return the canonical spelling of a float fill value: the number as a float of the dtype's width holds it. + + The v2 spec gives the dtype as a NumPy typestr + (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L130-L132), + and NumPy casts a float64 to the dtype. So `0` and `0.0` are one + value, and for ` ZarrV2ComplexComponent: - """Return `value` as a float of `itemsize` bytes holds it: the value as a float, or the infinity of its sign if it is past the largest such float. If no float has that width, the value is kept.""" + """Return `value` as a float of `itemsize` bytes holds it: the nearest value of that float, or the infinity of its sign if it rounds past the largest such float. If no float has that width, the value is kept as a float64.""" if isinstance(value, bool) or not isinstance(value, (int, float)): return value try: held = float(value) narrowed = held if itemsize in _FLOAT_CODES: - # `struct` raises for a float16 past the largest value, and packs - # a float32 past the largest value as an infinity. + # For a value that rounds past the largest float of the size, + # `struct` raises for a float16. For a float32 it raises on some + # Python versions and packs an infinity on others. code = _FLOAT_CODES[itemsize] (narrowed,) = struct.unpack(code, struct.pack(code, held)) except OverflowError: return "-Infinity" if value < 0 else "Infinity" if math.isinf(narrowed): return "-Infinity" if value < 0 else "Infinity" - return held + return narrowed _FLOAT_CODES: Final[Mapping[int, str]] = {2: "e", 4: "f", 8: "d"} -"""The `struct` code for the float of each size in bytes. Packing with it detects a value past the largest float.""" +"""The `struct` code for the float of each size in bytes. Packing with it rounds a number to the float of that size, and detects a value past the largest float.""" def _complex_canonical( diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/struct.py b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/struct.py index 9886893b3e..adae72c797 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/struct.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/struct.py @@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any, Final, cast from zarr_metadata._json import ValidationProblem +from zarr_metadata._numpy import base64_spelling from zarr_metadata._sentinel import UNSET from zarr_metadata.definition._definition import AcceptedDeclaration from zarr_metadata.v2._definition import STRUCT_NAME, ZarrV2DataTypeDefinition, item_bytes @@ -50,7 +51,14 @@ def _fill_value_rules( def _fill_value_default(configuration: ZarrV2StructConfiguration, nested: Nested) -> str | UNSET: """Return one record of null bytes, in base64. `UNSET` when the size of a field is not known.""" size = _record_size(configuration, nested) - return UNSET if size is None else base64.b64encode(bytes(size)).decode("ascii") + return UNSET if size is None else base64_spelling(bytes(size)) + + +def _fill_value_canonical( + configuration: ZarrV2StructConfiguration, nested: Nested, value: ZarrV2Base64FillValue +) -> ZarrV2Base64FillValue: + """Return the record's bytes in base64 again, so `"QR=="` and `"QQ=="`, which decode to the same byte, are one value. zarr-python 2 writes this spelling.""" + return None if value is None else base64_spelling(base64.b64decode(value)) def _record_size(configuration: ZarrV2StructConfiguration, nested: Nested) -> int | None: @@ -84,7 +92,8 @@ def _item_size(declaration: AcceptedDeclaration[Any]) -> int | None: fill_value=ZarrV2Base64FillValue, fill_value_default=_fill_value_default, fill_value_rules=_fill_value_rules, + fill_value_canonical=_fill_value_canonical, ) -"""A structured type: an array of field records. The fill value is base64 of one record (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L191-L193).""" +"""A structured type: an array of field records. The fill value is base64 of one record (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L192-L194).""" __all__ = ["STRUCT_DATA_TYPE_V2", "ZarrV2StructConfiguration", "ZarrV2StructRecord"] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/time.py b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/time.py index 6473f59392..3fdde8014d 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/time.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/time.py @@ -4,9 +4,7 @@ from typing import TYPE_CHECKING, Final -from zarr_metadata._numpy import ( - numpy_time_fill_value_canonical, -) +from zarr_metadata._numpy import numpy_time_canonical, numpy_time_fill_value_canonical from zarr_metadata.definition._definition import ConstantFillValue from zarr_metadata.v2._definition import ZarrV2DataTypeDefinition from zarr_metadata.v2._types.data_type import ( @@ -19,17 +17,10 @@ from zarr_metadata.definition._definition import Nested -def _canonical(configuration: ZarrV2TimeConfiguration) -> ZarrV2TimeConfiguration: - """Write `μs` as `us`, as NumPy writes it.""" - if configuration.get("unit") == "μs": - return {**configuration, "unit": "us"} - return configuration - - def _fill_value_canonical( configuration: ZarrV2TimeConfiguration, nested: Nested, value: ZarrV2TimeFillValue ) -> ZarrV2TimeFillValue: - """Return `NaT` for not-a-time however it is written, and any other value as written.""" + """Return `NaT` for not-a-time however it is written, and any other value as written. NumPy stores not-a-time as the smallest int64, and zarr-python 2 reads both `"NaT"` and that count of ticks as not-a-time, so the two are one value.""" if value is None: return None return numpy_time_fill_value_canonical(configuration, nested, value) @@ -39,23 +30,23 @@ def _fill_value_canonical( name="datetime64", configuration=ZarrV2TimeConfiguration, rules=time_rules("M"), - canonical=_canonical, + canonical=numpy_time_canonical, fill_value=ZarrV2TimeFillValue, fill_value_default=ConstantFillValue("NaT"), fill_value_canonical=_fill_value_canonical, ) -"""` DefaultChunkKeyEncodingConfiguration: - """Remove a `separator` of `/`, because an absent `separator` means the same thing. - - "If not specified, `separator` defaults to `/`" - (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/chunk-key-encodings/default/index.rst#L27-L29), - so the two spellings describe the same encoding. - """ - if configuration.get("separator") != DEFAULT_CHUNK_KEY_ENCODING_DEFAULT_SEPARATOR: - return configuration - return {} - - DEFAULT_CHUNK_KEY_ENCODING: Final = ChunkKeyEncodingDefinition( name=DEFAULT_CHUNK_KEY_ENCODING_NAME, configuration=DefaultChunkKeyEncodingConfiguration, - canonical=_canonical, + canonical=without_defaults(separator=DEFAULT_CHUNK_KEY_ENCODING_DEFAULT_SEPARATOR), ) -"""The `default` chunk key encoding. The type of `separator` already restricts its values, so the encoding has no rules of its own.""" +"""The `default` chunk key encoding. The type of `separator` already restricts its values, so the encoding has no rules of its own. + +A `separator` of `/` and an absent `separator` describe the same encoding: +"If not specified, `separator` defaults to `/`" +(https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/chunk-key-encodings/default/index.rst#L27-L29). +""" __all__ = [ diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py index 752e553053..4400ad22a6 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py @@ -15,6 +15,7 @@ from typing import Final +from zarr_metadata.definition._definition import without_defaults from zarr_metadata.v3._definition import ChunkKeyEncodingDefinition from zarr_metadata.v3._types.chunk_key_encoding import ( V2_CHUNK_KEY_ENCODING_DEFAULT_SEPARATOR, @@ -27,25 +28,17 @@ V2ChunkKeyEncodingSeparator, ) - -def _canonical(configuration: V2ChunkKeyEncodingConfiguration) -> V2ChunkKeyEncodingConfiguration: - """Remove a `separator` of `.`, because an absent `separator` means the same thing. - - "If not specified, `separator` defaults to `.`" - (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/chunk-key-encodings/v2/index.rst#L27-L29), - so the two spellings describe the same encoding. - """ - if configuration.get("separator") != V2_CHUNK_KEY_ENCODING_DEFAULT_SEPARATOR: - return configuration - return {} - - V2_CHUNK_KEY_ENCODING: Final = ChunkKeyEncodingDefinition( name=V2_CHUNK_KEY_ENCODING_NAME, configuration=V2ChunkKeyEncodingConfiguration, - canonical=_canonical, + canonical=without_defaults(separator=V2_CHUNK_KEY_ENCODING_DEFAULT_SEPARATOR), ) -"""The `v2` chunk key encoding. The type of `separator` already restricts its values, so the encoding has no rules of its own.""" +"""The `v2` chunk key encoding. The type of `separator` already restricts its values, so the encoding has no rules of its own. + +A `separator` of `.` and an absent `separator` describe the same +encoding: "If not specified, `separator` defaults to `.`" +(https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/chunk-key-encodings/v2/index.rst#L27-L29). +""" __all__ = [ diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/cast_value.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/cast_value.py index 377c92dfc1..5d6303c892 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/codec/cast_value.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/cast_value.py @@ -13,6 +13,7 @@ AcceptedDeclaration, Nested, fill_value_problems, + without_defaults, ) from zarr_metadata.v3._definition import ( ArrayArrayCodecDefinition, @@ -137,6 +138,7 @@ def _transition(configuration: CastValueCodecConfiguration, nested: Nested, chun CAST_VALUE_CODEC: Final = ArrayArrayCodecDefinition( name=CAST_VALUE_CODEC_NAME, configuration=CastValueCodecConfiguration, + canonical=without_defaults(rounding="nearest-even"), size="static", rules=_rules, chunk_rules=_chunk_rules, @@ -146,6 +148,12 @@ def _transition(configuration: CastValueCodecConfiguration, nested: Nested, chun The target data type is a nested declaration. It is read in the same scope as the codec, and it becomes the data type of the output chunk. + +A `rounding` of `nearest-even` and an absent `rounding` describe the same +codec: "If this field is not present, implementations MUST use +`"nearest-even"`" +(https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/codecs/cast_value/README.md?plain=1#L73). +An absent `out_of_range` has a meaning of its own, so it has no default. """ diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py index 5a4d0f5983..6148172090 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py @@ -11,6 +11,7 @@ from zarr_metadata.definition._definition import ( AcceptedDeclaration, Nested, + without_defaults, ) from zarr_metadata.v3._definition import ( ArrayBytesCodecDefinition, @@ -118,26 +119,10 @@ def _per_shard(chunk_shape: tuple[int, ...], lengths: Lengths | None) -> Lengths ) -def _canonical( - configuration: ShardingIndexedCodecConfiguration, -) -> ShardingIndexedCodecConfiguration: - """Remove an `index_location` of `end`, because an absent `index_location` means the same thing. - - "If the parameter is not present, the value defaults to `end`" - (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/codecs/sharding-indexed/index.rst#L157-L161), - so the two spellings describe the same codec. - """ - if configuration.get("index_location") != "end": - return configuration - simpler = configuration.copy() - del simpler["index_location"] - return simpler - - SHARDING_INDEXED_CODEC: Final = ArrayBytesCodecDefinition( name=SHARDING_INDEXED_CODEC_NAME, configuration=ShardingIndexedCodecConfiguration, - canonical=_canonical, + canonical=without_defaults(index_location="end"), size="dynamic", chunk_rules=_chunk_rules, pipelines=_pipelines, @@ -148,6 +133,10 @@ def _canonical( same scope as the shard, and each pipeline is read as a pipeline: the inner codecs receive the inner chunks, and the index codecs receive the shard index. + +An `index_location` of `end` and an absent `index_location` describe the +same codec: "If the parameter is not present, the value defaults to `end`" +(https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/codecs/sharding-indexed/index.rst#L157-L161). """ diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py index 837f280921..c9cb6b2674 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py @@ -8,6 +8,7 @@ from typing import Final +from zarr_metadata.definition._definition import without_defaults from zarr_metadata.v3._definition import BytesBytesCodecDefinition from zarr_metadata.v3._types.codec import ( ZSTD_CODEC_NAME, @@ -19,28 +20,18 @@ ZstdCodecObject, ) - -def _canonical(configuration: ZstdCodecConfiguration) -> ZstdCodecConfiguration: - """Remove a `checksum` of `false`, because an absent `checksum` means the same thing. - - The spec says of `checksum` that it "should be omitted if false" - (https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/codecs/zstd/README.md?plain=1#L17-L19), - so the two spellings describe the same codec. - """ - if configuration.get("checksum") is not False: - return configuration - simpler = configuration.copy() - del simpler["checksum"] - return simpler - - ZSTD_CODEC: Final = BytesBytesCodecDefinition( name=ZSTD_CODEC_NAME, configuration=ZstdCodecConfiguration, - canonical=_canonical, + canonical=without_defaults(checksum=False), size="dynamic", ) -"""The `zstd` codec.""" +"""The `zstd` codec. + +A `checksum` of `false` and an absent `checksum` describe the same codec: +the spec says of `checksum` that it "should be omitted if false" +(https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/codecs/zstd/README.md?plain=1#L17-L19). +""" __all__ = [ diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/_byte.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/_byte.py index a8a82370aa..10a8c0cf85 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/_byte.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/_byte.py @@ -4,24 +4,13 @@ `zarr_metadata.v3._types.data_type`. """ -import base64 from collections.abc import Iterator -from zarr_metadata._json import ValidationProblem, shown -from zarr_metadata._numpy import base64_bytes +from zarr_metadata._json import ValidationProblem +from zarr_metadata._numpy import base64_decoded, base64_problems, base64_spelling from zarr_metadata.v3._types.codec import VLEN_BYTES_CODEC_NAME, VlenBytesCodecObject -def base64_problems(value: str) -> Iterator[ValidationProblem]: - """Check that a fill value written as a string is standard-alphabet base64.""" - try: - base64_bytes(value) - except ValueError: - yield ValidationProblem( - (), f"expected standard-alphabet base64, got {shown(value)}", "invalid_value" - ) - - def base64_fill_value_rules( configuration: object, nested: object, value: object ) -> Iterator[ValidationProblem]: @@ -39,19 +28,6 @@ def base64_fill_value_rules( yield from base64_problems(value) -def base64_decoded(value: str) -> bytes | None: - """The bytes that `value` encodes in standard-alphabet base64; None when it is not such base64.""" - try: - return base64.b64decode(base64_bytes(value)) - except ValueError: - return None - - -def base64_spelling(data: bytes) -> str: - """`data` in the single spelling of a base64 fill value, standard-alphabet base64: `"QR=="` decodes to the byte that `"QQ=="` spells.""" - return base64.b64encode(data).decode("ascii") - - def vlen_bytes_codec(*_: object) -> VlenBytesCodecObject: """The array -> bytes codec of a data type whose values are byte strings that vary in length: `vlen-bytes`, as zarr-python chooses it (https://github.com/zarr-developers/zarr-python/blob/0981311c07f0a8dc8650b74e33bd385ccb411f26/src/zarr/core/array.py#L5114-L5139).""" return {"name": VLEN_BYTES_CODEC_NAME} diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/null_terminated_bytes.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/null_terminated_bytes.py index 7217f5eb1d..38a5711237 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/null_terminated_bytes.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/null_terminated_bytes.py @@ -8,11 +8,11 @@ `ZARR_PYTHON_CONTEXT` scope, not in `CORE_AND_EXTENSIONS_CONTEXT`. """ -import base64 from collections.abc import Iterator from typing import Final from zarr_metadata._json import ValidationProblem +from zarr_metadata._numpy import base64_decoded, base64_problems, null_padded_bytes_spelling from zarr_metadata.definition._definition import ConstantFillValue, Nested from zarr_metadata.v3._definition import DataTypeDefinition, single_byte from zarr_metadata.v3._types.data_type import ( @@ -22,7 +22,6 @@ NullTerminatedBytesDataTypeName, NullTerminatedBytesFillValue, ) -from zarr_metadata.v3.data_type._byte import base64_decoded, base64_problems, base64_spelling def _fill_value_rules( @@ -58,7 +57,7 @@ def _fill_value_canonical( A value is padded with null bytes to `length_bytes`, so `"QQ=="` and `"QQAA"` are the same value, as are `"QR=="` and `"QQ=="`. """ - return base64_spelling(base64.b64decode(value).rstrip(b"\x00")) + return null_padded_bytes_spelling(value) NULL_TERMINATED_BYTES_DATA_TYPE: Final = DataTypeDefinition( diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py index ea33f7463b..8d8a490f6f 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py @@ -6,9 +6,7 @@ from typing import Final -from zarr_metadata._numpy import ( - numpy_time_fill_value_canonical, -) +from zarr_metadata._numpy import numpy_time_canonical, numpy_time_fill_value_canonical from zarr_metadata.definition._definition import ConstantFillValue from zarr_metadata.v3._definition import DataTypeDefinition from zarr_metadata.v3._types.data_type import ( @@ -27,6 +25,7 @@ configuration=NumpyDatetime64Configuration, fill_value=NumpyDatetime64FillValue, fill_value_default=ConstantFillValue("NaT"), + canonical=numpy_time_canonical, fill_value_canonical=numpy_time_fill_value_canonical, storage=numpy_time_storage, number_class="non_numeric", @@ -42,6 +41,11 @@ signed 64-bit integers" (https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/data-types/numpy.datetime64/README.md?plain=1#L120), which those two codecs' specs do not bear out. + +A unit of `μs` and a unit of `us` describe the same type: "as per NumPy, +`"us"` and `"μs"` are equivalent and interchangeable representations of +microseconds" +(https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/data-types/numpy.datetime64/README.md?plain=1#L87-L88). """ diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py index 4aaa3210d4..23a86de688 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py @@ -6,9 +6,7 @@ from typing import Final -from zarr_metadata._numpy import ( - numpy_time_fill_value_canonical, -) +from zarr_metadata._numpy import numpy_time_canonical, numpy_time_fill_value_canonical from zarr_metadata.definition._definition import ConstantFillValue from zarr_metadata.v3._definition import DataTypeDefinition from zarr_metadata.v3._types.data_type import ( @@ -25,6 +23,7 @@ configuration=NumpyTimedelta64Configuration, fill_value=NumpyTimedelta64FillValue, fill_value_default=ConstantFillValue("NaT"), + canonical=numpy_time_canonical, fill_value_canonical=numpy_time_fill_value_canonical, storage=numpy_time_storage, number_class="non_numeric", @@ -34,6 +33,11 @@ Its number class is non-numeric, as that of `numpy.datetime64` is: its values are durations, and neither `cast_value` nor `scale_offset` names it among the data types it supports. + +A unit of `μs` and a unit of `us` describe the same type: "as per NumPy, +`"us"` and `"μs"` are equivalent and interchangeable representations of +microseconds" +(https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/data-types/numpy.timedelta64/README.md?plain=1#L90-L91). """ diff --git a/packages/zarr-metadata/tests/model/test_array.py b/packages/zarr-metadata/tests/model/test_array.py index d08c273782..81262d15cf 100644 --- a/packages/zarr-metadata/tests/model/test_array.py +++ b/packages/zarr-metadata/tests/model/test_array.py @@ -791,8 +791,36 @@ def test_two_models_are_one_array_when_their_fill_values_are_one_value( "default", {"name": "default", "configuration": {"separator": "/"}}, ), + ( + "codecs", + [{"name": "cast_value", "configuration": {"data_type": "uint16"}}, _LITTLE], + [ + { + "name": "cast_value", + "configuration": {"data_type": "uint16", "rounding": "nearest-even"}, + }, + _LITTLE, + ], + ), + ( + "data_type", + {"name": "numpy.datetime64", "configuration": {"unit": "us", "scale_factor": 1}}, + {"name": "numpy.datetime64", "configuration": {"unit": "μs", "scale_factor": 1}}, + ), + ( + "data_type", + {"name": "numpy.timedelta64", "configuration": {"unit": "us", "scale_factor": 10}}, + {"name": "numpy.timedelta64", "configuration": {"unit": "μs", "scale_factor": 10}}, + ), + ], + ids=[ + "blosc-typesize-noshuffle", + "zstd-checksum-false", + "default-separator", + "cast-value-rounding", + "datetime64-microseconds", + "timedelta64-microseconds", ], - ids=["blosc-typesize-noshuffle", "zstd-checksum-false", "default-separator"], ) def test_two_models_are_one_array_when_their_declarations_read_the_same( member: str, left: object, right: object diff --git a/packages/zarr-metadata/tests/model/test_pair_v2.py b/packages/zarr-metadata/tests/model/test_pair_v2.py index bd86fd25b0..e6934811ba 100644 --- a/packages/zarr-metadata/tests/model/test_pair_v2.py +++ b/packages/zarr-metadata/tests/model/test_pair_v2.py @@ -112,6 +112,27 @@ def test_properties_are_what_the_reading_holds() -> None: True, ), ({"filters": [{"id": "crc32"}]}, {"filters": [{"id": "crc32", "location": "start"}]}, True), + ( + {"dtype": "f4"}, False), ({"compressor": {"id": "zstd", "level": 0}}, {"compressor": {"id": "zstd"}}, True), @@ -128,6 +149,15 @@ def test_properties_are_what_the_reading_holds() -> None: "key-order", "numcodecs-default", "numcodecs-default-filter", + "float32-rounding", + "float64-no-rounding", + "bytes-padding", + "void-base64", + "str-padding", + "str-cut", + "str-zero-size", + "str-zero-size-cut", + "struct-base64", "signed-zero", "byte-order", "numcodecs-default-omitted", @@ -140,7 +170,7 @@ def test_properties_are_what_the_reading_holds() -> None: def test_models_are_equal_by_what_their_documents_mean( left: dict[str, Any], right: dict[str, Any], same: bool ) -> None: - """Two models are equal when their documents mean the same in their scopes. A typestr with two spellings, a fill value written as an integer or a float, or a codec parameter written or left to its numcodecs default, gives equal models. No `.zattrs` and an empty one give equal models, since both mean no attributes, as in v3. A different byte order or a codec parameter away from its default gives different models. Equal models have equal hashes, and refine each other: read in one scope, `refines` is that equality.""" + """Two models are equal when their documents mean the same in their scopes. A typestr with two spellings, a fill value written as an integer or a float, two numbers that read as one float of the dtype's width, two base64 spellings of the same bytes, a string or byte string with or without its padding, a string and the part of it that fits the item, or a codec parameter written or left to its numcodecs default, gives equal models. No `.zattrs` and an empty one give equal models, since both mean no attributes, as in v3. A different byte order or a codec parameter away from its default gives different models. Equal models have equal hashes, and refine each other: read in one scope, `refines` is that equality.""" one, other = ZarrV2ArrayMetadata(_document(left)), ZarrV2ArrayMetadata(_document(right)) assert (one == other) is same assert one.refines(other) is same diff --git a/packages/zarr-metadata/tests/v2/test_codecs.py b/packages/zarr-metadata/tests/v2/test_codecs.py index 0db277f03c..9325ce21f6 100644 --- a/packages/zarr-metadata/tests/v2/test_codecs.py +++ b/packages/zarr-metadata/tests/v2/test_codecs.py @@ -207,10 +207,13 @@ def test_every_example_reads_and_is_written_back_as_it_was( def test_the_canonical_form_fills_in_defaults_and_writes_each_value_one_way( declaration: dict[str, Any], canonical: dict[str, Any] ) -> None: - """The canonical form of a codec fills in each parameter that numcodecs gives a default, where the configuration omits it or writes null, as `get_config()` writes it. A blosc `shuffle` of `true` or `false` is 1 or 0, which numcodecs reads it as, and an `astype` left out is the `dtype`. It writes a dtype parameter as NumPy spells it (` st.SearchStrategy[str]: + """Each byte string `data` draws, in any of its base64 spellings.""" + return st.builds(_spelled, data, st.integers(0, 15)) + + +def _spelled(data: bytes, unused: int) -> str: + """`data` in base64, with the bits that its padding leaves unused set to `unused`. `b"A"` is `"QQ=="`, and with other unused bits it is `"QR=="`, which decodes to the same byte.""" + text = base64.b64encode(data).decode("ascii") + padding = text.count("=") + if padding == 0: + return text + at = len(text) - padding - 1 + index = _BASE64_ALPHABET.index(text[at]) | (unused & ((1 << (2 * padding)) - 1)) + return text[:at] + _BASE64_ALPHABET[index] + text[at + 1 :] + + +def _bytes(least: int, most: int) -> st.SearchStrategy[bytes]: + """Byte strings of `least` to `most` bytes, each a null byte or `a`.""" + return st.lists(st.sampled_from([0, 97]), min_size=least, max_size=most).map(bytes) + + +_STRINGS = st.text(st.sampled_from("a\x00"), max_size=4) | st.text( + st.sampled_from("ab\x00\U0001f600"), max_size=5 +) +"""A string fill value. Short strings of `a` and `U+0000` are drawn often, because they are the ones that differ only in padding or past the end of an item.""" + +_TICKS = st.one_of(st.integers(-(2**63), -(2**63) + 1), st.integers(-2, 2), st.just("NaT")) + + +def _twice(values: st.SearchStrategy[JSONValue]) -> st.SearchStrategy[tuple[JSONValue, ...]]: + """Two fill values drawn from `values`, one after the other.""" + return st.tuples(values, values) + + +def _neighbors(width: Literal[16, 32]) -> st.SearchStrategy[tuple[JSONValue, ...]]: + """A number that a float of `width` bits holds exactly, and the next float64 above it. Both read as the same float of that width, except `-0.0`, whose next float64 reads as `0.0`.""" + return st.floats(allow_nan=False, allow_infinity=False, width=width).map(_with_next) + + +def _with_next(number: float) -> tuple[JSONValue, ...]: + return (number, math.nextafter(number, math.inf)) + + +_FAMILIES: list[tuple[JSONValue, st.SearchStrategy[tuple[JSONValue, ...]]]] = [ + *[(dtype, _twice(_FLOAT_COMPONENTS)) for dtype in ("f4")], + ("f4")], + ( + "c8")], + *[(f"|S{size}", _twice(_base64(_bytes(0, size)))) for size in range(4)], + *[(f"|V{size}", _twice(_base64(_bytes(size, size)))) for size in range(4)], + *[(f"{order}U{size}", _twice(_STRINGS)) for order in "<>" for size in range(4)], + *[(dtype, _twice(_TICKS)) for dtype in (" st.SearchStrategy[tuple[JSONValue, JSONValue, JSONValue]]: + """A dtype, and two fill values it takes. The second is null one time in ten.""" + dtype, pairs = family + return st.tuples(st.just(dtype), pairs, st.integers(0, 9)).map(_sometimes_null) + + +def _sometimes_null( + drawn: tuple[JSONValue, tuple[JSONValue, ...], int], +) -> tuple[JSONValue, JSONValue, JSONValue]: + dtype, (one, other), chance = drawn + return (dtype, one, None if chance == 0 else other) + + +def _stored(dtype: JSONValue, value: JSONValue) -> object: + """What NumPy stores in one item of an array of `dtype` for the fill value `value`, written without the package: the bytes of a float, the padded bytes of a byte string, the padded code points of a string, the ticks of a time. Two fill values are one value exactly when this is equal for both. + + zarr-python 2.18.7 with NumPy 1.26.4 stores the same, with two + exceptions. It reads a complex fill value as `real + 1j * imag`, which + loses a negative zero and makes the real part NaN when the imaginary + part is not finite, where this function keeps the two components as + NumPy stores a complex. And it does not read an integer too large for + a float64, which this function reads as an infinity, as the package + does. + """ + if value is None or not isinstance(dtype, str): + return value if value is None else base64.b64decode(str(value)) + code, size = dtype[1], dtype[2:] + if code == "f": + return _float_stored(value, int(size)) + if code == "c": + assert isinstance(value, list) + return tuple(_float_stored(part, int(size) // 2) for part in value) + if code == "S": + return base64.b64decode(str(value)).ljust(int(size), b"\x00") + if code == "V": + return base64.b64decode(str(value)) + if code == "U": + # NumPy makes an array of `U0` an array of `U1`. + held = max(int(size), 1) + return str(value)[:held].ljust(held, "\x00") + if code in "Mm": + return -(2**63) if value == "NaT" else value + return (type(value), value) + + +def _float_stored(value: JSONValue, size: int) -> bytes: + """The bytes of the float of `size` bytes that NumPy casts `value` to. A number that rounds past the largest such float is an infinity. So is an integer too large for a float64, which NumPy refuses and the package reads as an infinity.""" + code = {2: "e", 4: "f", 8: "d"}[size] + named = {"NaN": math.nan, "Infinity": math.inf, "-Infinity": -math.inf} + if isinstance(value, str): + return struct.pack(f">{code}", named[value]) + assert isinstance(value, (int, float)) + try: + return struct.pack(f">{code}", float(value)) + except OverflowError: + return struct.pack(f">{code}", -math.inf if value < 0 else math.inf) + + +@given(st.sampled_from(_FAMILIES).flatmap(_drawn_twice)) +@settings(max_examples=3000, deadline=None) +def test_two_fill_values_have_one_canonical_spelling_when_numpy_stores_them_alike( + drawn: tuple[JSONValue, JSONValue, JSONValue], +) -> None: + """Two fill values of a v2 dtype have the same canonical spelling exactly when NumPy stores the same item for both. The canonical spelling is itself a fill value the dtype takes, so it can be written to a v2 document, and it is its own canonical spelling. This holds for a number that a narrower float rounds, a number past the largest float, a string longer than its item, padded strings and byte strings, and base64 with unused bits set.""" + dtype, one, other = drawn + resolved, problems = resolve(dtype, ZarrV2DataTypeDefinition, CONTEXT) + assert isinstance(resolved, AcceptedDeclaration) + assert problems == () + spellings = [] + for value in (one, other): + assert fill_value_problems(resolved, value) == () + canonical = canonical_fill_value(resolved, value) + assert fill_value_problems(resolved, canonical) == () + assert repr(canonical_fill_value(resolved, canonical)) == repr(canonical) + spellings.append(repr(canonical)) + alike = _stored(dtype, one) == _stored(dtype, other) + written_alike = json.dumps(one) == json.dumps(other) + event( + f"{resolved.name}: " + + ("two values" if not alike else "one spelling" if written_alike else "two spellings") + ) + assert (spellings[0] == spellings[1]) is alike + def _read(value: object) -> tuple[type, list[tuple[Loc, str]]]: resolved, problems = resolve(value, ZarrV2DataTypeDefinition, CONTEXT, ("dtype",)) @@ -191,27 +373,61 @@ def test_error_a_time_typestr_without_a_unit_is_refused_with_an_example_of_its_o ("f4", 0.1, 0.10000000149011612), + (" None: - """Each family accepts the fill values the v2 spec allows for it, and always accepts `null`: booleans; integers in the type's range; numbers or the named non-finite strings for floats and for each complex component; base64 for bytes, void and struct; a string for str; any JSON for object; and ticks or `NaT` for times. The canonical spelling turns an integer written for a float into a float, and turns the ticks value of `NaT` into `"NaT"`.""" + """Each family accepts the fill values the v2 spec allows for it, and always accepts `null`: booleans; integers in the type's range; numbers or the named non-finite strings for floats and for each complex component; base64 for bytes, void and struct; a string for str; any JSON for object; and ticks or `NaT` for times. The canonical spelling is one per value, as NumPy stores the value: a number written for a float is the float of the dtype's width that it reads as, base64 is encoded again, the padding of a byte string or a string is dropped, a string is cut to the item's size, and the ticks value of `NaT` is `"NaT"`.""" resolved, _ = resolve(dtype, ZarrV2DataTypeDefinition, CONTEXT) assert fill_value_problems(resolved, value) == () - assert canonical_fill_value(resolved, value) == canonical + found = canonical_fill_value(resolved, value) + assert (found, type(found)) == (canonical, type(canonical)) @pytest.mark.parametrize( diff --git a/packages/zarr-metadata/tests/v3/test_definitions.py b/packages/zarr-metadata/tests/v3/test_definitions.py index 3dc2f14ba2..18c3722316 100644 --- a/packages/zarr-metadata/tests/v3/test_definitions.py +++ b/packages/zarr-metadata/tests/v3/test_definitions.py @@ -7,10 +7,9 @@ import math import pickle import re -from collections.abc import ( - Mapping, -) +from collections.abc import Callable, Mapping from dataclasses import dataclass, replace +from types import MappingProxyType from typing import TYPE_CHECKING, Annotated, Any, Final, NotRequired, cast import pytest @@ -34,7 +33,7 @@ configuration_of, resolve, ) -from zarr_metadata.definition._definition import resolve_refined +from zarr_metadata.definition._definition import resolve_refined, with_defaults, without_defaults from zarr_metadata.model import ( UNSET, ZarrV3ArrayMetadata, @@ -1884,3 +1883,83 @@ def test_error_resolve_refuses_a_kind_of_the_other_format_whatever_the_declarati """`resolve` with a kind of one format and a scope of the other raises one `TypeError`, before it reads the declaration. So the message is the same for a declaration with a name that a scope could look up and for a value with no name.""" with pytest.raises(TypeError, match=f"^{re.escape(message)}$"): resolve(declaration, kind, context) + + +@pytest.mark.parametrize( + ("canonical", "configuration", "expected"), + [ + (without_defaults(checksum=False), {"level": 3, "checksum": False}, {"level": 3}), + (without_defaults(checksum=False), {"level": 3, "checksum": True}, None), + (without_defaults(checksum=False), {"level": 3}, None), + (without_defaults(checksum=False), {"level": 3, "checksum": 0}, None), + (without_defaults(a="x", b=None), {"a": "x", "b": None, "c": 1}, {"c": 1}), + (without_defaults(a=1), {"a": 1.0}, None), + ], + ids=[ + "drops-the-default", + "keeps-another-value", + "keeps-absent", + "zero-is-not-false", + "drops-each-default", + "an-integer-is-not-a-float", + ], +) +def test_without_defaults_drops_each_member_written_with_its_default( + canonical: Callable[[Mapping[str, JSONValue]], Mapping[str, JSONValue]], + configuration: dict[str, JSONValue], + expected: dict[str, JSONValue] | None, +) -> None: + """`without_defaults` removes each member written with the value its absence means, and leaves every other member as written. It compares a value as JSON, so `0` is not `False` and `1.0` is not `1`. It takes a mapping or the read-only view a definition hands its `canonical`, and changes neither. `expected` is None where the configuration is already canonical.""" + before = copy.deepcopy(configuration) + for given in (configuration, MappingProxyType(configuration)): + assert dict(canonical(given)) == (configuration if expected is None else expected) + assert configuration == before + + +@pytest.mark.parametrize( + ("canonical", "configuration", "expected"), + [ + (with_defaults(level=1), {}, {"level": 1}), + (with_defaults(level=1), {"level": 5}, {"level": 5}), + (with_defaults(level=0, preset=None), {"level": 2}, {"level": 2, "preset": None}), + ], + ids=["writes-the-default", "keeps-a-written-value", "writes-each-absent-default"], +) +def test_with_defaults_writes_each_absent_member_with_its_default( + canonical: Callable[[Mapping[str, JSONValue]], Mapping[str, JSONValue]], + configuration: dict[str, JSONValue], + expected: dict[str, JSONValue], +) -> None: + """`with_defaults` writes each absent member with the value its absence means, and leaves every written member as written. It takes a mapping or the read-only view a definition hands its `canonical`, and changes neither.""" + before = copy.deepcopy(configuration) + for given in (configuration, MappingProxyType(configuration)): + assert dict(canonical(given)) == expected + assert configuration == before + + +def test_declared_defaults_are_values() -> None: + """Two canonical forms built from the same defaults, given in the same order, are equal and hash equal, so two definitions that hold them are the same definition. The order counts because `with_defaults` writes the members in it, so equal forms write a configuration the same way. They survive a pickle, a copy, and `dataclasses.replace`, which keeps the form in step with its new defaults. A canonical form that drops defaults is not one that writes them, and `0` and `False` are two defaults.""" + assert without_defaults(a=0, b="x") == without_defaults(a=0, b="x") + assert hash(without_defaults(a=0, b="x")) == hash(without_defaults(a=0, b="x")) + assert without_defaults(a=0) != without_defaults(a=False) + assert without_defaults(a=0) != with_defaults(a=0) + assert with_defaults(a=1, b=2) != with_defaults(b=2, a=1) + assert list(with_defaults(b=2, a=1)({"c": 0, "a": 5})) == ["b", "a", "c"] + for canonical in (without_defaults(a=0, b="x"), with_defaults(a=None)): + for again in (pickle.loads(pickle.dumps(canonical)), copy.deepcopy(canonical)): + assert again == canonical + assert hash(again) == hash(canonical) + replaced = dataclasses.replace(cast("Any", without_defaults(a=0)), defaults=(("a", 1),)) + assert replaced == without_defaults(a=1) + assert replaced({"a": 1}) == {} + + +@pytest.mark.parametrize("build", [without_defaults, with_defaults]) +def test_error_a_declared_default_that_is_not_a_scalar_is_refused( + build: Callable[..., object], +) -> None: + """A default is a string, a number, a boolean or null. Any other value raises `TypeError` where the definition is written, because a default that is a list or an object could be changed after the definition is built.""" + with pytest.raises( + TypeError, match=r"takes a string, a number, a boolean or null for 'a', got \[1\]" + ): + build(a=cast("Any", [1])) diff --git a/packages/zarr-metadata/tests/v3/test_every_definition.py b/packages/zarr-metadata/tests/v3/test_every_definition.py index c72161d85c..b6ea086acc 100644 --- a/packages/zarr-metadata/tests/v3/test_every_definition.py +++ b/packages/zarr-metadata/tests/v3/test_every_definition.py @@ -302,7 +302,8 @@ def test_every_example_reads_and_its_simplest_spelling_is_stable( }, ), # A member set to its spec default is left out: a key encoding's - # separator, a shard's index location, and zstd's checksum. + # separator, a shard's index location, zstd's checksum, and the + # rounding of `cast_value`. ({"name": "default", "configuration": {"separator": "/"}}, {"name": "default"}), ({"name": "v2", "configuration": {"separator": "."}}, {"name": "v2"}), ( @@ -334,6 +335,45 @@ def test_every_example_reads_and_its_simplest_spelling_is_stable( {"name": "zstd", "configuration": {"level": 3, "checksum": False}}, {"name": "zstd", "configuration": {"level": 3}}, ), + ( + { + "name": "cast_value", + "configuration": {"data_type": "uint8", "rounding": "nearest-even"}, + }, + {"name": "cast_value", "configuration": {"data_type": "uint8"}}, + ), + # A rounding other than the default is kept. + ( + { + "name": "cast_value", + "configuration": {"data_type": "uint8", "rounding": "towards-zero"}, + }, + { + "name": "cast_value", + "configuration": {"data_type": "uint8", "rounding": "towards-zero"}, + }, + ), + # An absent `out_of_range` has a meaning of its own, so a written + # one is always kept. + ( + { + "name": "cast_value", + "configuration": {"data_type": "uint8", "out_of_range": "clamp"}, + }, + { + "name": "cast_value", + "configuration": {"data_type": "uint8", "out_of_range": "clamp"}, + }, + ), + # NumPy's two spellings of microseconds are one unit. + ( + {"name": "numpy.datetime64", "configuration": {"unit": "μs", "scale_factor": 10}}, + {"name": "numpy.datetime64", "configuration": {"unit": "us", "scale_factor": 10}}, + ), + ( + {"name": "numpy.timedelta64", "configuration": {"unit": "μs", "scale_factor": 1}}, + {"name": "numpy.timedelta64", "configuration": {"unit": "us", "scale_factor": 1}}, + ), ], ids=[ "blosc-noshuffle", @@ -346,12 +386,19 @@ def test_every_example_reads_and_its_simplest_spelling_is_stable( "v2-separator", "sharding-index-location", "zstd-checksum", + "cast-value-rounding", + "cast-value-other-rounding", + "cast-value-out-of-range", + "datetime64-microseconds", + "timedelta64-microseconds", ], ) def test_the_simplest_spelling(declaration: dict[str, Any], simplest: object) -> None: kinds = { "rectilinear": ChunkGridDefinition, "int8": DataTypeDefinition, + "numpy.datetime64": DataTypeDefinition, + "numpy.timedelta64": DataTypeDefinition, "default": ChunkKeyEncodingDefinition, "v2": ChunkKeyEncodingDefinition, }