zarr-metadata 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/semantics.ts CHANGED
@@ -1,389 +1,38 @@
1
1
  /**
2
- * Semantic (cross-field) validation for v3 array metadata.
3
- *
4
- * The structural validators never interpret what an extension point names;
5
- * this module deliberately interprets a small set of WELL-KNOWN core
6
- * extension points to enforce the cross-field rules the specs state in
7
- * prose:
8
- *
9
- * - the `regular` chunk grid REQUIRES a configuration with `chunk_shape`,
10
- * which has one length per dimension of `shape`;
11
- * - the `rectilinear` chunk grid requires a configuration with `kind` and
12
- * `chunk_shapes`; `chunk_shapes` has one entry per dimension, and each
13
- * explicit chunk list (integers and `[size, count]` run-length pairs)
14
- * sums exactly to that dimension's length (the bare-integer uniform
15
- * shorthand carries no sum constraint, like the regular grid);
16
- * - a `transpose` codec's `order` is a permutation of `0..n-1`, with one
17
- * entry per array dimension;
18
- * - a `sharding_indexed` codec's inner `chunk_shape` matches the array's
19
- * dimensionality and evenly divides every chunk it shards — the grid's
20
- * chunk at the top level (each distinct per-dimension size, for
21
- * rectilinear grids), the parent shard's inner chunk when sharding
22
- * nests;
23
- * - `fill_value` has a JSON shape permitted for the named core data type
24
- * (booleans for `bool`, ranged integers for the int types, numbers /
25
- * the "NaN"-family sentinels / width-checked "0x…" strings for the
26
- * float types, two-element arrays for the complex types).
27
- *
28
- * Dimensional context is THREADED through codec pipelines rather than
29
- * assumed constant (mirroring zarr-python's chunk-spec threading): a valid
30
- * `transpose` permutes the per-dimension chunk sizes for the codecs after
31
- * it, and any codec this layer cannot reason about — `reshape` may change
32
- * a chunk's rank, and unknown codecs may do anything — invalidates the
33
- * dimensional context for the rest of the pipeline instead of letting
34
- * stale array-level facts produce false verdicts.
2
+ * Semantic (cross-field) validation for v3 array metadata: the
3
+ * orchestrator. The rules themselves live with their content —
4
+ * `chunk-grids.ts`, `codecs.ts`, and `data-types.ts` each hold the syntax
5
+ * (types) and semantics (procedures) for the names this package
6
+ * interprets, mirroring how the spec, the Python reference's type layout,
7
+ * and the zarr-extensions registry are organized. This module only walks
8
+ * documents: extract shape, ask each content module for its verdicts,
9
+ * thread the chunk-size context into codec pipelines, and descend into a
10
+ * group's inline consolidated entries.
35
11
  *
36
12
  * Unrecognized names are skipped everywhere — the extension name space is
37
13
  * open, and a rule that guessed would lie. This layer has no counterpart
38
14
  * in the Python reference implementation (which stops at structure), so it
39
15
  * is covered by this package's own tests rather than the conformance
40
- * corpus.
16
+ * corpus. The structural document layer (validation.ts) stays
17
+ * content-agnostic and corpus-governed; it never reads the content
18
+ * modules.
41
19
  */
42
20
 
21
+ import { chunkGridVerdict } from "./chunk-grids.js";
22
+ import { pipelineIssues } from "./codecs.js";
23
+ import { fillValueIssue } from "./data-types.js";
43
24
  import { treeOf, type ErrorTree, type PathedIssue } from "./errors.js";
44
-
45
- type Path = ReadonlyArray<string | number>;
46
-
47
- function isPlainObject(value: unknown): value is Record<string, unknown> {
48
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
49
- const proto: unknown = Object.getPrototypeOf(value);
50
- return proto === null || proto === Object.prototype;
51
- }
52
-
53
- function isIntArray(value: unknown): value is number[] {
54
- return (
55
- Array.isArray(value) &&
56
- Object.keys(value).length === value.length &&
57
- value.every((item) => Number.isInteger(item))
58
- );
59
- }
60
-
61
- /** The `{name, configuration}` of a metadata field, when extractable. */
62
- function fieldParts(
63
- field: unknown,
64
- ): { name: string; configuration: Record<string, unknown> | undefined } | undefined {
65
- if (typeof field === "string") return { name: field, configuration: undefined };
66
- if (isPlainObject(field) && typeof field["name"] === "string") {
67
- const configuration = field["configuration"];
68
- return {
69
- name: field["name"],
70
- configuration: isPlainObject(configuration) ? configuration : undefined,
71
- };
72
- }
73
- return undefined;
74
- }
75
-
76
- // --- fill_value vs data_type ----------------------------------------------
77
-
78
- const INT_RANGES: Record<string, readonly [number, number]> = {
79
- int8: [-128, 127],
80
- int16: [-32768, 32767],
81
- int32: [-2147483648, 2147483647],
82
- int64: [-9223372036854775808, 9223372036854775807],
83
- uint8: [0, 255],
84
- uint16: [0, 65535],
85
- uint32: [0, 4294967295],
86
- uint64: [0, 18446744073709551615],
87
- };
88
-
89
- const FLOAT_HEX_DIGITS: Record<string, number> = {
90
- float16: 4,
91
- float32: 8,
92
- float64: 16,
93
- };
94
-
95
- /** Hex digit width of each complex type's component floats. */
96
- const COMPLEX_COMPONENT_HEX_DIGITS: Record<string, number> = {
97
- complex64: 8,
98
- complex128: 16,
99
- };
100
-
101
- function isFloatFill(value: unknown, hexDigits: number): boolean {
102
- if (typeof value === "number") return true;
103
- if (typeof value !== "string") return false;
104
- if (value === "NaN" || value === "Infinity" || value === "-Infinity") return true;
105
- return new RegExp(`^0x[0-9a-fA-F]{${hexDigits}}$`).test(value);
106
- }
107
-
108
- function floatFillMessage(name: string, hexDigits: number): string {
109
- return (
110
- `expected a number, "NaN", "Infinity", "-Infinity", or a ` +
111
- `${hexDigits}-hex-digit "0x..." string for data type ${JSON.stringify(name)}`
112
- );
113
- }
114
-
115
- /** The fill_value issue for a KNOWN core data type, if any; undefined otherwise. */
116
- function fillValueIssue(dataTypeName: string, fill: unknown): string | undefined {
117
- if (dataTypeName === "bool") {
118
- return typeof fill === "boolean"
119
- ? undefined
120
- : 'expected a boolean fill value for data type "bool"';
121
- }
122
- const intRange = INT_RANGES[dataTypeName];
123
- if (intRange !== undefined) {
124
- const [low, high] = intRange;
125
- return Number.isInteger(fill) && (fill as number) >= low && (fill as number) <= high
126
- ? undefined
127
- : `expected an integer in [${low}, ${high}] for data type ${JSON.stringify(dataTypeName)}`;
128
- }
129
- const floatDigits = FLOAT_HEX_DIGITS[dataTypeName];
130
- if (floatDigits !== undefined) {
131
- return isFloatFill(fill, floatDigits)
132
- ? undefined
133
- : floatFillMessage(dataTypeName, floatDigits);
134
- }
135
- const complexDigits = COMPLEX_COMPONENT_HEX_DIGITS[dataTypeName];
136
- if (complexDigits !== undefined) {
137
- const ok =
138
- Array.isArray(fill) &&
139
- fill.length === 2 &&
140
- fill.every((part) => isFloatFill(part, complexDigits));
141
- return ok
142
- ? undefined
143
- : `expected a two-element [real, imaginary] array for data type ${JSON.stringify(dataTypeName)}`;
144
- }
145
- return undefined; // unrecognized data type: no verdict
146
- }
147
-
148
- // --- codec pipelines (transpose / sharding) --------------------------------
149
-
150
- function isPermutation(order: number[]): boolean {
151
- const seen = new Set(order);
152
- return seen.size === order.length && order.every((entry) => entry >= 0 && entry < order.length);
153
- }
154
-
155
- /**
156
- * Walk one codec pipeline. `dims` is the array dimensionality at this point
157
- * (undefined when unknowable); `outerChunkSizes` holds the distinct chunk
158
- * lengths per dimension this pipeline may encode — what a sharding codec's
159
- * inner chunks must divide. A regular grid contributes one size per
160
- * dimension; a rectilinear grid may contribute several.
161
- */
162
- function pipelineIssues(
163
- pipeline: unknown[],
164
- path: Path,
165
- initialDims: number | undefined,
166
- initialChunkSizes: number[][] | undefined,
167
- ): PathedIssue[] {
168
- const issues: PathedIssue[] = [];
169
- // The dimensional context THREADS through the pipeline: transpose permutes
170
- // it, and anything this layer cannot reason about invalidates it for the
171
- // remaining codecs.
172
- let dims = initialDims;
173
- let chunkSizes = initialChunkSizes;
174
- const dropContext = (): void => {
175
- dims = undefined;
176
- chunkSizes = undefined;
177
- };
178
- pipeline.forEach((entry, index) => {
179
- const parts = fieldParts(entry);
180
- if (parts === undefined) {
181
- dropContext(); // structurally invalid entry: no further reasoning
182
- return;
183
- }
184
- const { name, configuration } = parts;
185
- if (name === "transpose") {
186
- const order = configuration?.["order"];
187
- if (!isIntArray(order)) {
188
- dropContext(); // shape errors are the schema layer's
189
- return;
190
- }
191
- const orderPath = [...path, index, "configuration", "order"];
192
- let sound = true;
193
- if (!isPermutation(order)) {
194
- sound = false;
195
- issues.push({
196
- path: orderPath,
197
- message: `expected a permutation of the integers 0..${order.length - 1}`,
198
- kind: "invalid_value",
199
- });
200
- }
201
- if (dims !== undefined && order.length !== dims) {
202
- sound = false;
203
- issues.push({
204
- path: orderPath,
205
- message: `expected one entry per array dimension (${dims})`,
206
- kind: "invalid_value",
207
- });
208
- }
209
- if (!sound) {
210
- dropContext();
211
- } else if (chunkSizes !== undefined) {
212
- const sizes = chunkSizes;
213
- chunkSizes =
214
- order.length === sizes.length
215
- ? order.map((axis) => sizes[axis] as number[])
216
- : undefined;
217
- }
218
- } else if (name === "sharding_indexed") {
219
- const chunkShape = configuration?.["chunk_shape"];
220
- if (!isIntArray(chunkShape)) {
221
- dropContext();
222
- return;
223
- }
224
- const chunkShapePath = [...path, index, "configuration", "chunk_shape"];
225
- if (dims !== undefined && chunkShape.length !== dims) {
226
- issues.push({
227
- path: chunkShapePath,
228
- message: `expected one length per array dimension (${dims})`,
229
- kind: "invalid_value",
230
- });
231
- } else if (
232
- chunkSizes !== undefined &&
233
- chunkShape.length === chunkSizes.length &&
234
- chunkShape.every((length) => length > 0)
235
- ) {
236
- let violation: { axis: number; size: number } | undefined;
237
- chunkSizes.forEach((sizes, axis) => {
238
- if (violation !== undefined) return;
239
- const bad = sizes.find((size) => size % (chunkShape[axis] as number) !== 0);
240
- if (bad !== undefined) violation = { axis, size: bad };
241
- });
242
- if (violation !== undefined) {
243
- const { axis, size } = violation;
244
- const sizesNow = chunkSizes;
245
- const uniform = sizesNow.every((sizes) => sizes.length === 1);
246
- issues.push({
247
- path: chunkShapePath,
248
- message: uniform
249
- ? `expected ${JSON.stringify(chunkShape)} to evenly divide the outer chunk shape ${JSON.stringify(sizesNow.map((sizes) => sizes[0]))}`
250
- : `expected ${JSON.stringify(chunkShape)} to evenly divide every chunk size of the grid (dimension ${axis} has chunk size ${size})`,
251
- kind: "invalid_value",
252
- });
253
- }
254
- }
255
- const inner = configuration?.["codecs"];
256
- if (Array.isArray(inner)) {
257
- issues.push(
258
- ...pipelineIssues(
259
- inner,
260
- [...path, index, "configuration", "codecs"],
261
- chunkShape.length,
262
- chunkShape.map((length) => [length]),
263
- ),
264
- );
265
- }
266
- // index_codecs encode the shard index, whose shape differs from the
267
- // array's — no dimensional context applies there. After the
268
- // array -> bytes boundary the dimensional context is spent.
269
- dropContext();
270
- } else {
271
- // A codec this layer cannot reason about (reshape may change a
272
- // chunk's rank; unknown codecs may do anything): stale array-level
273
- // facts must not judge the codecs after it.
274
- dropContext();
275
- }
276
- });
277
- return issues;
278
- }
25
+ import { fieldParts, isIntArray, isPlainObject } from "./guards.js";
279
26
 
280
27
  function arraySemanticsIssues(value: unknown): PathedIssue[] {
281
28
  if (!isPlainObject(value) || value["node_type"] !== "array") return [];
282
29
  const issues: PathedIssue[] = [];
283
30
  const shape = isIntArray(value["shape"]) ? value["shape"] : undefined;
284
- const dims = shape?.length;
285
31
 
286
- const rawGrid = value["chunk_grid"];
287
- const grid = fieldParts(rawGrid);
288
- // Whether the field genuinely lacks a configuration member (a malformed
289
- // one — configuration: 5 — is the structural layer's complaint, not ours).
290
- const configMissing =
291
- typeof rawGrid === "string" ||
292
- (isPlainObject(rawGrid) && !Object.hasOwn(rawGrid, "configuration"));
293
- let chunkSizes: number[][] | undefined;
294
- if (grid?.name === "regular") {
295
- if (configMissing) {
296
- issues.push({
297
- path: ["chunk_grid"],
298
- message: '"regular" requires a configuration with "chunk_shape"',
299
- kind: "missing_key",
300
- });
301
- } else if (grid.configuration !== undefined && !Object.hasOwn(grid.configuration, "chunk_shape")) {
302
- issues.push({
303
- path: ["chunk_grid", "configuration", "chunk_shape"],
304
- message: "missing required key",
305
- kind: "missing_key",
306
- });
307
- }
308
- const configured = grid.configuration?.["chunk_shape"];
309
- if (isIntArray(configured)) {
310
- if (dims !== undefined && configured.length !== dims) {
311
- issues.push({
312
- path: ["chunk_grid", "configuration", "chunk_shape"],
313
- message: `expected one length per dimension of shape (${dims})`,
314
- kind: "invalid_value",
315
- });
316
- // wrong arity: unusable as division context
317
- } else {
318
- chunkSizes = configured.map((length) => [length]);
319
- }
320
- }
321
- } else if (grid?.name === "rectilinear") {
322
- if (configMissing) {
323
- issues.push({
324
- path: ["chunk_grid"],
325
- message: '"rectilinear" requires a configuration with "kind" and "chunk_shapes"',
326
- kind: "missing_key",
327
- });
328
- } else if (grid.configuration !== undefined) {
329
- for (const key of ["kind", "chunk_shapes"]) {
330
- if (!Object.hasOwn(grid.configuration, key)) {
331
- issues.push({
332
- path: ["chunk_grid", "configuration", key],
333
- message: "missing required key",
334
- kind: "missing_key",
335
- });
336
- }
337
- }
338
- }
339
- const specs = grid.configuration?.["chunk_shapes"];
340
- if (Array.isArray(specs)) {
341
- if (dims !== undefined && specs.length !== dims) {
342
- issues.push({
343
- path: ["chunk_grid", "configuration", "chunk_shapes"],
344
- message: `expected one entry per dimension of shape (${dims})`,
345
- kind: "invalid_value",
346
- });
347
- } else {
348
- const perDim: (number[] | undefined)[] = specs.map((spec, dim) => {
349
- // Bare integer: uniform shorthand, no sum constraint (edge chunks
350
- // are permitted, as with the regular grid).
351
- if (Number.isInteger(spec)) return spec as number > 0 ? [spec as number] : undefined;
352
- if (!Array.isArray(spec)) return undefined; // registry schema's problem
353
- const sizes = new Set<number>();
354
- let total = 0;
355
- for (const entry of spec) {
356
- if (Number.isInteger(entry)) {
357
- sizes.add(entry as number);
358
- total += entry as number;
359
- } else if (
360
- Array.isArray(entry) &&
361
- entry.length === 2 &&
362
- Number.isInteger(entry[0]) &&
363
- Number.isInteger(entry[1])
364
- ) {
365
- sizes.add(entry[0] as number);
366
- total += (entry[0] as number) * (entry[1] as number);
367
- } else {
368
- return undefined; // malformed entry: registry schema's problem
369
- }
370
- }
371
- const extent = shape?.[dim];
372
- if (extent !== undefined && total !== extent) {
373
- issues.push({
374
- path: ["chunk_grid", "configuration", "chunk_shapes", dim],
375
- message: `expected chunk sizes summing to ${extent} along dimension ${dim}, got ${total}`,
376
- kind: "invalid_value",
377
- });
378
- }
379
- return [...sizes];
380
- });
381
- if (perDim.every((sizes) => sizes !== undefined)) {
382
- chunkSizes = perDim as number[][];
383
- }
384
- }
385
- }
386
- }
32
+ const grid = chunkGridVerdict(value["chunk_grid"], shape);
33
+ issues.push(
34
+ ...grid.issues.map((issue) => ({ ...issue, path: ["chunk_grid", ...issue.path] })),
35
+ );
387
36
 
388
37
  const dataType = fieldParts(value["data_type"]);
389
38
  if (dataType !== undefined && "fill_value" in value) {
@@ -395,7 +44,7 @@ function arraySemanticsIssues(value: unknown): PathedIssue[] {
395
44
 
396
45
  const codecs = value["codecs"];
397
46
  if (Array.isArray(codecs)) {
398
- issues.push(...pipelineIssues(codecs, ["codecs"], dims, chunkSizes));
47
+ issues.push(...pipelineIssues(codecs, ["codecs"], shape?.length, grid.chunkSizes));
399
48
  }
400
49
  return issues;
401
50
  }