Parallel writes¶
Functions and data classes for writing a pyramid with many independent workers, for example as an HPC array job. The workflow is
init_pyramid_storecreates empty level stores and returns aPyramidManifestwith oneWriteTaskper unit of work,- every worker calls
write_pyramid_taskfor its task, check_pyramid_storereports whether all tasks finished.
The Parallel writes recipe explains the design, the manifest format and a complete reflow workflow.
Workflow steps¶
init_pyramid_store(pyramid, path, s3_options=None, *, zarr_format=2, encoding=None, write_coords='auto', materialise=None, structure='flat', split=None, variables_per_task=None, if_exists='error')
¶
init_pyramid_store(pyramid: dict[int, xr.Dataset], path: str, s3_options: S3Options | None = None, *, zarr_format: Literal[2, 3] = 2, encoding: PyramidEncoding | None = None, write_coords: bool | Literal['auto'] = 'auto', materialise: list[str] | None = None, structure: Literal['flat'] = 'flat', split: Mapping[str, int] | None = None, variables_per_task: int | None = None, if_exists: IfExists = 'error') -> PyramidManifest
init_pyramid_store(pyramid: dict[int, xr.Dataset], path: str, s3_options: S3Options | None = None, *, zarr_format: Literal[2, 3] = 2, encoding: PyramidEncoding | None = None, write_coords: bool | Literal['auto'] = 'auto', materialise: list[str] | None = None, structure: Literal['multiscales'], split: Mapping[str, int] | None = None, variables_per_task: int | None = None, if_exists: IfExists = 'error') -> None
Create empty pyramid stores and plan the work to fill them.
This is step one of a fan-out write. It writes, for every level,
"<path>/level_<level>.zarr" with all metadata, encodings and
coordinates, but none of the (lazy) data variables, and returns a
PyramidManifest that splits the
remaining work into independent
WriteTask units. Hand each task to one
worker, which calls
write_pyramid_task; afterwards
check_pyramid_store tells
whether everything was written. The manifest is also stored as
"<path>/_grid_doctor/manifest.json".
No data is computed (apart from coordinates and materialise), so the init is cheap even for stores with hundreds of thousands of chunks. The pyramid only needs the right shapes, dtypes, chunks and attributes; it can be built lazily from the full source.
What happens when path already holds a pyramid is controlled by if_exists; by default the init refuses, so a second run cannot destroy the stores of a first one by accident.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pyramid
|
dict[int, Dataset]
|
Mapping of HEALPix level to dataset, typically the lazy result
of |
required |
path
|
str
|
Target prefix. An |
required |
s3_options
|
S3Options | None
|
Options forwarded to :class: |
None
|
zarr_format
|
Literal[2, 3]
|
Zarr format version. |
2
|
encoding
|
PyramidEncoding | None
|
Per-level encoding dictionaries. Chunking always follows the dask chunks of the pyramid (first chunk along each dimension). |
None
|
write_coords
|
bool | Literal['auto']
|
Whether to materialise the |
'auto'
|
materialise
|
list[str] | None
|
Data variables to compute and write completely during the init, e.g. small static fields. They are not part of any task. |
None
|
structure
|
Literal['flat', 'multiscales']
|
|
'flat'
|
split
|
Mapping[str, int] | None
|
Task size per dimension in index units, e.g. |
None
|
variables_per_task
|
int | None
|
Maximum number of variables per task. |
None
|
if_exists
|
IfExists
|
What to do if path already has a manifest, level stores, or the remains of an interrupted init:
|
'error'
|
Returns:
| Type | Description |
|---|---|
PyramidManifest or None
|
Store layout and tasks. JSON-serialisable via
|
Examples:
pyramid = create_healpix_pyramid(ds, max_level=9)
manifest = init_pyramid_store(pyramid, "/scratch/out", split={"time": 24})
for task in manifest.tasks: # one array-job element each
write_pyramid_task(pyramid, task)
check_pyramid_store(manifest).raise_if_incomplete()
Source code in grid_doctor/io/_save.py
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 | |
write_pyramid_task(pyramid, task, s3_options=None)
¶
Write one task's region of pyramid into an initialised store.
This is the function an array-job element calls. It is safe to run any number of tasks of the same manifest concurrently, on any number of nodes, without locks: the planner guarantees that no two tasks share a zarr chunk (or shard). Re-running a task overwrites the same region with the same data, so retries are harmless.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pyramid
|
Mapping[int, Dataset]
|
Mapping of level to dataset, built the same way as for the init
step (same levels, variables, dimension lengths). It may cover
either the full extent of the split dimensions, in which case
the task region is selected here, or only the task region,
e.g. because the source was subset with
|
required |
task
|
WriteTask
|
The work unit, as taken from |
required |
s3_options
|
S3Options | None
|
Options for :class: |
None
|
Returns:
| Type | Description |
|---|---|
WriteTask
|
task itself, after the data and the completion marker have
been written. Returning the task (rather than nothing) makes
the result usable as a cache key: reflow can check a cached
result with |
Raises:
| Type | Description |
|---|---|
StaleTaskError
|
The store was re-initialised after task was planned. |
ManifestError
|
task is not identical to the task of the same id in the stored manifest (only tasks the manifest validated are written), or pyramid does not match the manifest (missing level or variable, different dimension lengths, a region the data cannot cover), or its coordinate values in the task region differ from the ones the init stored (e.g. another time range of the same length). |
Source code in grid_doctor/io/_fanout.py
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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 | |
check_pyramid_store(manifest, s3_options=None, *, inspect_chunks=False)
¶
Check whether a store is complete according to its manifest.
The check is cheap: it reads the level metadata and lists one small marker file per finished task. It does not read any data.
A store is complete when
- the stored manifest is the one being checked (the store was not re-initialised in between),
- every level store and every array exists with the shape, write unit and dtype recorded in the manifest, and
- every task has written its completion marker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manifest
|
PyramidManifest | str
|
The manifest returned by
|
required |
s3_options
|
S3Options | None
|
Options for :class: |
None
|
inspect_chunks
|
bool
|
Also list the stored chunk keys and report, per finished task,
how many chunks of its region are absent. This lists every
object of every array and can be slow on large S3 stores. It
never makes a store incomplete; see
|
False
|
Returns:
| Type | Description |
|---|---|
StoreReport
|
Use |
Source code in grid_doctor/io/_fanout.py
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 | |
Manifest and tasks¶
These classes are frozen dataclasses that round-trip through JSON and through reflow's manifest codec.
PyramidManifest(manifest_id, path, zarr_format, created, grid_doctor_version, split, levels, tasks, materialised=(), schema_version=MANIFEST_SCHEMA_VERSION)
dataclass
¶
Layout of an initialised pyramid and the work needed to fill it.
Returned by
init_pyramid_store and
stored as <path>/_grid_doctor/manifest.json.
Attributes:
| Name | Type | Description |
|---|---|---|
manifest_id |
str
|
Random id generated at init. Every task and every completion marker carries it. |
path |
str
|
Pyramid root. |
zarr_format |
Literal[2, 3]
|
Zarr format of all level stores. |
created |
str
|
ISO 8601 UTC timestamp of the init. |
grid_doctor_version |
str
|
Version of grid-doctor that wrote the manifest. |
split |
tuple[tuple[str, int], ...]
|
Effective task size per split dimension, in index units, after rounding up to whole write units. Empty when nothing was split. |
levels |
tuple[LevelSpec, ...]
|
One |
tasks |
tuple[WriteTask, ...]
|
All work units. Together they cover every data variable on every level exactly once. |
materialised |
tuple[str, ...]
|
Data variables written completely by the init step. |
schema_version |
int
|
Manifest layout version, see :data: |
__post_init__()
¶
Validate the fields and the consistency of levels and tasks.
Besides field types this enforces what parallel writes depend on, for every data variable on every level:
- every task region lies inside the array and starts and ends on write-unit boundaries (or the array end),
- the tasks writing it partition it exactly: no gaps, no overlaps, no duplicates,
- every data variable is written by at least one task.
Source code in grid_doctor/io/_manifest.py
level(level)
¶
task(task_id)
¶
select_tasks(task_ids)
¶
Return the tasks with the given ids, in manifest order.
Handy for re-submitting only what
check_pyramid_store reported
as missing::
retry = manifest.select_tasks(report.missing_tasks)
Source code in grid_doctor/io/_manifest.py
to_dict()
¶
JSON-compatible representation.
Tasks are written without the fields they share with the
manifest (manifest_id, path, zarr_format).
Source code in grid_doctor/io/_manifest.py
from_dict(data)
classmethod
¶
Inverse of to_dict.
The schema version is checked first, so a manifest from an incompatible grid-doctor fails with a clear message rather than with a missing field.
Source code in grid_doctor/io/_manifest.py
to_json(*, indent=2)
¶
WriteTask(task_id, manifest_id, path, zarr_format, variables, region, levels)
dataclass
¶
One self-contained unit of work for a single worker.
A task carries everything a worker needs besides the data itself and
the storage credentials: where the store lives, which variables to
write on which levels, and the index region along the split
dimensions. Dimensions not listed in region are written in full.
Attributes:
| Name | Type | Description |
|---|---|---|
task_id |
str
|
Identifier, unique within the manifest ( |
manifest_id |
str
|
Id of the manifest this task belongs to. Workers refuse to run a task whose id does not match the manifest stored in the target, which protects a re-initialised store from stale array jobs. |
path |
str
|
Pyramid root, as passed to |
zarr_format |
Literal[2, 3]
|
Zarr format of the level stores. |
variables |
tuple[str, ...]
|
Data variables to write. |
region |
Region
|
|
levels |
tuple[int, ...]
|
Levels the task writes, finest first. |
slices
property
¶
The region as an isel-ready mapping, e.g. {"time": slice(0, 24)}.
__post_init__()
¶
Validate and normalise the fields (lists become tuples).
A task on its own can only be checked for well-formed fields.
Whether its region is chunk-aligned is checked by the manifest
that contains it, and by
write_pyramid_task, which
refuses tasks that differ from the stored manifest.
Source code in grid_doctor/io/_manifest.py
isel()
¶
Return the region as a mapping for Dataset.isel.
Same as slices; use it as
ds.isel(task.isel()).
to_dict()
¶
JSON-compatible representation with all fields.
Source code in grid_doctor/io/_manifest.py
to_entry()
¶
JSON form inside a manifest, without the fields it shares with it.
Source code in grid_doctor/io/_manifest.py
from_dict(data, *, defaults=None, where='task')
classmethod
¶
Inverse of to_dict.
defaults supplies manifest_id, path and zarr_format
when they are absent, as inside a manifest file. where names
the location in error messages.
Source code in grid_doctor/io/_manifest.py
to_json(*, indent=None)
¶
from_json(text)
classmethod
¶
LevelSpec(level, store, coords, data_vars)
dataclass
¶
Layout of one level store (<path>/level_<n>.zarr).
Attributes:
| Name | Type | Description |
|---|---|---|
level |
int
|
HEALPix refinement level. |
store |
str
|
Store name relative to the pyramid root, e.g. |
coords |
tuple[str, ...]
|
Coordinate (and other non-task) arrays written completely by the init step. Workers never touch them. |
data_vars |
tuple[ArraySpec, ...]
|
Data variables that are written by tasks. Variables listed in
|
__post_init__()
¶
Validate and normalise the fields (lists become tuples).
Source code in grid_doctor/io/_manifest.py
array(name)
¶
Return the spec of data variable name.
to_dict()
¶
JSON-compatible representation.
from_dict(data, *, where='level')
classmethod
¶
Inverse of to_dict.
where names the location in error messages.
Source code in grid_doctor/io/_manifest.py
ArraySpec(name, dims, shape, chunks, dtype)
dataclass
¶
Layout of one data variable in one level store.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Variable name. |
dims |
tuple[str, ...]
|
Dimension names, in storage order. |
shape |
tuple[int, ...]
|
Full array shape. |
chunks |
tuple[int, ...]
|
Size of the smallest independently writable unit along every dimension: the shard shape for sharded zarr v3 arrays, the chunk shape otherwise. Task regions start on multiples of these. |
dtype |
str
|
On-disk dtype (after CF encoding, e.g. |
__post_init__()
¶
Validate and normalise the fields (lists become tuples).
Source code in grid_doctor/io/_manifest.py
size(dim)
¶
chunk(dim)
¶
to_dict()
¶
JSON-compatible representation.
from_dict(data, *, where='array')
classmethod
¶
Inverse of to_dict.
where names the location in error messages.
Source code in grid_doctor/io/_manifest.py
Completeness report¶
StoreReport(manifest_id, n_tasks, done_tasks, missing_tasks, problems=(), stale_markers=0, absent_chunks=())
dataclass
¶
Result of check_pyramid_store.
Attributes:
| Name | Type | Description |
|---|---|---|
manifest_id |
str
|
Manifest the store was checked against. |
n_tasks |
int
|
Number of tasks in the manifest. |
done_tasks |
tuple[str, ...]
|
Ids of tasks with a valid completion marker. |
missing_tasks |
tuple[str, ...]
|
Ids of tasks without one. Feed them to
|
problems |
tuple[str, ...]
|
Structural mismatches between store and manifest (missing level store or array, changed shape, chunking or dtype, a store that was re-initialised with a different manifest). |
stale_markers |
int
|
Markers that belong to another manifest or name unknown tasks. They are ignored. |
absent_chunks |
tuple[tuple[str, int, int], ...]
|
Only with |
complete
property
¶
True if every task finished and the layout matches.
__bool__()
¶
summary()
¶
One human-readable paragraph.
Source code in grid_doctor/io/_fanout.py
raise_if_incomplete()
¶
Store state helpers¶
These read the manifest and the completion markers below
<path>/_grid_doctor/. The two predicates are cheap enough to serve
as cache checks, e.g. reflow's verify= hook.
load_manifest(path, s3_options=None)
¶
Read the manifest that the init step stored below path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Pyramid root, as passed to |
required |
s3_options
|
S3Options | None
|
Options for :class: |
None
|
Raises:
| Type | Description |
|---|---|
ManifestError
|
If no manifest exists, e.g. because the init step has not finished or the store was not initialised with a manifest. |
Source code in grid_doctor/io/_fanout.py
is_current(item, s3_options=None)
¶
Whether the store at item.path still holds item's manifest.
False if the store was deleted, never finished its init, or was
re-initialised since item was created. Meant as a cache check, for
example reflow's verify= hook on the init step: a cached manifest
is only reusable while the store it describes still exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
PyramidManifest | WriteTask
|
A manifest or any of its tasks. |
required |
s3_options
|
S3Options | None
|
Options for :class: |
None
|
Source code in grid_doctor/io/_fanout.py
is_task_done(task, s3_options=None)
¶
Whether task has a completion marker for the current manifest.
Equivalent to task.task_id in check_pyramid_store(...).done_tasks
but reads a single small file, so it is cheap enough to call per
task, e.g. as reflow's verify= hook on the array job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
WriteTask
|
The work unit. |
required |
s3_options
|
S3Options | None
|
Options for :class: |
None
|
Source code in grid_doctor/io/_fanout.py
JSON layout¶
The to_dict() methods return these typed dictionaries, so the layout
of manifest.json and of a serialised task is spelled out in the types.
ManifestDict
¶
TaskEntryDict
¶
Bases: TypedDict
JSON form of a task inside a manifest (shared fields omitted).
Exceptions¶
ManifestError
¶
Bases: ValueError
The manifest cannot be built, read, or does not match the store.
StaleTaskError
¶
Bases: ManifestError
The task belongs to a different manifest than the one in the store.
StoreExistsError
¶
Bases: ManifestError
The init target already holds a pyramid (or the remains of one).
Raised by init_pyramid_store(if_exists="error"), and by
if_exists="resume" when there is nothing it could resume.
IncompleteStoreError
¶
Bases: RuntimeError
Raised by StoreReport.raise_if_incomplete.