zarrchive 0.2.0__py3-none-any.whl

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.
zarrchive/__init__.py ADDED
@@ -0,0 +1,72 @@
1
+ """zarrchive: schema-driven Zarr v3 storage for all-sky camera sensor data.
2
+
3
+ A template (YAML) describes a dataset's dimensions, variables, dtypes, chunking,
4
+ sharding, codecs, and metadata. :class:`Zarrchive` creates the store from that
5
+ template, appends to it one capture at a time, and reads it back.
6
+
7
+ The store is appendable by design: the same code runs on the sensor writing a
8
+ frame and on the server backfilling a month, and neither rebuilds the archive.
9
+
10
+ This library describes *storage only*. How data is acquired -- files, demosaicing,
11
+ masks -- is the caller's concern.
12
+
13
+ How the code is organised
14
+ -------------------------
15
+ As much logic as possible is kept in *pure* functions: functions whose result
16
+ depends only on their arguments, which read no files, hold no state between calls,
17
+ and change nothing outside themselves (not even their inputs). Pure code is easy to
18
+ test and to reason about, because the same input always gives the same output.
19
+
20
+ Reading and writing the store necessarily depends on the filesystem -- on state
21
+ that lives outside the program -- so it cannot be pure. That code is confined to a
22
+ few modules, kept deliberately thin, so the bulk of the logic stays pure. Each
23
+ module's docstring says which kind it is.
24
+
25
+ Examples
26
+ --------
27
+ >>> from zarrchive import Zarrchive
28
+ >>> with Zarrchive("out.zarr", "cam_schema2.yaml") as store: # doctest: +SKIP
29
+ ... store.write("example_timeseries", 1.0, loc={"time": "2020-01-01T09:00:00"})
30
+
31
+ Reading needs nothing from this package -- the store is plain Zarr v3:
32
+
33
+ >>> import imagecodecs.zarr, xarray as xr # doctest: +SKIP
34
+ >>> imagecodecs.zarr.register_codecs() # doctest: +SKIP
35
+ >>> ds = xr.open_zarr("out.zarr") # doctest: +SKIP
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import logging
41
+
42
+ from zarrchive.cam_store import Zarrchive
43
+ from zarrchive.codecs import set_jpegxl_threads
44
+ from zarrchive.planning import time_label_for
45
+ from zarrchive.schema import (
46
+ CF_CONVENTIONS,
47
+ EncodingSpec,
48
+ TemplateSpec,
49
+ TimeGridSpec,
50
+ VariableSpec,
51
+ load_template,
52
+ )
53
+ from zarrchive.store_file_dir_count import estimate_store_file_dir_count
54
+ from zarrchive.store_writer import DeleteAfterReport, DeleteBeforeReport
55
+
56
+ # A library configures no handlers; the application decides where logs go.
57
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
58
+
59
+ __all__ = [
60
+ "CF_CONVENTIONS",
61
+ "DeleteAfterReport",
62
+ "DeleteBeforeReport",
63
+ "EncodingSpec",
64
+ "TemplateSpec",
65
+ "TimeGridSpec",
66
+ "VariableSpec",
67
+ "Zarrchive",
68
+ "estimate_store_file_dir_count",
69
+ "load_template",
70
+ "set_jpegxl_threads",
71
+ "time_label_for",
72
+ ]
zarrchive/append.py ADDED
@@ -0,0 +1,458 @@
1
+ """Grow a store in place, without rebuilding it.
2
+
3
+ This is the machinery behind the append guarantee: the same code runs on the
4
+ sensor writing one capture and on the server backfilling a month, and neither
5
+ rewrites what is already there.
6
+
7
+ The trick throughout is to never materialise data in memory just to make room.
8
+ Arrays are resized on disk, which leaves the new slots implicit -- zarr reports
9
+ them as fill until a region write lands. Only the ``time`` coordinate itself is
10
+ written out, and only the part of it that changed.
11
+
12
+ Resizing is split by direction on purpose. :func:`grow_store_arrays` makes room
13
+ and refuses to shrink; :func:`truncate_store_arrays` deletes from the *end* and
14
+ refuses to grow. Neither can delete from the *start* -- a zarr array pins index 0
15
+ to the first chunk key and has no origin offset -- so oldest-first deletion is a
16
+ different mechanism entirely.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import logging
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+ import xarray as xr
27
+ import zarr
28
+
29
+ from zarrchive.chunking import is_dimension_variable, variable_chunk_list_spec
30
+ from zarrchive.encoding import DEFAULT_CHUNK_KEY_SEPARATOR, build_write_encoding
31
+ from zarrchive.schema import TIME_VARIABLE, TemplateSpec, VariableSpec
32
+ from zarrchive.structure import variable_attributes
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ def clear_consolidated_metadata(store_path: Path) -> None:
38
+ """
39
+ Drop consolidated metadata so resized or appended arrays stay visible.
40
+
41
+ Parameters
42
+ ----------
43
+ store_path : pathlib.Path
44
+ The store directory.
45
+
46
+ Notes
47
+ -----
48
+ Consolidated metadata is a cached copy of every array's metadata. After a
49
+ resize it disagrees with the arrays themselves, and a reader trusting the
50
+ cache would see stale shapes. It is rebuilt by
51
+ :func:`consolidate_store_metadata` at the end of a run.
52
+ """
53
+ meta_path = store_path / "zarr.json"
54
+ if not meta_path.is_file():
55
+ return
56
+ meta = json.loads(meta_path.read_text(encoding="utf-8"))
57
+ if "consolidated_metadata" not in meta:
58
+ return
59
+ del meta["consolidated_metadata"]
60
+ meta_path.write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
61
+
62
+
63
+ def consolidate_store_metadata(store_path: Path) -> None:
64
+ """
65
+ Write consolidated metadata, so a reader opens the store in one request.
66
+
67
+ Parameters
68
+ ----------
69
+ store_path : pathlib.Path
70
+ The store directory.
71
+ """
72
+ zarr.consolidate_metadata(store_path)
73
+
74
+
75
+ def _resize_arrays(
76
+ store_path: Path,
77
+ template: TemplateSpec,
78
+ dim_sizes: dict[str, int],
79
+ only_names: set[str] | None,
80
+ ) -> None:
81
+ """
82
+ Resize on-disk arrays to match *dim_sizes*, allocating nothing in memory.
83
+
84
+ Shared core of :func:`grow_store_arrays` and :func:`truncate_store_arrays`,
85
+ which differ only in the direction they permit. Variables with static
86
+ ``values`` are skipped: they are fully written at creation and never resize.
87
+ """
88
+ for name, var_spec in template.variables.items():
89
+ if only_names is not None and name not in only_names:
90
+ continue
91
+ if var_spec.values is not None:
92
+ continue
93
+ path = template.path(name)
94
+ if not (store_path / path / "zarr.json").is_file():
95
+ continue
96
+
97
+ new_shape = tuple(int(dim_sizes[dim]) for dim in var_spec.dimensions)
98
+ array = zarr.open_array(store_path / path, mode="a", zarr_format=3)
99
+ if tuple(array.shape) != new_shape:
100
+ logger.info("Resizing %s: %s -> %s", name, tuple(array.shape), new_shape)
101
+ array.resize(new_shape)
102
+
103
+
104
+ def grow_store_arrays(
105
+ store_path: Path,
106
+ template: TemplateSpec,
107
+ dim_sizes: dict[str, int],
108
+ *,
109
+ only_names: set[str] | None = None,
110
+ ) -> None:
111
+ """
112
+ Grow on-disk arrays to match *dim_sizes*, allocating nothing in memory.
113
+
114
+ Parameters
115
+ ----------
116
+ store_path : pathlib.Path
117
+ The store directory.
118
+ template : TemplateSpec
119
+ The template describing the store.
120
+ dim_sizes : dict of str to int
121
+ Target length of each dimension. Must be at least the current length.
122
+ only_names : set of str, optional
123
+ Restrict the resize to these variables. Defaults to all of them.
124
+
125
+ Raises
126
+ ------
127
+ ValueError
128
+ A dimension would shrink. Deleting data is
129
+ :func:`truncate_store_arrays`' job, and doing it here would be silent.
130
+
131
+ Notes
132
+ -----
133
+ New slots stay implicit -- zarr reports them as fill value until a region
134
+ write lands. Variables with static ``values`` are skipped: they are fully
135
+ written at creation and do not grow.
136
+ """
137
+ _reject_wrong_direction(store_path, template, dim_sizes, only_names, grow=True)
138
+ _resize_arrays(store_path, template, dim_sizes, only_names)
139
+
140
+
141
+ def truncate_store_arrays(
142
+ store_path: Path,
143
+ template: TemplateSpec,
144
+ dim_sizes: dict[str, int],
145
+ *,
146
+ only_names: set[str] | None = None,
147
+ ) -> None:
148
+ """
149
+ Shrink on-disk arrays to *dim_sizes*, deleting the chunks past the new end.
150
+
151
+ This is newest-first deletion. Zarr pins index 0 to the first chunk key and
152
+ has no origin offset, so a resize can only drop the *high* indices -- see
153
+ :func:`zarrchive.store_writer.apply_prune` for the oldest-first case, which
154
+ removes whole shard files instead and leaves the shape alone.
155
+
156
+ Parameters
157
+ ----------
158
+ store_path : pathlib.Path
159
+ The store directory.
160
+ template : TemplateSpec
161
+ The template describing the store.
162
+ dim_sizes : dict of str to int
163
+ Target length of each dimension. Must be at most the current length, and
164
+ a whole multiple of the shard (or chunk) size along any dimension that
165
+ shrinks. Dimension coordinates are exempt; rewrite them afterwards
166
+ with :func:`write_time_coordinate`.
167
+ only_names : set of str, optional
168
+ Restrict the resize to these variables. Defaults to all of them.
169
+
170
+ Raises
171
+ ------
172
+ ValueError
173
+ A dimension would grow, or a shrinking dimension lands mid-block.
174
+
175
+ Notes
176
+ -----
177
+ The block-boundary rule is not cosmetic. Zarr deletes only the chunks (or
178
+ shards) that fall *entirely* outside the new shape; a partially-filled one
179
+ is left intact, so data past the cut survives inside it and reappears if
180
+ the array is grown again. Cutting on a boundary is the only way to make the
181
+ deletion real.
182
+
183
+ This resizes arrays and nothing else. A caller truncating the ``time`` axis
184
+ must follow up with :func:`write_time_coordinate` to shorten the coordinate
185
+ to match, and :func:`clear_consolidated_metadata` so readers see the new
186
+ shape.
187
+ """
188
+ _reject_wrong_direction(store_path, template, dim_sizes, only_names, grow=False)
189
+ _reject_unaligned_cut(store_path, template, dim_sizes, only_names)
190
+ _resize_arrays(store_path, template, dim_sizes, only_names)
191
+
192
+
193
+ def _resizable_arrays(
194
+ store_path: Path,
195
+ template: TemplateSpec,
196
+ only_names: set[str] | None,
197
+ ) -> list[tuple[str, VariableSpec, zarr.Array]]:
198
+ """Template variables that exist on disk and are allowed to resize."""
199
+ found = []
200
+ for name, var_spec in template.variables.items():
201
+ if only_names is not None and name not in only_names:
202
+ continue
203
+ if var_spec.values is not None:
204
+ continue
205
+ path = template.path(name)
206
+ if not (store_path / path / "zarr.json").is_file():
207
+ continue
208
+ found.append((name, var_spec, zarr.open_array(store_path / path, mode="r")))
209
+ return found
210
+
211
+
212
+ def _reject_wrong_direction(
213
+ store_path: Path,
214
+ template: TemplateSpec,
215
+ dim_sizes: dict[str, int],
216
+ only_names: set[str] | None,
217
+ *,
218
+ grow: bool,
219
+ ) -> None:
220
+ """Refuse a resize that moves any dimension the wrong way."""
221
+ verb, other = (
222
+ ("shrink", "truncate_store_arrays")
223
+ if grow
224
+ else (
225
+ "grow",
226
+ "grow_store_arrays",
227
+ )
228
+ )
229
+ for name, var_spec, array in _resizable_arrays(store_path, template, only_names):
230
+ for axis, dim in enumerate(var_spec.dimensions):
231
+ old, new = int(array.shape[axis]), int(dim_sizes[dim])
232
+ if (new < old) if grow else (new > old):
233
+ raise ValueError(
234
+ f"{name!r} would {verb} along {dim!r} ({old} -> {new}). "
235
+ f"Use {other}() for that.",
236
+ )
237
+
238
+
239
+ def _deletable_block(array: zarr.Array, axis: int) -> int:
240
+ """
241
+ The smallest unit *deletion* works on, along one axis.
242
+
243
+ The shard where the array is sharded, the chunk otherwise: a shard is one
244
+ file, so zarr keeps the whole of it as long as any part is still in range.
245
+ """
246
+ if array.shards is not None:
247
+ return int(array.shards[axis])
248
+ return int(array.chunks[axis])
249
+
250
+
251
+ def _reject_unaligned_cut(
252
+ store_path: Path,
253
+ template: TemplateSpec,
254
+ dim_sizes: dict[str, int],
255
+ only_names: set[str] | None,
256
+ ) -> None:
257
+ """
258
+ Refuse a truncation that lands mid-block, because it would not delete.
259
+
260
+ Dimension coordinates are exempt. They are rewritten wholesale after a
261
+ truncation -- see :func:`write_time_coordinate` -- so a stale value left
262
+ inside a boundary block is overwritten rather than resurrected. Every other
263
+ variable holds data nothing rewrites, so the cut has to fall on a boundary.
264
+ """
265
+ for name, var_spec, array in _resizable_arrays(store_path, template, only_names):
266
+ if is_dimension_variable(name, var_spec, template):
267
+ continue
268
+ for axis, dim in enumerate(var_spec.dimensions):
269
+ old, new = int(array.shape[axis]), int(dim_sizes[dim])
270
+ if new >= old:
271
+ continue
272
+ block = _deletable_block(array, axis)
273
+ if new % block:
274
+ raise ValueError(
275
+ f"Truncating {name!r} to {new} along {dim!r} lands inside a "
276
+ f"block of {block}. Zarr keeps a partially-filled block "
277
+ f"intact, so the data past the cut would survive in it and "
278
+ f"reappear on a regrow. Cut at {(new // block) * block} or "
279
+ f"{(new // block + 1) * block}.",
280
+ )
281
+
282
+
283
+ def _fixed_time_chunk(template: TemplateSpec, time_var: VariableSpec) -> int | None:
284
+ """
285
+ The ``time`` coordinate's declared chunk size, when it is a fixed number.
286
+
287
+ Returns ``None`` when the template leaves it as one chunk spanning the whole
288
+ axis (the default for a coordinate). Such a chunk changes size on every
289
+ extension, and zarr cannot re-chunk an array in place -- so that layout can
290
+ only be maintained by deleting and rewriting the array.
291
+ """
292
+ spec = variable_chunk_list_spec(TIME_VARIABLE, time_var, template)
293
+ if spec is None or spec[0] <= 0:
294
+ return None
295
+ return int(spec[0])
296
+
297
+
298
+ def write_time_coordinate(
299
+ store_path: Path,
300
+ template: TemplateSpec,
301
+ time_var: VariableSpec,
302
+ time_values: np.ndarray,
303
+ *,
304
+ start: int = 0,
305
+ chunk_key_separator: str = DEFAULT_CHUNK_KEY_SEPARATOR,
306
+ ) -> None:
307
+ """
308
+ Write the ``time`` coordinate, touching as few chunks as possible.
309
+
310
+ Parameters
311
+ ----------
312
+ store_path : pathlib.Path
313
+ The store directory.
314
+ template : TemplateSpec
315
+ The template describing the store.
316
+ time_var : VariableSpec
317
+ The ``time`` coordinate's schema entry.
318
+ time_values : numpy.ndarray
319
+ The full time axis, as it should read after this call.
320
+ start : int, optional
321
+ Index of the first *changed* value. Everything below it is already on
322
+ disk and correct, so it is not rewritten. Defaults to ``0``, a full write.
323
+ chunk_key_separator : {".", "/"}, optional
324
+ Chunk key separator, used when the array is (re)created.
325
+
326
+ Notes
327
+ -----
328
+ Two layouts, and the template picks which one applies.
329
+
330
+ When ``time`` declares a fixed chunk size (``chunks: {time: 1024}``), the
331
+ array is resized and only the chunks from *start* on are written. A store on
332
+ a 15-minute cadence then pays one small chunk per append no matter how long
333
+ the axis has grown -- which matters on flash, where the whole-array rewrite
334
+ below is a steady write-amplification source.
335
+
336
+ When it does not, the chunk spans the whole axis and therefore changes size
337
+ on every extension. Zarr cannot re-chunk in place, so the array is deleted
338
+ and rewritten. That is the historical layout, kept working for stores and
339
+ templates that predate the declared chunk.
340
+ """
341
+ n = len(time_values)
342
+ if n == 0:
343
+ return
344
+
345
+ values = np.asarray(time_values, dtype=np.uint64)
346
+ chunk = _fixed_time_chunk(template, time_var)
347
+ array_path = store_path / TIME_VARIABLE
348
+
349
+ if chunk is not None and start > 0 and array_path.is_dir():
350
+ array = zarr.open_array(array_path, mode="a", zarr_format=3)
351
+ if int(array.shape[0]) != n:
352
+ array.resize((n,))
353
+ array[start:n] = values[start:]
354
+ logger.info(
355
+ "Time coordinate: wrote slots %d:%d (chunk=%d), %d slot(s) untouched",
356
+ start,
357
+ n,
358
+ chunk,
359
+ start,
360
+ )
361
+ return
362
+
363
+ time_da = xr.DataArray(
364
+ values,
365
+ dims=[TIME_VARIABLE],
366
+ name=TIME_VARIABLE,
367
+ attrs=variable_attributes(TIME_VARIABLE, time_var, template),
368
+ )
369
+
370
+ # Through the same builder every other variable uses, so a codec declared on
371
+ # `time` is applied rather than silently dropped. A gridded axis is an
372
+ # arithmetic sequence, which the right codec compresses to almost nothing.
373
+ encoding = build_write_encoding(
374
+ template,
375
+ {TIME_VARIABLE: n},
376
+ variables={TIME_VARIABLE},
377
+ chunk_key_separator=chunk_key_separator,
378
+ )
379
+
380
+ group = zarr.open_group(store_path, mode="a", zarr_format=3, use_consolidated=False)
381
+ # to_zarr(mode="a") writes the dataset's attributes over the root group's, and
382
+ # this dataset has none. Carry the store's own across, or every global
383
+ # attribute -- Conventions, the prune watermark, the ACDD block -- is dropped.
384
+ root_attrs = dict(group.attrs)
385
+ if TIME_VARIABLE in group:
386
+ del group[TIME_VARIABLE]
387
+ xr.Dataset({TIME_VARIABLE: time_da}, attrs=root_attrs).to_zarr(
388
+ store_path,
389
+ mode="a",
390
+ zarr_format=3,
391
+ consolidated=False,
392
+ encoding=encoding,
393
+ )
394
+
395
+
396
+ def extend_store_time_axis(
397
+ store_path: Path,
398
+ template: TemplateSpec,
399
+ existing_times: np.ndarray,
400
+ future_times: np.ndarray,
401
+ dim_sizes: dict[str, int],
402
+ *,
403
+ chunk_key_separator: str = DEFAULT_CHUNK_KEY_SEPARATOR,
404
+ ) -> None:
405
+ """
406
+ Extend the store's time axis, append-only.
407
+
408
+ Parameters
409
+ ----------
410
+ store_path : pathlib.Path
411
+ The store directory.
412
+ template : TemplateSpec
413
+ The template describing the store.
414
+ existing_times : numpy.ndarray
415
+ The current time coordinate.
416
+ future_times : numpy.ndarray
417
+ The target time coordinate, as planned by
418
+ :func:`zarrchive.planning.plan_time_axis`.
419
+ dim_sizes : dict of str to int
420
+ Current length of each dimension; ``time`` is overridden here.
421
+ chunk_key_separator : {".", "/"}, optional
422
+ Chunk key separator, used if the time coordinate is (re)created.
423
+
424
+ Notes
425
+ -----
426
+ A no-op when the axis is already long enough. Data arrays are resized on disk
427
+ and their new slots stay implicit, so extending by one slot costs one metadata
428
+ update per array rather than a rewrite.
429
+
430
+ This is the expensive part of a write, which is why
431
+ :meth:`zarrchive.cam_store.Zarrchive.reserve_time` exists: doing it once
432
+ for N timestamps beats doing it N times.
433
+ """
434
+ if len(future_times) <= len(existing_times):
435
+ return
436
+
437
+ logger.info(
438
+ "Extending time axis: %d -> %d slot(s)",
439
+ len(existing_times),
440
+ len(future_times),
441
+ )
442
+
443
+ sizes = dict(dim_sizes)
444
+ sizes[TIME_VARIABLE] = len(future_times)
445
+ grow_store_arrays(store_path, template, sizes)
446
+
447
+ time_var = template.variables.get(TIME_VARIABLE)
448
+ if time_var is not None:
449
+ write_time_coordinate(
450
+ store_path,
451
+ template,
452
+ time_var,
453
+ future_times,
454
+ start=len(existing_times),
455
+ chunk_key_separator=chunk_key_separator,
456
+ )
457
+
458
+ clear_consolidated_metadata(store_path)