Repository navigation
Expand file tree
/
Copy pathv3.py
More file actions
778 lines (655 loc) · 31.4 KB
/
Copy pathv3.py
File metadata and controls
778 lines (655 loc) · 31.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
from __future__ import annotations
import json
from collections.abc import Iterable, Mapping, Sequence
from collections.abc import Set as AbstractSet
from dataclasses import dataclass, field, replace
from typing import TYPE_CHECKING, Any, ClassVar, Final, Literal, NotRequired, TypeGuard, cast
from typing_extensions import TypedDict
from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec, Codec
from zarr.abc.metadata import Metadata
from zarr.core._json import json_to_buffer
from zarr.core.array_spec import ArrayConfig, ArraySpec
from zarr.core.buffer.core import default_buffer_prototype
from zarr.core.chunk_grids import FixedDimension, VaryingDimension
from zarr.core.chunk_key_encodings import (
ChunkKeyEncoding,
ChunkKeyEncodingLike,
parse_chunk_key_encoding,
)
from zarr.core.common import (
JSON,
ZARR_JSON,
DimensionNamesLike,
NamedConfig,
NamedRequiredConfig,
NodeType,
compress_rle,
expand_rle,
expand_short_hand_name,
parse_chunk_edge,
parse_chunk_shape,
parse_named_configuration,
parse_shapelike,
validate_rectilinear_edges,
validate_rectilinear_kind,
)
from zarr.core.config import config
from zarr.core.dtype import VariableLengthUTF8, ZDType, get_data_type_from_json
from zarr.core.dtype.common import check_dtype_spec_v3
from zarr.core.json_parse import parse_field
from zarr.core.metadata.common import parse_attributes
from zarr.core.metadata.repair import (
mark_repaired,
repair_array_document,
)
from zarr.errors import MetadataValidationError, NodeTypeValidationError
from zarr.registry import get_codec_class
if TYPE_CHECKING:
from typing import Self
from zarr.codecs.sharding import ShardingCodec
from zarr.core.buffer import Buffer, BufferPrototype
from zarr.core.chunk_grids import ChunkGrid
from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar
from zarr.core.metadata.repair import ArrayDocument
def parse_zarr_format(data: object) -> Literal[3]:
return cast(
"Literal[3]", parse_field(data, Literal[3], "zarr_format", error=MetadataValidationError)
)
def parse_node_type_array(data: object) -> Literal["array"]:
return cast(
'Literal["array"]',
parse_field(data, Literal["array"], "node_type", error=NodeTypeValidationError),
)
def parse_codecs(data: object) -> tuple[Codec, ...]:
out: tuple[Codec, ...] = ()
if not isinstance(data, Iterable):
raise TypeError(f"Expected iterable, got {type(data)}")
for c in data:
if isinstance(
c, ArrayArrayCodec | ArrayBytesCodec | BytesBytesCodec
): # Can't use Codec here because of mypy limitation
out += (c,)
else:
c = expand_short_hand_name(c)
name_parsed, _ = parse_named_configuration(c, require_configuration=False)
codec_cls = get_codec_class(name_parsed)
try:
out += (codec_cls.from_dict(c),)
except KeyError as e:
# A codec's `from_dict` may index its configuration directly, so a malformed
# configuration surfaces as a KeyError. Convert it: a bare KeyError escaping
# metadata parsing is swallowed by the array-then-group fallback in
# `zarr.api.asynchronous.open`, which then reports an unrelated group error.
# The KeyError may carry no arguments (`raise KeyError`), and it may come from
# an internal lookup rather than the configuration mapping itself, so name the
# key only when there is one and don't claim it was a missing configuration key.
key_text = f" {e.args[0]!r}" if e.args else ""
raise MetadataValidationError(
f"KeyError{key_text} while parsing the configuration for codec {name_parsed!r}."
) from e
return out
def validate_array_bytes_codec(codecs: tuple[Codec, ...]) -> ArrayBytesCodec:
# ensure that we have at least one ArrayBytesCodec
abcs: list[ArrayBytesCodec] = [codec for codec in codecs if isinstance(codec, ArrayBytesCodec)]
if len(abcs) == 0:
raise ValueError("At least one ArrayBytesCodec is required.")
elif len(abcs) > 1:
raise ValueError("Only one ArrayBytesCodec is allowed.")
return abcs[0]
def validate_codecs(codecs: tuple[Codec, ...], dtype: ZDType[TBaseDType, TBaseScalar]) -> None:
"""Check that the codecs are valid for the given dtype"""
from zarr.codecs.sharding import ShardingCodec
abc = validate_array_bytes_codec(codecs)
# Recursively resolve array-bytes codecs within sharding codecs
while isinstance(abc, ShardingCodec):
abc = validate_array_bytes_codec(abc.codecs)
# we need to have special codecs if we are decoding vlen strings or bytestrings
# TODO: use codec ID instead of class name
codec_class_name = abc.__class__.__name__
# TODO: Fix typing here
if isinstance(dtype, VariableLengthUTF8) and not codec_class_name == "VLenUTF8Codec": # type: ignore[unreachable]
raise ValueError(
f"For string dtype, ArrayBytesCodec must be `VLenUTF8Codec`, got `{codec_class_name}`."
)
def parse_dimension_names(data: object) -> tuple[str | None, ...] | None:
if data is None:
return data
elif isinstance(data, Iterable) and all(isinstance(x, type(None) | str) for x in data):
return tuple(data)
else:
msg = f"Expected either None or an iterable of str, got {type(data)}"
raise TypeError(msg)
def parse_storage_transformers(data: object) -> tuple[dict[str, JSON], ...]:
"""
Parse storage_transformers. Zarr python cannot use storage transformers
at this time, so this function doesn't attempt to validate them.
"""
if data is None:
return ()
if isinstance(data, Iterable) and not isinstance(data, (str, bytes)):
# Materialise once. The previous implementation called ``len(tuple(data))``
# and then returned ``data`` itself, which exhausted (and discarded) a
# one-shot iterable and could return a value typed as a tuple that was not
# actually a tuple.
return tuple(expand_short_hand_name(t) for t in data)
raise TypeError(
f"Invalid storage_transformers. Expected an iterable of dicts. Got {type(data)} instead."
)
class AllowedExtraField(TypedDict, extra_items=JSON): # type: ignore[call-arg]
"""
This class models allowed extra fields in array or group metadata.
They must have `must_understand` set to `False`, and may contain
arbitrary additional JSON data.
"""
must_understand: Literal[False]
def check_allowed_extra_field(data: object) -> TypeGuard[AllowedExtraField]:
"""
Check if the extra field is allowed according to the Zarr v3 spec. The object
must be a mapping with a "must_understand" key set to `False`.
"""
return isinstance(data, Mapping) and data.get("must_understand") is False
def parse_extra_fields(
data: Mapping[str, object] | None,
*,
reserved_keys: AbstractSet[str],
node_type: NodeType,
) -> dict[str, AllowedExtraField]:
"""
Check the extra fields of a Zarr V3 metadata document.
Raises `ValueError` if a key collides with a key in `reserved_keys`, and
`MetadataValidationError` if a value is not an object with `"must_understand": false`.
"""
if data is None:
return {}
conflict_keys = reserved_keys & set(data.keys())
if len(conflict_keys) > 0:
msg = (
"Invalid extra fields. "
"The following keys: "
f"{sorted(conflict_keys)} "
"are invalid because they collide with keys reserved for use by the "
f"{node_type} metadata document."
)
raise ValueError(msg)
allowed_extra_fields: dict[str, AllowedExtraField] = {}
invalid_extra_fields: list[str] = []
for key, val in data.items():
if check_allowed_extra_field(val):
allowed_extra_fields[key] = val
else:
invalid_extra_fields.append(key)
if len(invalid_extra_fields) > 0:
msg = (
f"Got Zarr V3 {node_type} metadata with the following disallowed extra "
f"fields: {sorted(invalid_extra_fields)}. "
'Extra fields are not allowed unless they are an object with a "must_understand" '
"key which is assigned the value `false`."
)
raise MetadataValidationError(msg)
return allowed_extra_fields
# JSON type for a single dimension's rectilinear spec:
# bare int (uniform shorthand), or list of ints / [value, count] RLE pairs.
RectilinearDimSpecJSON = int | list[int | list[int]]
class RegularChunkGridMetadataConfig(TypedDict):
chunk_shape: Sequence[int]
class RectilinearChunkGridMetadataConfig(TypedDict):
kind: Literal["inline"]
chunk_shapes: Sequence[RectilinearDimSpecJSON]
RegularChunkGridMetadataJSON = NamedRequiredConfig[
Literal["regular"], RegularChunkGridMetadataConfig
]
RectilinearChunkGridMetadataJSON = NamedRequiredConfig[
Literal["rectilinear"], RectilinearChunkGridMetadataConfig
]
def _validate_chunk_shapes(
chunk_shapes: Sequence[int | Sequence[int]],
) -> tuple[int | tuple[int, ...], ...]:
"""Validate per-dimension chunk specifications.
Each element is either a bare ``int`` (regular step size, must be >= 1)
or a sequence of explicit edge lengths (all must be >= 1, non-empty).
"""
result: list[int | tuple[int, ...]] = []
for dim_idx, dim_spec in enumerate(chunk_shapes):
match dim_spec:
case list() | tuple():
edges = tuple(parse_chunk_edge(edge, dim_idx) for edge in dim_spec)
if not edges:
raise ValueError(f"Dimension {dim_idx} has no chunk edges.")
result.append(edges)
case _:
result.append(parse_chunk_edge(dim_spec, dim_idx))
return tuple(result)
@dataclass(frozen=True, kw_only=True)
class RegularChunkGridMetadata(Metadata):
"""Metadata-only description of a regular chunk grid.
Stores just the chunk shape — no array extent, no runtime logic.
This is what lives on ``ArrayV3Metadata.chunk_grid``.
"""
chunk_shape: tuple[int, ...]
def __post_init__(self) -> None:
chunk_shape_parsed = parse_chunk_shape(self.chunk_shape)
object.__setattr__(self, "chunk_shape", chunk_shape_parsed)
@property
def ndim(self) -> int:
return len(self.chunk_shape)
def to_dict(self) -> RegularChunkGridMetadataJSON: # type: ignore[override]
return {
"name": "regular",
"configuration": {"chunk_shape": self.chunk_shape},
}
@classmethod
def from_dict(cls, data: RegularChunkGridMetadataJSON) -> Self: # type: ignore[override]
parse_named_configuration(data, "regular") # validate name
configuration = data["configuration"]
return cls(chunk_shape=parse_chunk_shape(configuration["chunk_shape"]))
@dataclass(frozen=True, kw_only=True)
class RectilinearChunkGridMetadata(Metadata):
"""Metadata-only description of a rectilinear chunk grid.
Each element of ``chunk_shapes`` is either:
- A bare ``int`` — a regular step size that repeats to cover the axis
(the spec's single-integer shorthand).
- A ``tuple[int, ...]`` — explicit per-chunk edge lengths (already
expanded from any RLE encoding).
This distinction matters for faithful round-tripping: a bare int
serializes back as a bare int, while a single-element tuple serializes
as a list.
"""
chunk_shapes: tuple[int | tuple[int, ...], ...]
def __post_init__(self) -> None:
object.__setattr__(self, "chunk_shapes", _validate_chunk_shapes(self.chunk_shapes))
@property
def ndim(self) -> int:
return len(self.chunk_shapes)
def to_dict(self) -> RectilinearChunkGridMetadataJSON: # type: ignore[override]
serialized_dims: list[RectilinearDimSpecJSON] = []
for dim_spec in self.chunk_shapes:
if isinstance(dim_spec, int):
# Bare int shorthand — serialize as-is
serialized_dims.append(dim_spec)
else:
rle = compress_rle(dim_spec)
# Use RLE only if it's actually shorter
if len(rle) < len(dim_spec):
serialized_dims.append(rle)
else:
serialized_dims.append(list(dim_spec))
return {
"name": "rectilinear",
"configuration": {
"kind": "inline",
"chunk_shapes": tuple(serialized_dims),
},
}
def update_shape(
self, old_shape: tuple[int, ...], new_shape: tuple[int, ...]
) -> RectilinearChunkGridMetadata:
"""Return a new RectilinearChunkGridMetadata with edges adjusted for *new_shape*.
- Bare-int dimensions stay as bare ints (they cover any extent).
- Explicit-edge dimensions: if the new extent exceeds the sum of
edges, a new chunk is appended to cover the additional extent.
Otherwise edges are kept as-is (the spec allows trailing edges
beyond the array extent).
"""
new_chunk_shapes: list[int | tuple[int, ...]] = []
for dim_spec, new_ext in zip(self.chunk_shapes, new_shape, strict=True):
if isinstance(dim_spec, int):
# Bare int covers any extent — no change needed
new_chunk_shapes.append(dim_spec)
else:
edge_sum = sum(dim_spec)
if new_ext > edge_sum:
new_chunk_shapes.append((*dim_spec, new_ext - edge_sum))
else:
new_chunk_shapes.append(dim_spec)
return RectilinearChunkGridMetadata(chunk_shapes=tuple(new_chunk_shapes))
@classmethod
def from_dict(cls, data: RectilinearChunkGridMetadataJSON) -> Self: # type: ignore[override]
parse_named_configuration(data, "rectilinear") # validate name
configuration = data["configuration"]
validate_rectilinear_kind(configuration.get("kind"))
raw_shapes = configuration["chunk_shapes"]
parsed = [
tuple(expand_rle(dim_spec, axis)) if isinstance(dim_spec, list) else dim_spec
for axis, dim_spec in enumerate(raw_shapes)
]
return cls(chunk_shapes=tuple(parsed))
ChunkGridMetadata = RegularChunkGridMetadata | RectilinearChunkGridMetadata
class RectilinearChunksDisabledError(ValueError):
"""Rectilinear chunk grids are used while the `array.rectilinear_chunks` flag is off."""
def _check_rectilinear_chunks_enabled() -> None:
"""Raise unless rectilinear chunks are enabled.
The flag gates storing and reading array metadata documents that declare a
rectilinear chunk grid; the chunk grid metadata classes themselves are not gated.
"""
if not config.get("array.rectilinear_chunks"):
raise RectilinearChunksDisabledError(
"Rectilinear chunk grids are experimental and disabled by default. "
"Enable them with: zarr.config.set({'array.rectilinear_chunks': True}) "
"or set the environment variable ZARR_ARRAY__RECTILINEAR_CHUNKS=True"
)
def check_storable(metadata: ArrayV3Metadata) -> None:
"""Raise if `metadata` may not be stored: a rectilinear chunk grid requires the
rectilinear chunks flag. `zarr.core.metadata.io.encode_documents` names the node in
the error.
Every serialization of array metadata for a store calls this, before the store is
touched: `ArrayV3Metadata.to_buffer_dict` and, for the arrays in a group's
consolidated metadata, `GroupMetadata.to_buffer_dict`.
"""
if isinstance(metadata.chunk_grid, RectilinearChunkGridMetadata):
_check_rectilinear_chunks_enabled()
def create_chunk_grid_metadata(
chunks: ChunkGrid,
) -> ChunkGridMetadata:
"""Construct a chunk grid metadata object from a normalized `ChunkGrid`.
Regular grids produce a `RegularChunkGridMetadata`.
Rectilinear grids produce a `RectilinearChunkGridMetadata`.
Parameters
----------
chunks : ChunkGrid
Normalized chunk grid, as returned by
`normalize_chunks_nd` or `guess_chunks`.
See Also
--------
parse_chunk_grid : Deserialize a chunk grid from stored JSON metadata.
"""
if chunks.is_regular:
return RegularChunkGridMetadata(chunk_shape=chunks.chunk_shape)
# Uniform dimensions stay bare ints — the rectilinear grid spec treats
# a bare int as a step size repeating to cover the axis.
chunk_shapes: list[int | tuple[int, ...]] = []
for dim in chunks.dimensions:
if isinstance(dim, FixedDimension):
chunk_shapes.append(dim.size)
elif isinstance(dim, VaryingDimension):
chunk_shapes.append(dim.edges)
else:
raise TypeError(f"Unknown dimension grid type: {type(dim)}")
return RectilinearChunkGridMetadata(chunk_shapes=tuple(chunk_shapes))
def parse_chunk_grid(
data: dict[str, JSON] | ChunkGridMetadata | NamedConfig[str, Any],
) -> ChunkGridMetadata:
"""Deserialize a chunk grid from stored JSON metadata or pass through an existing instance.
See Also
--------
create_chunk_grid_metadata : Construct a chunk grid from user-facing input.
"""
if isinstance(data, (RegularChunkGridMetadata, RectilinearChunkGridMetadata)):
return data
data = expand_short_hand_name(data)
name, _ = parse_named_configuration(data)
if name == "regular":
return RegularChunkGridMetadata.from_dict(data) # type: ignore[arg-type]
if name == "rectilinear":
return RectilinearChunkGridMetadata.from_dict(data) # type: ignore[arg-type]
raise ValueError(f"Unknown chunk grid name: {name!r}")
class ArrayMetadataJSON_V3(TypedDict, extra_items=AllowedExtraField): # type: ignore[call-arg]
"""
A typed dictionary model for zarr v3 array metadata.
Extra keys are permitted if they conform to ``AllowedExtraField``
(i.e. they are mappings with ``must_understand: false``).
"""
zarr_format: Literal[3]
node_type: Literal["array"]
data_type: str | NamedConfig[str, Mapping[str, JSON]]
shape: tuple[int, ...]
chunk_grid: str | NamedConfig[str, Mapping[str, JSON]]
chunk_key_encoding: str | NamedConfig[str, Mapping[str, JSON]]
fill_value: JSON
codecs: tuple[str | NamedConfig[str, Mapping[str, JSON]], ...]
attributes: NotRequired[Mapping[str, JSON]]
storage_transformers: NotRequired[tuple[str | NamedConfig[str, Mapping[str, JSON]], ...]]
dimension_names: NotRequired[tuple[str | None, ...]]
"""
The names of the fields of the array metadata document defined in the zarr V3 spec.
"""
ARRAY_METADATA_KEYS: Final[set[str]] = {
"zarr_format",
"node_type",
"data_type",
"shape",
"chunk_grid",
"chunk_key_encoding",
"fill_value",
"codecs",
"attributes",
"storage_transformers",
"dimension_names",
}
@dataclass(frozen=True, kw_only=True)
class ArrayV3Metadata(Metadata):
shape: tuple[int, ...]
data_type: ZDType[TBaseDType, TBaseScalar]
chunk_grid: ChunkGridMetadata
chunk_key_encoding: ChunkKeyEncoding
fill_value: Any
codecs: tuple[Codec, ...]
attributes: dict[str, Any] = field(default_factory=dict)
dimension_names: tuple[str | None, ...] | None = None
zarr_format: Literal[3] = field(default=3, init=False)
node_type: Literal["array"] = field(default="array", init=False)
storage_transformers: tuple[dict[str, JSON], ...]
extra_fields: dict[str, AllowedExtraField]
_stored_document: ClassVar[ArrayDocument | None] = None
"""The stored document `from_dict` read this metadata from, if it had to repair it
(set on the instance by `mark_repaired`): the store may still hold it."""
def __init__(
self,
*,
shape: Iterable[int],
data_type: ZDType[TBaseDType, TBaseScalar],
chunk_grid: dict[str, JSON] | ChunkGridMetadata | NamedConfig[str, Any],
chunk_key_encoding: ChunkKeyEncodingLike,
fill_value: object,
codecs: Iterable[Codec | dict[str, JSON] | NamedConfig[str, Any] | str],
attributes: dict[str, JSON] | None,
dimension_names: DimensionNamesLike,
storage_transformers: Iterable[dict[str, JSON]] | None = None,
extra_fields: Mapping[str, AllowedExtraField] | None = None,
) -> None:
"""
Because the class is a frozen dataclass, we set attributes using object.__setattr__
"""
shape_parsed = parse_shapelike(shape)
chunk_grid_parsed = parse_chunk_grid(chunk_grid)
chunk_key_encoding_parsed = parse_chunk_key_encoding(chunk_key_encoding)
dimension_names_parsed = parse_dimension_names(dimension_names)
# Note: relying on a type method is numpy-specific
fill_value_parsed = data_type.cast_scalar(fill_value)
attributes_parsed = parse_attributes(attributes)
codecs_parsed_partial = parse_codecs(codecs)
storage_transformers_parsed = parse_storage_transformers(storage_transformers)
extra_fields_parsed = parse_extra_fields(
extra_fields, reserved_keys=ARRAY_METADATA_KEYS, node_type="array"
)
array_spec = ArraySpec(
shape=shape_parsed,
dtype=data_type,
fill_value=fill_value_parsed,
config=ArrayConfig.from_dict({}), # TODO: config is not needed here.
prototype=default_buffer_prototype(), # TODO: prototype is not needed here.
)
# Thread the spec through evolution: each codec must be evolved against
# the spec it will actually see at run-time, not the original array spec.
# Earlier array->array codecs may transform the dtype (e.g. cast_value),
# so the spec passed to later codecs must reflect those transformations.
# Per-codec validate() must run before resolve_metadata(), since the
# latter may rely on invariants the former checks (e.g. cast_value
# rejects complex source dtypes that would otherwise crash _do_cast).
evolved: list[Codec] = []
spec = array_spec
for c in codecs_parsed_partial:
evolved_codec = c.evolve_from_array_spec(spec)
evolved_codec.validate(shape=spec.shape, dtype=spec.dtype, chunk_grid=chunk_grid_parsed)
evolved.append(evolved_codec)
spec = evolved_codec.resolve_metadata(spec)
codecs_parsed = tuple(evolved)
validate_codecs(codecs_parsed_partial, data_type)
object.__setattr__(self, "shape", shape_parsed)
object.__setattr__(self, "data_type", data_type)
object.__setattr__(self, "chunk_grid", chunk_grid_parsed)
object.__setattr__(self, "chunk_key_encoding", chunk_key_encoding_parsed)
object.__setattr__(self, "codecs", codecs_parsed)
object.__setattr__(self, "dimension_names", dimension_names_parsed)
object.__setattr__(self, "fill_value", fill_value_parsed)
object.__setattr__(self, "attributes", attributes_parsed)
object.__setattr__(self, "storage_transformers", storage_transformers_parsed)
object.__setattr__(self, "extra_fields", extra_fields_parsed)
self._validate_metadata()
def _validate_metadata(self) -> None:
if len(self.shape) != self.chunk_grid.ndim:
raise ValueError("`chunk_grid` and `shape` need to have the same number of dimensions.")
if isinstance(self.chunk_grid, RectilinearChunkGridMetadata):
validate_rectilinear_edges(self.chunk_grid.chunk_shapes, self.shape)
if self.dimension_names is not None and len(self.shape) != len(self.dimension_names):
raise ValueError(
"`dimension_names` and `shape` need to have the same number of dimensions."
)
if self.fill_value is None:
raise ValueError("`fill_value` is required.")
for codec in self.codecs:
codec.validate(shape=self.shape, dtype=self.data_type, chunk_grid=self.chunk_grid)
@property
def ndim(self) -> int:
return len(self.shape)
@property
def dtype(self) -> ZDType[TBaseDType, TBaseScalar]:
return self.data_type
# TODO: move these properties to the Array class.
# They require knowledge of codecs (ShardingCodec) and don't belong on a metadata DTO.
@property
def sharding_codec(self) -> ShardingCodec | None:
"""The array's sharding codec, or None if the array is not sharded."""
from zarr.codecs.sharding import ShardingCodec
if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec):
return self.codecs[0]
return None
@property
def chunks(self) -> tuple[int, ...]:
if (sharding_codec := self.sharding_codec) is not None:
# Inner chunks are always regular, whatever the shape of the outer
# (shard) grid.
return sharding_codec.chunk_shape
if not isinstance(self.chunk_grid, RegularChunkGridMetadata):
msg = (
"The `chunks` attribute is only defined for arrays using regular chunk grids. "
"This array has a rectilinear chunk grid. Use `read_chunk_sizes` for general access."
)
raise NotImplementedError(msg)
return self.chunk_grid.chunk_shape
@property
def shards(self) -> tuple[int, ...] | None:
if self.sharding_codec is not None:
if not isinstance(self.chunk_grid, RegularChunkGridMetadata):
msg = (
"The `shards` attribute is only defined for arrays using regular chunk grids. "
"This array has a rectilinear chunk grid. Use `write_chunk_sizes` for general access."
)
raise NotImplementedError(msg)
return self.chunk_grid.chunk_shape
return None
@property
def inner_codecs(self) -> tuple[Codec, ...]:
if (sharding_codec := self.sharding_codec) is not None:
return sharding_codec.codecs
return self.codecs
def encode_chunk_key(self, chunk_coords: tuple[int, ...]) -> str:
return self.chunk_key_encoding.encode_chunk_key(chunk_coords)
def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]:
check_storable(self)
indent = config.get("json_indent")
return {ZARR_JSON: json_to_buffer(self.to_dict(), prototype=prototype, indent=indent)}
@classmethod
def from_dict(cls, data: dict[str, JSON], *, path: str | None = None) -> Self:
"""Read a stored `zarr.json` array document. An invalid document that
`zarr.core.metadata.repair` can read is read as repaired; a reading the user
must act on warns, and a document the rectilinear chunks flag refuses raises,
naming the array at `path`."""
# The flag gates what the document declares, so it is checked before repairs.
chunk_grid = data.get("chunk_grid")
if isinstance(chunk_grid, Mapping) and chunk_grid.get("name") == "rectilinear":
try:
_check_rectilinear_chunks_enabled()
except ValueError as e:
if path is not None:
e.add_note(f"Array {path!r}: nothing was read.")
raise
repaired, readings = repair_array_document(data, 3)
# a new dict, because we are modifying it
_data = dict(repaired)
# check that the zarr_format attribute is correct
_ = parse_zarr_format(_data.pop("zarr_format"))
# check that the node_type attribute is correct
_ = parse_node_type_array(_data.pop("node_type"))
data_type_json = _data.pop("data_type")
if not check_dtype_spec_v3(data_type_json):
raise ValueError(f"Invalid data_type: {data_type_json!r}")
data_type = get_data_type_from_json(data_type_json, zarr_format=3)
# check that the fill value is consistent with the data type
try:
fill = _data.pop("fill_value")
fill_value_parsed = data_type.from_json_scalar(fill, zarr_format=3)
except ValueError as e:
raise TypeError(f"Invalid fill_value: {fill!r}") from e
# check if there are extra keys
allowed_extra_fields = parse_extra_fields(
{k: v for k, v in _data.items() if k not in ARRAY_METADATA_KEYS},
reserved_keys=ARRAY_METADATA_KEYS,
node_type="array",
)
# TODO: replace this with a real type check!
_data_typed = cast(ArrayMetadataJSON_V3, _data)
metadata = cls(
shape=_data_typed["shape"],
chunk_grid=_data_typed["chunk_grid"], # type: ignore[arg-type]
chunk_key_encoding=_data_typed["chunk_key_encoding"],
codecs=_data_typed["codecs"],
# Attribute values are arbitrary JSON, so they have no field-specific
# schema to validate. `__init__` checks the outer dict via `parse_attributes`.
attributes=_data_typed.get("attributes", {}), # type: ignore[arg-type]
dimension_names=_data_typed.get("dimension_names", None),
fill_value=fill_value_parsed,
data_type=data_type,
extra_fields=allowed_extra_fields,
storage_transformers=_data_typed.get("storage_transformers", ()), # type: ignore[arg-type]
)
return mark_repaired(metadata, data, readings, path)
def to_dict(self) -> dict[str, JSON]:
out_dict = super().to_dict()
extra_fields = out_dict.pop("extra_fields")
out_dict = out_dict | extra_fields # type: ignore[operator]
out_dict["chunk_grid"] = self.chunk_grid.to_dict()
out_dict["fill_value"] = self.data_type.to_json_scalar(
self.fill_value, zarr_format=self.zarr_format
)
if not isinstance(out_dict, dict):
raise TypeError(f"Expected dict. Got {type(out_dict)}.")
# if `dimension_names` is `None`, we do not include it in
# the metadata document
if out_dict["dimension_names"] is None:
out_dict.pop("dimension_names")
# TODO: replace the `to_dict` / `from_dict` on the `Metadata`` class with
# to_json, from_json, and have ZDType inherit from `Metadata`
# until then, we have this hack here, which relies on the fact that to_dict will pass through
# any non-`Metadata` fields as-is.
dtype_meta = out_dict["data_type"]
if isinstance(dtype_meta, ZDType):
out_dict["data_type"] = dtype_meta.to_json(zarr_format=3) # type: ignore[unreachable]
return out_dict
def __eq__(self, other: object) -> bool:
# The default dataclass __eq__ compares fields directly, which is wrong for a NaN
# fill_value: NaN != NaN under IEEE 754. Comparing the JSON-serialized form instead
# treats matching NaN (and inf) fill values as equal. See issue #2929.
if not isinstance(other, ArrayV3Metadata):
return NotImplemented
return self.to_dict() == other.to_dict()
def __hash__(self) -> int:
# Hash the JSON-serialized form to stay consistent with __eq__: equal metadata
# must hash equally, which a field-based hash violates for a NaN fill_value.
return hash(json.dumps(self.to_dict(), sort_keys=True))
def update_shape(self, shape: tuple[int, ...]) -> Self:
chunk_grid = self.chunk_grid
if isinstance(chunk_grid, RectilinearChunkGridMetadata):
chunk_grid = chunk_grid.update_shape(self.shape, shape)
return replace(self, shape=shape, chunk_grid=chunk_grid)
def update_attributes(self, attributes: dict[str, JSON]) -> Self:
return replace(self, attributes=attributes)