Skip to content

Parallel writes

Functions and data classes for writing a pyramid with many independent workers, for example as an HPC array job. The workflow is

  1. init_pyramid_store creates empty level stores and returns a PyramidManifest with one WriteTask per unit of work,
  2. every worker calls write_pyramid_task for its task,
  3. check_pyramid_store reports 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 create_healpix_pyramid.

required
path str

Target prefix. An "s3://bucket/pyramid" URL writes to S3; any other value is treated as a local directory path.

required
s3_options S3Options | None

Options forwarded to :class:s3fs.S3FileSystem. Only used for S3 targets; ignored (and optional) for local paths. Never stored in the manifest.

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 cell/latitude/longitude coordinate arrays in the store. HEALPix coordinates are a pure function of the cell index, and above roughly level 10 the arrays dwarf regional payloads (hundreds of GB at level 16, and they are never fill values, so chunk elision cannot help). "auto" (default) writes coordinates for levels up to :data:WRITE_COORDS_MAX_LEVEL and omits them above; True / False force either behaviour for all levels. Coordinate- less stores keep the crs grid mapping, are marked as having implicit coordinates (see HealpixMetadata), and are meant to be accessed through the region selectors (select_bbox, select_cells), which reconstruct coordinates for exactly the cells they return.

'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" (default) writes one store per level, "<path>/level_<level>.zarr", and plans the fan-out tasks. "multiscales" writes the template of a single datatree store at path (one group per level) and returns None: fan-out tasks are not supported for it yet, so split, variables_per_task and if_exists="resume" are rejected, and an existing store at path is overwritten. Fill it with save_pyramid and structure="multiscales".

'flat'
split Mapping[str, int] | None

Task size per dimension in index units, e.g. {"time": 24} for tasks of 24 time steps. Sizes are rounded up to a multiple of the zarr chunk (or shard) size along that dimension, taken over all variables and levels, so no two tasks ever write to the same chunk. Several dimensions give the cartesian product of their regions. Splitting along cell is not supported. None (default) plans one task per group of variables, covering the whole store.

None
variables_per_task int | None

Maximum number of variables per task. None (default) keeps all variables that share split dimensions and levels in one task, so the regridding they share is computed once per region.

None
if_exists IfExists

What to do if path already has a manifest, level stores, or the remains of an interrupted init:

  • "error" (default): raise StoreExistsError.
  • "resume": if the stored manifest was planned exactly as this call would plan it (same path, levels, array layouts, split and tasks), return it unchanged, with its manifest_id, and write nothing. Tasks that already finished keep their markers, so re-submitting a conversion after a time-out only redoes the missing tasks. Raises StoreExistsError listing the differences otherwise, or if there is no readable manifest to resume (e.g. the previous init was killed). Without anything at path it initialises normally.
  • "overwrite": re-initialise. All data is discarded, the result gets a new manifest_id, and tasks and markers of the previous manifest become invalid; workers still running for it fail with StaleTaskError. Only overwrite when no worker of a previous run may still be writing: grid-doctor does not lock the store, and a worker that is already writing can put its data into the new stores before it notices.
'error'

Returns:

Type Description
PyramidManifest or None

Store layout and tasks. JSON-serialisable via manifest.to_json() and accepted directly as a reflow task result. None for structure="multiscales".

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
def 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", "multiscales"] = "flat",
    split: Mapping[str, int] | None = None,
    variables_per_task: int | None = None,
    if_exists: IfExists = "error",
) -> PyramidManifest | 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`][grid_doctor.PyramidManifest] that splits the
    remaining work into independent
    [`WriteTask`][grid_doctor.WriteTask] units.  Hand each task to one
    worker, which calls
    [`write_pyramid_task`][grid_doctor.write_pyramid_task]; afterwards
    [`check_pyramid_store`][grid_doctor.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
    ----------
    pyramid:
        Mapping of HEALPix level to dataset, typically the lazy result
        of [`create_healpix_pyramid`][grid_doctor.create_healpix_pyramid].
    path:
        Target prefix.  An ``"s3://bucket/pyramid"`` URL writes to S3; any
        other value is treated as a local directory path.
    s3_options:
        Options forwarded to :class:`s3fs.S3FileSystem`.  Only used for S3
        targets; ignored (and optional) for local paths.  Never stored in
        the manifest.
    zarr_format:
        Zarr format version.
    encoding:
        Per-level encoding dictionaries.  Chunking always follows the
        dask chunks of the pyramid (first chunk along each dimension).
    write_coords:
        Whether to materialise the ``cell``/``latitude``/``longitude``
        coordinate arrays in the store.  HEALPix coordinates are a pure
        function of the cell index, and above roughly level 10 the
        arrays dwarf regional payloads (hundreds of GB at level 16, and
        they are never fill values, so chunk elision cannot help).
        ``"auto"`` (default) writes coordinates for levels up to
        :data:`WRITE_COORDS_MAX_LEVEL` and omits them above; ``True`` /
        ``False`` force either behaviour for all levels.  Coordinate-
        less stores keep the ``crs`` grid mapping, are marked as having
        implicit coordinates (see
        [`HealpixMetadata`][grid_doctor.metadata.HealpixMetadata]), and are
        meant to be accessed through the region selectors
        ([`select_bbox`][grid_doctor.select_bbox],
        [`select_cells`][grid_doctor.select_cells]), which reconstruct
        coordinates for exactly the cells they return.
    materialise:
        Data variables to compute and write completely during the init,
        e.g. small static fields.  They are not part of any task.
    structure:
        ``"flat"`` (default) writes one store per level,
        ``"<path>/level_<level>.zarr"``, and plans the fan-out tasks.
        ``"multiscales"`` writes the template of a single datatree store
        at *path* (one group per level) and returns ``None``: fan-out
        tasks are not supported for it yet, so *split*,
        *variables_per_task* and ``if_exists="resume"`` are rejected, and
        an existing store at *path* is overwritten.  Fill it with
        [`save_pyramid`][grid_doctor.save_pyramid] and
        ``structure="multiscales"``.
    split:
        Task size per dimension in index units, e.g. ``{"time": 24}``
        for tasks of 24 time steps.  Sizes are rounded **up** to a
        multiple of the zarr chunk (or shard) size along that dimension,
        taken over all variables and levels, so no two tasks ever write
        to the same chunk.  Several dimensions give the cartesian
        product of their regions.  Splitting along ``cell`` is not
        supported.  ``None`` (default) plans one task per group of
        variables, covering the whole store.
    variables_per_task:
        Maximum number of variables per task.  ``None`` (default) keeps
        all variables that share split dimensions and levels in one
        task, so the regridding they share is computed once per region.
    if_exists:
        What to do if *path* already has a manifest, level stores, or the
        remains of an interrupted init:

        - ``"error"`` (default): raise
          [`StoreExistsError`][grid_doctor.io.StoreExistsError].
        - ``"resume"``: if the stored manifest was planned exactly as
          this call would plan it (same path, levels, array layouts,
          split and tasks), return it unchanged, with its
          ``manifest_id``, and write nothing.  Tasks that already
          finished keep their markers, so re-submitting a conversion
          after a time-out only redoes the missing tasks.  Raises
          [`StoreExistsError`][grid_doctor.io.StoreExistsError] listing
          the differences otherwise, or if there is no readable
          manifest to resume (e.g. the previous init was killed).
          Without anything at *path* it initialises normally.
        - ``"overwrite"``: re-initialise.  All data is discarded, the
          result gets a new ``manifest_id``, and tasks and markers of the
          previous manifest become invalid; workers still running for
          it fail with ``StaleTaskError``.  Only overwrite when no
          worker of a previous run may still be writing: grid-doctor
          does not lock the store, and a worker that is already writing
          can put its data into the new stores before it notices.

    Returns
    -------
    PyramidManifest or None
        Store layout and tasks.  JSON-serialisable via
        ``manifest.to_json()`` and accepted directly as a reflow task
        result.  ``None`` for ``structure="multiscales"``.

    Examples
    --------
    ```python
    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()
    ```
    """
    if if_exists not in ("error", "resume", "overwrite"):
        raise ValueError(f"if_exists must be 'error', 'resume' or 'overwrite', got {if_exists!r}")
    if structure not in ("flat", "multiscales"):
        raise ValueError(f"structure must be 'flat' or 'multiscales', got {structure!r}")
    materialise = list(materialise or [])
    if structure == "multiscales":
        unsupported = [
            name
            for name, given in (
                ("split", split is not None),
                ("variables_per_task", variables_per_task is not None),
                ("if_exists='resume'", if_exists == "resume"),
            )
            if given
        ]
        if unsupported:
            raise NotImplementedError(
                f"{', '.join(unsupported)} not supported for "
                "structure='multiscales' yet; use structure='flat' for fan-out "
                "writes"
            )
        _init_multiscales(
            pyramid,
            path,
            s3_options,
            zarr_format=zarr_format,
            encoding=encoding,
            write_coords=write_coords,
            materialise=materialise,
        )
        return None

    # Workers rebuild store paths from the manifest; keep them identical.
    path = path.rstrip("/")
    existing = inspect_target(path, s3_options, [f"level_{level}.zarr" for level in pyramid])
    if existing.exists and if_exists == "error":
        raise StoreExistsError(
            f"{path} already holds a pyramid ({existing.describe()}).  Pass "
            "if_exists='resume' to continue it or if_exists='overwrite' to "
            "start over."
        )
    if existing.exists and if_exists == "resume":
        if existing.manifest is None:
            raise StoreExistsError(
                f"cannot resume {path}: there is no readable manifest "
                f"({existing.describe()}).  Use if_exists='overwrite'."
            )
        templates = {
            level: maybe_drop_coordinates(ds, level, write_coords, WRITE_COORDS_MAX_LEVEL)
            for level, ds in pyramid.items()
        }
        return resume_init(
            existing.manifest,
            path,
            templates,
            {level: [str(k) for k in ds.data_vars if str(k) not in materialise] for level, ds in templates.items()},
            s3_options,
            zarr_format=zarr_format,
            split=split,
            variables_per_task=variables_per_task,
            materialised=[m for m in materialise if m in {str(v) for ds in pyramid.values() for v in ds}],
        )
    fs = get_filesystem(path, s3_options)
    begin_init(path, s3_options)
    level_specs: dict[int, LevelSpec] = {}
    for level, dataset in pyramid.items():
        template, combined_encoding = prepare_template(
            dataset,
            level,
            write_coords=write_coords,
            max_level_to_auto_write_coords=WRITE_COORDS_MAX_LEVEL,
            encoding=encoding,
            materialise=materialise,
        )
        task_vars = [str(k) for k in template.data_vars if str(k) not in materialise]
        store_name = f"level_{level}.zarr"
        root_path = f"{path}/{store_name}"
        store = get_store(root_path, fs)
        logger.info("Writing HEALPix to %s", root_path)
        zarr_options = get_zarr_options("w", zarr_format, combined_encoding)
        template.to_zarr(store, **zarr_options)  # type: ignore[call-overload]
        level_specs[level] = describe_level(
            level,
            store_name,
            store,
            template,
            task_vars,
            zarr_format=zarr_format,
        )

    unknown = sorted(set(materialise) - {str(v) for ds in pyramid.values() for v in ds})
    if unknown:
        logger.warning("materialise names unknown variables: %s", ", ".join(unknown))
    return finish_init(
        path,
        s3_options,
        [level_specs[lvl] for lvl in sorted(level_specs, reverse=True)],
        zarr_format=zarr_format,
        split=split,
        variables_per_task=variables_per_task,
        materialised=[m for m in materialise if m not in unknown],
    )

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 source.isel(task.isel()) before regridding. The second form is usually much cheaper, since only the task's slice of the source is read and regridded. Datasets may contain more variables or levels than the task needs; they are ignored.

required
task WriteTask

The work unit, as taken from manifest.tasks.

required
s3_options S3Options | None

Options for :class:s3fs.S3FileSystem. Credentials are never stored in the manifest, so every worker passes its own.

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 verify=is_task_done.

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
def write_pyramid_task(
    pyramid: Mapping[int, xr.Dataset],
    task: WriteTask,
    s3_options: S3Options | None = None,
) -> WriteTask:
    """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
    ----------
    pyramid:
        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
        ``source.isel(task.isel())`` before regridding.  The second form
        is usually much cheaper, since only the task's slice of the
        source is read and regridded.  Datasets may contain more
        variables or levels than the task needs; they are ignored.
    task:
        The work unit, as taken from ``manifest.tasks``.
    s3_options:
        Options for :class:`s3fs.S3FileSystem`.  Credentials are never
        stored in the manifest, so every worker passes its own.

    Returns
    -------
    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 ``verify=is_task_done``.

    Raises
    ------
    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).
    """
    started = time.monotonic()
    target = _Target(task.path, s3_options)
    manifest = load_manifest(task.path, s3_options)
    if manifest.manifest_id != task.manifest_id:
        raise StaleTaskError(
            f"{task.task_id} belongs to manifest {task.manifest_id}, but "
            f"{task.path} was re-initialised with manifest "
            f"{manifest.manifest_id}; plan the tasks again from the new manifest"
        )
    try:
        planned = manifest.task(task.task_id)
    except KeyError:
        raise ManifestError(f"{task.task_id} is not part of manifest {manifest.manifest_id}") from None
    if planned != task:
        # The manifest validated that its own tasks are chunk-aligned and
        # disjoint; a task that differs (edited or hand-built) has no such
        # guarantee and could race with another worker.
        raise ManifestError(
            f"{task.task_id} differs from the task stored in the manifest "
            f"({task} != {planned}); use the tasks of the stored manifest"
        )

    writes: list[DeferredWrite] = []
    for level in task.levels:
        if level not in pyramid:
            raise ManifestError(
                f"{task.task_id} writes level {level}, but the pyramid only has levels {sorted(pyramid)}"
            )
        spec = manifest.level(level)
        store = target.store(spec.store)
        group = zarr.open_group(store, mode="r+", zarr_format=task.zarr_format)
        encodings = stored_encodings(store, zarr_format=task.zarr_format)
        for name in task.variables:
            array_spec = spec.array(name)
            if name not in pyramid[level]:
                raise ManifestError(f"{task.task_id}: variable {name!r} missing on level {level}")
            var = _select_region(pyramid[level][name].variable, array_spec, task)
            var = var.copy(deep=False)
            var.encoding = encodings.get(name, {})
            encoded = encode_zarr_variable(var, name=name, zarr_format=task.zarr_format)
            offsets = _region_offsets(array_spec, task)
            source = _aligned(encoded.data, array_spec.chunks, offsets, name)
            region = tuple(slice(off, off + n) for off, n in zip(offsets, encoded.shape))
            writes.append(DeferredWrite(source, get_array(group, name), region))

        mismatches = coordinate_differences(
            pyramid[level],
            store,
            spec.coords,
            zarr_format=task.zarr_format,
            region={dim: (start, stop) for dim, start, stop in task.region},
        )
        if mismatches:
            raise ManifestError(
                f"{task.task_id}: the pyramid does not match the coordinates "
                f"stored by the init on level {level} ("
                + "; ".join(mismatches)
                + ").  It was built from other data than the store; nothing "
                "was written."
            )

    store_all(writes)
    # The manifest was checked before writing.  If the store was
    # re-initialised meanwhile (an overwrite while this task ran), the
    # data above may have landed in the new stores: fail loudly instead
    # of reporting success, and never write a marker for it.
    if not is_current(task, s3_options):
        raise StaleTaskError(
            f"{task.path} was re-initialised while {task.task_id} was writing; "
            "its data may have been written into the new stores.  Do not "
            "re-initialise a store while a conversion into it is running."
        )
    marker = {
        "manifest_id": task.manifest_id,
        "task_id": task.task_id,
        "finished": datetime.now(UTC).isoformat(timespec="seconds"),
        "elapsed_s": round(time.monotonic() - started, 3),
        "host": socket.gethostname(),
        "variables": list(task.variables),
        "levels": list(task.levels),
        "region": {d: [a, b] for d, a, b in task.region},
    }
    target.write_text(json.dumps(marker, indent=2), STATE_DIR, DONE_DIR, f"{task.task_id}.json")
    logger.info(
        "%s done (%s, %d level(s)) in %.1fs",
        task.task_id,
        ", ".join(task.variables),
        len(task.levels),
        marker["elapsed_s"],
    )
    return task

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

  1. the stored manifest is the one being checked (the store was not re-initialised in between),
  2. every level store and every array exists with the shape, write unit and dtype recorded in the manifest, and
  3. every task has written its completion marker.

Parameters:

Name Type Description Default
manifest PyramidManifest | str

The manifest returned by init_pyramid_store, or the pyramid root path, in which case the stored manifest is loaded.

required
s3_options S3Options | None

Options for :class:s3fs.S3FileSystem (S3 targets only).

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 StoreReport.absent_chunks.

False

Returns:

Type Description
StoreReport

Use report.complete (or bool(report)), report.missing_tasks and report.summary(); call report.raise_if_incomplete() to fail a workflow step.

Source code in grid_doctor/io/_fanout.py
def check_pyramid_store(
    manifest: PyramidManifest | str,
    s3_options: S3Options | None = None,
    *,
    inspect_chunks: bool = False,
) -> StoreReport:
    """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

    1. the stored manifest is the one being checked (the store was not
       re-initialised in between),
    2. every level store and every array exists with the shape, write
       unit and dtype recorded in the manifest, and
    3. every task has written its completion marker.

    Parameters
    ----------
    manifest:
        The manifest returned by
        [`init_pyramid_store`][grid_doctor.init_pyramid_store],
        or the pyramid root path, in which case the stored manifest is
        loaded.
    s3_options:
        Options for :class:`s3fs.S3FileSystem` (S3 targets only).
    inspect_chunks:
        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
        [`StoreReport.absent_chunks`][grid_doctor.StoreReport].

    Returns
    -------
    StoreReport
        Use ``report.complete`` (or ``bool(report)``),
        ``report.missing_tasks`` and ``report.summary()``; call
        ``report.raise_if_incomplete()`` to fail a workflow step.
    """
    if isinstance(manifest, str):
        manifest = load_manifest(manifest, s3_options)
    target = _Target(manifest.path, s3_options)
    problems: list[str] = []

    stored_text = target.read_text(STATE_DIR, MANIFEST_FILE)
    if stored_text is None:
        interrupted = _interrupted_init(target)
        problems.append(
            f"no manifest stored at {manifest.path}/{STATE_DIR}" + (f": {interrupted}" if interrupted else "")
        )
    else:
        stored_id = json.loads(stored_text).get("manifest_id")
        if stored_id != manifest.manifest_id:
            problems.append(f"store was re-initialised: it holds manifest {stored_id}, not {manifest.manifest_id}")

    groups: dict[int, zarr.Group] = {}
    for spec in manifest.levels:
        try:
            group = zarr.open_group(target.store(spec.store), mode="r", zarr_format=manifest.zarr_format)
        except Exception as error:  # noqa: BLE001 - report, do not raise
            problems.append(f"level {spec.level}: cannot open {spec.store}: {error}")
            continue
        groups[spec.level] = group
        members = set(group.array_keys())
        for name in spec.coords:
            if name not in members:
                problems.append(f"level {spec.level}: coordinate {name!r} missing")
        for array_spec in spec.data_vars:
            problems.extend(_check_array(spec.level, group, members, array_spec))

    known = {t.task_id for t in manifest.tasks}
    done: set[str] = set()
    stale = 0
    for filename in target.list_dir(STATE_DIR, DONE_DIR):
        if not filename.endswith(".json") or filename.startswith("."):
            continue
        text = target.read_text(STATE_DIR, DONE_DIR, filename)
        try:
            marker = json.loads(text or "")
        except json.JSONDecodeError:
            stale += 1
            continue
        task_id = marker.get("task_id")
        if marker.get("manifest_id") == manifest.manifest_id and task_id in known:
            done.add(str(task_id))
        else:
            stale += 1

    order = [t.task_id for t in manifest.tasks]
    done_tasks = tuple(t for t in order if t in done)
    missing = tuple(t for t in order if t not in done)

    absent: list[tuple[str, int, int]] = []
    if inspect_chunks:
        absent = _absent_chunks(manifest, target, groups, [manifest.task(t) for t in done_tasks])

    return StoreReport(
        manifest_id=manifest.manifest_id,
        n_tasks=len(manifest.tasks),
        done_tasks=done_tasks,
        missing_tasks=missing,
        problems=tuple(problems),
        stale_markers=stale,
        absent_chunks=tuple(absent),
    )

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 LevelSpec per level, finest first.

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:MANIFEST_SCHEMA_VERSION.

__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
def __post_init__(self) -> None:
    """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.
    """
    where = "manifest"
    _check_schema_version(self.schema_version)
    levels = _instances(_as_tuple(self.levels, where, "levels"), LevelSpec, where, "levels")
    tasks = _instances(_as_tuple(self.tasks, where, "tasks"), WriteTask, where, "tasks")
    _set(
        self,
        manifest_id=_as_str(self.manifest_id, where, "manifest_id", safe=True),
        path=_as_str(self.path, where, "path"),
        zarr_format=_zarr_format(self.zarr_format, where),
        created=_as_str(self.created, where, "created"),
        grid_doctor_version=_as_str(self.grid_doctor_version, where, "grid_doctor_version"),
        split=_split(self.split, where),
        levels=levels,
        tasks=tasks,
        materialised=_str_tuple(self.materialised, where, "materialised", unique=True),
    )
    _check_consistency(self)

level(level)

Return the spec of level.

Source code in grid_doctor/io/_manifest.py
def level(self, level: int) -> LevelSpec:
    """Return the spec of *level*."""
    for spec in self.levels:
        if spec.level == level:
            return spec
    raise KeyError(f"manifest has no level {level}")

task(task_id)

Return the task with id task_id.

Source code in grid_doctor/io/_manifest.py
def task(self, task_id: str) -> WriteTask:
    """Return the task with id *task_id*."""
    for task in self.tasks:
        if task.task_id == task_id:
            return task
    raise KeyError(f"manifest has no task {task_id!r}")

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
def select_tasks(self, task_ids: Iterable[str]) -> list[WriteTask]:
    """Return the tasks with the given ids, in manifest order.

    Handy for re-submitting only what
    [`check_pyramid_store`][grid_doctor.check_pyramid_store] reported
    as missing::

        retry = manifest.select_tasks(report.missing_tasks)
    """
    wanted = set(task_ids)
    unknown = wanted - {t.task_id for t in self.tasks}
    if unknown:
        raise KeyError(f"unknown task ids: {sorted(unknown)}")
    return [t for t in self.tasks if t.task_id in wanted]

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
def to_dict(self) -> ManifestDict:
    """JSON-compatible representation.

    Tasks are written without the fields they share with the
    manifest (``manifest_id``, ``path``, ``zarr_format``).
    """
    return {
        "schema_version": self.schema_version,
        "manifest_id": self.manifest_id,
        "path": self.path,
        "zarr_format": self.zarr_format,
        "created": self.created,
        "grid_doctor_version": self.grid_doctor_version,
        "split": dict(self.split),
        "materialised": list(self.materialised),
        "levels": [spec.to_dict() for spec in self.levels],
        "tasks": [task.to_entry() for task in self.tasks],
    }

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
@classmethod
def from_dict(cls, data: Mapping[str, object]) -> PyramidManifest:
    """Inverse of [`to_dict`][grid_doctor.PyramidManifest.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.
    """
    where = "manifest"
    fields = _mapping(data, where)
    _check_schema_version(fields.get("schema_version"))
    defaults = {key: _field(fields, key, where) for key in ("manifest_id", "path", "zarr_format")}
    raw_split = _field(fields, "split", where)
    if not isinstance(raw_split, Mapping):
        _fail(where, f"split must be an object, got {type(raw_split).__name__}")
    raw_levels = _as_tuple(_field(fields, "levels", where), where, "levels")
    raw_tasks = _as_tuple(_field(fields, "tasks", where), where, "tasks")
    return cls(
        manifest_id=_as_str(defaults["manifest_id"], where, "manifest_id", safe=True),
        path=_as_str(defaults["path"], where, "path"),
        zarr_format=_zarr_format(defaults["zarr_format"], where),
        created=_as_str(_field(fields, "created", where), where, "created"),
        grid_doctor_version=_as_str(
            _field(fields, "grid_doctor_version", where),
            where,
            "grid_doctor_version",
        ),
        split=_split(tuple(raw_split.items()), where),
        materialised=_str_tuple(fields.get("materialised", ()), where, "materialised"),
        levels=tuple(
            LevelSpec.from_dict(_mapping(lvl, f"levels[{i}]"), where=f"levels[{i}]")
            for i, lvl in enumerate(raw_levels)
        ),
        tasks=tuple(
            WriteTask.from_dict(
                _mapping(task, f"tasks[{i}]"),
                defaults=defaults,
                where=f"tasks[{i}]",
            )
            for i, task in enumerate(raw_tasks)
        ),
        schema_version=MANIFEST_SCHEMA_VERSION,
    )

to_json(*, indent=2)

Serialise to a JSON string.

Source code in grid_doctor/io/_manifest.py
def to_json(self, *, indent: int | None = 2) -> str:
    """Serialise to a JSON string."""
    return json.dumps(self.to_dict(), indent=indent, sort_keys=False)

from_json(text) classmethod

Parse a manifest written by to_json.

Source code in grid_doctor/io/_manifest.py
@classmethod
def from_json(cls, text: str | bytes) -> PyramidManifest:
    """Parse a manifest written by [`to_json`][grid_doctor.PyramidManifest.to_json]."""
    return cls.from_dict(_mapping(_loads(text, "manifest"), "manifest"))

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 ("task-000042").

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 init_pyramid_store.

zarr_format Literal[2, 3]

Zarr format of the level stores.

variables tuple[str, ...]

Data variables to write.

region Region

((dim, start, stop), ...). Empty for variables that have none of the split dimensions (e.g. a static land-sea mask).

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
def __post_init__(self) -> None:
    """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`][grid_doctor.write_pyramid_task], which
    refuses tasks that differ from the stored manifest.
    """
    where = f"task {self.task_id!r}"
    _set(
        self,
        task_id=_as_str(self.task_id, where, "task_id", safe=True),
        manifest_id=_as_str(self.manifest_id, where, "manifest_id", safe=True),
        path=_as_str(self.path, where, "path"),
        zarr_format=_zarr_format(self.zarr_format, where),
        variables=_str_tuple(self.variables, where, "variables", unique=True, nonempty=True),
        region=_region(self.region, where),
        levels=_int_tuple(self.levels, where, "levels", minimum=0, unique=True, nonempty=True),
    )
    for name in self.variables:
        _name(name, where, "variables")

isel()

Return the region as a mapping for Dataset.isel.

Same as slices; use it as ds.isel(task.isel()).

Source code in grid_doctor/io/_manifest.py
def isel(self) -> dict[str, IndexSlice]:
    """Return the region as a mapping for ``Dataset.isel``.

    Same as [`slices`][grid_doctor.WriteTask.slices]; use it as
    ``ds.isel(task.isel())``.
    """
    return self.slices

to_dict()

JSON-compatible representation with all fields.

Source code in grid_doctor/io/_manifest.py
def to_dict(self) -> WriteTaskDict:
    """JSON-compatible representation with all fields."""
    return {
        "task_id": self.task_id,
        "manifest_id": self.manifest_id,
        "path": self.path,
        "zarr_format": self.zarr_format,
        "variables": list(self.variables),
        "region": _region_to_json(self.region),
        "levels": list(self.levels),
    }

to_entry()

JSON form inside a manifest, without the fields it shares with it.

Source code in grid_doctor/io/_manifest.py
def to_entry(self) -> TaskEntryDict:
    """JSON form inside a manifest, without the fields it shares with it."""
    return {
        "task_id": self.task_id,
        "variables": list(self.variables),
        "region": _region_to_json(self.region),
        "levels": list(self.levels),
    }

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
@classmethod
def from_dict(
    cls,
    data: Mapping[str, object],
    *,
    defaults: Mapping[str, object] | None = None,
    where: str = "task",
) -> WriteTask:
    """Inverse of [`to_dict`][grid_doctor.WriteTask.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.
    """
    merged: dict[str, object] = {**(defaults or {}), **_mapping(data, where)}
    return cls(
        task_id=_as_str(_field(merged, "task_id", where), where, "task_id", safe=True),
        manifest_id=_as_str(_field(merged, "manifest_id", where), where, "manifest_id", safe=True),
        path=_as_str(_field(merged, "path", where), where, "path"),
        zarr_format=_zarr_format(_field(merged, "zarr_format", where), where),
        variables=_str_tuple(_field(merged, "variables", where), where, "variables"),
        region=_region(_field(merged, "region", where), where),
        levels=_int_tuple(_field(merged, "levels", where), where, "levels", minimum=0),
    )

to_json(*, indent=None)

Serialise to a JSON string.

Source code in grid_doctor/io/_manifest.py
def to_json(self, *, indent: int | None = None) -> str:
    """Serialise to a JSON string."""
    return json.dumps(self.to_dict(), indent=indent, sort_keys=True)

from_json(text) classmethod

Parse a task written by to_json.

Source code in grid_doctor/io/_manifest.py
@classmethod
def from_json(cls, text: str | bytes) -> WriteTask:
    """Parse a task written by [`to_json`][grid_doctor.WriteTask.to_json]."""
    return cls.from_dict(_mapping(_loads(text, "task"), "task"))

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. "level_7.zarr".

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 materialise at init time are written by the init step and appear in coords instead.

__post_init__()

Validate and normalise the fields (lists become tuples).

Source code in grid_doctor/io/_manifest.py
def __post_init__(self) -> None:
    """Validate and normalise the fields (lists become tuples)."""
    where = f"level {self.level!r}"
    coords = _str_tuple(self.coords, where, "coords", unique=True)
    data_vars = _instances(_as_tuple(self.data_vars, where, "data_vars"), ArraySpec, where, "data_vars")
    names = [spec.name for spec in data_vars]
    duplicates = sorted({n for n in names if names.count(n) > 1})
    if duplicates:
        _fail(where, f"duplicate data variables {duplicates}")
    both = sorted(set(names) & set(coords))
    if both:
        _fail(where, f"{both} listed as coordinate and data variable")
    _set(
        self,
        level=_as_int(self.level, where, "level", minimum=0),
        store=_as_str(self.store, where, "store", safe=True),
        coords=coords,
        data_vars=data_vars,
    )

array(name)

Return the spec of data variable name.

Source code in grid_doctor/io/_manifest.py
def array(self, name: str) -> ArraySpec:
    """Return the spec of data variable *name*."""
    for spec in self.data_vars:
        if spec.name == name:
            return spec
    raise KeyError(f"level {self.level} has no data variable {name!r}")

to_dict()

JSON-compatible representation.

Source code in grid_doctor/io/_manifest.py
def to_dict(self) -> LevelSpecDict:
    """JSON-compatible representation."""
    return {
        "level": self.level,
        "store": self.store,
        "coords": list(self.coords),
        "data_vars": [spec.to_dict() for spec in self.data_vars],
    }

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
@classmethod
def from_dict(cls, data: Mapping[str, object], *, where: str = "level") -> LevelSpec:
    """Inverse of [`to_dict`][grid_doctor.io.LevelSpec.to_dict].

    *where* names the location in error messages.
    """
    fields = _mapping(data, where)
    raw_vars = _as_tuple(_field(fields, "data_vars", where), where, "data_vars")
    return cls(
        level=_as_int(_field(fields, "level", where), where, "level"),
        store=_as_str(_field(fields, "store", where), where, "store", safe=True),
        coords=_str_tuple(_field(fields, "coords", where), where, "coords"),
        data_vars=tuple(
            ArraySpec.from_dict(
                _mapping(v, f"{where}.data_vars[{i}]"),
                where=f"{where}.data_vars[{i}]",
            )
            for i, v in enumerate(raw_vars)
        ),
    )

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. int16 for packed data).

__post_init__()

Validate and normalise the fields (lists become tuples).

Source code in grid_doctor/io/_manifest.py
def __post_init__(self) -> None:
    """Validate and normalise the fields (lists become tuples)."""
    where = f"array {self.name!r}"
    dims = _str_tuple(self.dims, where, "dims", unique=True)
    shape = _int_tuple(self.shape, where, "shape", minimum=0)
    chunks = _int_tuple(self.chunks, where, "chunks", minimum=1)
    if not len(dims) == len(shape) == len(chunks):
        _fail(
            where,
            f"dims {dims}, shape {shape} and chunks {chunks} must have the same length",
        )
    _set(
        self,
        name=_name(self.name, where, "name"),
        dims=dims,
        shape=shape,
        chunks=chunks,
        dtype=_as_str(self.dtype, where, "dtype"),
    )

size(dim)

Length of dim.

Source code in grid_doctor/io/_manifest.py
def size(self, dim: str) -> int:
    """Length of *dim*."""
    return self.shape[self.dims.index(dim)]

chunk(dim)

Write-unit size along dim.

Source code in grid_doctor/io/_manifest.py
def chunk(self, dim: str) -> int:
    """Write-unit size along *dim*."""
    return self.chunks[self.dims.index(dim)]

to_dict()

JSON-compatible representation.

Source code in grid_doctor/io/_manifest.py
def to_dict(self) -> ArraySpecDict:
    """JSON-compatible representation."""
    return {
        "name": self.name,
        "dims": list(self.dims),
        "shape": list(self.shape),
        "chunks": list(self.chunks),
        "dtype": self.dtype,
    }

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
@classmethod
def from_dict(cls, data: Mapping[str, object], *, where: str = "array") -> ArraySpec:
    """Inverse of [`to_dict`][grid_doctor.io.ArraySpec.to_dict].

    *where* names the location in error messages.
    """
    fields = _mapping(data, where)
    return cls(
        name=_name(_field(fields, "name", where), where, "name"),
        dims=_str_tuple(_field(fields, "dims", where), where, "dims"),
        shape=_int_tuple(_field(fields, "shape", where), where, "shape", minimum=0),
        chunks=_int_tuple(_field(fields, "chunks", where), where, "chunks", minimum=1),
        dtype=_as_str(_field(fields, "dtype", where), where, "dtype"),
    )

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 PyramidManifest.select_tasks to retry only those.

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 inspect_chunks=True: (task_id, absent, expected) for finished tasks whose region has chunks that are not stored. This is informational: zarr skips chunks that contain only fill values, so absent chunks are expected for masked or regional data.

complete property

True if every task finished and the layout matches.

__bool__()

Return complete.

Source code in grid_doctor/io/_fanout.py
def __bool__(self) -> bool:
    """Return [`complete`][grid_doctor.StoreReport.complete]."""
    return self.complete

summary()

One human-readable paragraph.

Source code in grid_doctor/io/_fanout.py
def summary(self) -> str:
    """One human-readable paragraph."""
    state = "complete" if self.complete else "INCOMPLETE"
    lines = [(f"Store {state}: {len(self.done_tasks)}/{self.n_tasks} task(s) done (manifest {self.manifest_id}).")]
    if self.missing_tasks:
        shown = ", ".join(self.missing_tasks[:10])
        more = len(self.missing_tasks) - 10
        lines.append(f"Missing: {shown}" + (f" and {more} more." if more > 0 else "."))
    lines.extend(f"Problem: {p}" for p in self.problems)
    if self.stale_markers:
        lines.append(f"Ignored {self.stale_markers} stale marker(s).")
    if self.absent_chunks:
        absent = sum(a for _, a, _ in self.absent_chunks)
        lines.append(
            f"{absent} chunk(s) not stored in {len(self.absent_chunks)} finished "
            "task(s) (all-fill-value chunks are skipped by zarr; this is "
            "expected for masked or regional data)."
        )
    return "\n".join(lines)

raise_if_incomplete()

Raise :class:IncompleteStoreError unless the store is complete.

Source code in grid_doctor/io/_fanout.py
def raise_if_incomplete(self) -> None:
    """Raise :class:`IncompleteStoreError` unless the store is complete."""
    if not self.complete:
        raise IncompleteStoreError(self.summary())

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 init_pyramid_store.

required
s3_options S3Options | None

Options for :class:s3fs.S3FileSystem (S3 targets only).

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
def load_manifest(path: str, s3_options: S3Options | None = None) -> PyramidManifest:
    """Read the manifest that the init step stored below *path*.

    Parameters
    ----------
    path:
        Pyramid root, as passed to ``init_pyramid_store``.
    s3_options:
        Options for :class:`s3fs.S3FileSystem` (S3 targets only).

    Raises
    ------
    ManifestError
        If no manifest exists, e.g. because the init step has not
        finished or the store was not initialised with a manifest.
    """
    target = _Target(path, s3_options)
    text = target.read_text(STATE_DIR, MANIFEST_FILE)
    if text is None:
        interrupted = _interrupted_init(target)
        if interrupted:
            raise ManifestError(f"no manifest at {path}: {interrupted}")
        raise ManifestError(
            f"no manifest at {path}/{STATE_DIR}/{MANIFEST_FILE}: run "
            "init_pyramid_store first (or wait for it to finish)"
        )
    return PyramidManifest.from_json(text)

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:s3fs.S3FileSystem (S3 targets only).

None
Source code in grid_doctor/io/_fanout.py
def is_current(item: PyramidManifest | WriteTask, s3_options: S3Options | None = None) -> bool:
    """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
    ----------
    item:
        A manifest or any of its tasks.
    s3_options:
        Options for :class:`s3fs.S3FileSystem` (S3 targets only).
    """
    text = _Target(item.path, s3_options).read_text(STATE_DIR, MANIFEST_FILE)
    if text is None:
        return False
    try:
        stored_id = json.loads(text).get("manifest_id")
    except json.JSONDecodeError:
        return False
    return bool(stored_id == item.manifest_id)

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:s3fs.S3FileSystem (S3 targets only).

None
Source code in grid_doctor/io/_fanout.py
def is_task_done(task: WriteTask, s3_options: S3Options | None = None) -> bool:
    """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
    ----------
    task:
        The work unit.
    s3_options:
        Options for :class:`s3fs.S3FileSystem` (S3 targets only).
    """
    if not is_current(task, s3_options):
        return False
    text = _Target(task.path, s3_options).read_text(STATE_DIR, DONE_DIR, f"{task.task_id}.json")
    if text is None:
        return False
    try:
        marker = json.loads(text)
    except json.JSONDecodeError:
        return False
    return bool(marker.get("manifest_id") == task.manifest_id and marker.get("task_id") == task.task_id)

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

Bases: TypedDict

JSON form of a PyramidManifest.

LevelSpecDict

Bases: TypedDict

JSON form of a LevelSpec.

ArraySpecDict

Bases: TypedDict

JSON form of an ArraySpec.

TaskEntryDict

Bases: TypedDict

JSON form of a task inside a manifest (shared fields omitted).

WriteTaskDict

Bases: TypedDict

JSON form of a stand-alone WriteTask.

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.