"""Multi-resolution pyramid construction orchestrator.

Two entry points (use one):

* ``build_pyramid(store, factors=[(cf_1, sf_1), ...])`` builds every
  coarser level in sequence, optionally emitting cross-level link
  arrays (``cross_level_storage="implicit"`` or ``"explicit"``).
* ``coarsen_level(store, source, target, coarsen_factor=..., sparsity_factor=...)``
  writes a single coarser level for callers that want manual control.

Both use the per-object pyramid: each surviving object's vertices are
aggregated into bin centroids (metavertices) that may be shared
between objects, and per-object OIDs are preserved across levels.
"""

from __future__ import annotations

import copy
from contextlib import contextmanager, nullcontext
from pathlib import Path
from typing import TYPE_CHECKING, Any

import numpy as np
import numpy.typing as npt

from zarr_vectors.constants import (
    CAP_MULTISCALE_LINKS,
    CAP_PRESERVED_OBJECT_IDS,
    CAP_SHARED_FRAGMENTS,
    COARSEN_PER_OBJECT,
    DEFAULT_CROSS_LEVEL_DEPTH,
    DEFAULT_CROSS_LEVEL_STORAGE,
    GEOM_LINE,
    GEOM_POLYLINE,
    GEOM_SKELETON,
    GEOM_STREAMLINE,
    LINK_ATTRIBUTES,
    LINKS,
    OBJECT_ATTRIBUTES,
    VALID_XLEVEL_STORAGE,
    VERTEX_FRAGMENTS,
    VERTICES,
    XLEVEL_EXPLICIT,
    XLEVEL_NONE,
)
from zarr_vectors.core.arrays import (
    _leading_grid_axes,
    create_object_attributes_array,
    create_object_index_array,
    create_vertices_array,
    link_endpoints_to_rows,
    list_chunk_keys,
    read_chunk_vertices,
    read_link_arrays,
    read_object_attributes,
    read_object_manifest_rows,
    vertices_dtype,
    write_chunk_vertices,
    write_cross_level_links,
    write_object_attributes,
    write_object_index,
)
from zarr_vectors.core.metadata import (
    LevelMetadata,
    get_level_chunk_shape,
    normalise_shard_shape,
)
from zarr_vectors.core.paths import links_group_path
from zarr_vectors.core.store import (
    create_resolution_level,
    get_resolution_level,
    list_resolution_levels,
    open_store,
    read_level_metadata,
    read_root_metadata,
    remove_resolution_level,
)
from zarr_vectors.exceptions import ArrayError, CoarseningError
from zarr_vectors.multiresolution.object_selection import apply_sparsity
from zarr_vectors.spatial.boundary import build_vertex_chunk_mapping
from zarr_vectors.spatial.chunking import assign_chunks
from zarr_vectors.typing import ChunkCoords

if TYPE_CHECKING:  # pragma: no cover - typing only
    from zarr_vectors.core.group import Group


# ===================================================================
# Single-level coarsening
# ===================================================================

def coarsen_level(
    store_path: str | Path | Group,
    source_level: int,
    target_level: int,
    *,
    coarsen_factor: float = 1.0,
    sparsity_factor: float = 1.0,
    chunk_scale_factor: int | tuple[int, ...] = 1,
    sparsity_strategy: str = "random",
    sparsity_seed: int | None = None,
    cross_level_storage: str = XLEVEL_NONE,
    method: str = COARSEN_PER_OBJECT,
    options: dict[str, Any] | None = None,
    sparsity_attribute: str | None = None,
    sparsity_attribute_mode: str = "max",
) -> dict[str, Any]:
    """Coarsen a single level and write it to the store.

    Per-object vertex aggregation with stable OIDs across levels.  A
    metavertex's source vertices may come from multiple source objects;
    the resulting metavertex appears in each of those objects' manifests
    at the coarser level.

    A level chunked by an attribute keeps its bins: the coarse level has
    the same leading bin axis and ``chunk_attribute_*`` metadata, and a
    metavertex aggregates vertices of one bin only.

    If the step raises part-way, what it wrote is removed before the
    error propagates: the target level, a ``links/+1`` family it added to
    the source level (or the one it replaced, which is put back), and the
    root attributes it stamped.  A registered ``method`` gets the same
    guarantee.

    Args:
        store_path: Path to the zarr vectors store.
        source_level: Level to read from.
        target_level: Level to write to.  Must not exist: raises
            :class:`~zarr_vectors.exceptions.CoarseningError` rather than
            merging into one that does.
        coarsen_factor: Per-object vertex aggregation factor (>= 1),
            expressed as a **ratio against the source level's bin**, not the
            root's: the target bin is ``source_level.bin_shape *
            coarsen_factor``, seeded from the root's effective bin at level 0.
            Factors therefore compound down a pyramid.  ``1.0`` is the identity
            (no aggregation).
        sparsity_factor: Object-dropping factor (≥ 1).  Survivors keep
            their OIDs; dropped objects leave empty manifest slots.
            ``1.0`` is the identity (no drop).
        chunk_scale_factor: Per-axis multiplier applied to the source
            level's ``chunk_shape`` to derive the target level's
            ``chunk_shape``.  ``1`` (default) keeps the chunk grid
            unchanged.  Scalar values apply uniformly to every axis;
            tuples set per-axis multipliers.  Each multiplier must be a
            positive integer (nested chunk grids).  When the resulting
            target chunk_shape differs from the root chunk_shape it is
            stamped on the target level's ``LevelMetadata.chunk_shape``;
            otherwise the target inherits from root.
        sparsity_strategy: Object selection strategy — ``"random"`` (core)
            or a name registered by ``zarr-vectors-tools``.
        sparsity_seed: Random seed.
        sparsity_attribute: Per-object attribute handed to the selection
            strategy as ``attribute_values``.
        sparsity_attribute_mode: ``"max"`` or ``"min"``, forwarded as
            ``attribute_mode``.
        cross_level_storage: When called via ``build_pyramid`` this is
            threaded through to enable inline ``±1`` cross-level link
            emission.  Standalone callers should leave it at the
            ``"none"`` default.
        method: Coarsening method.  ``"per_object"`` (core default) uses the
            metavertex-binning pyramid; any other name is dispatched to a
            method registered by ``zarr-vectors-tools`` via
            :mod:`zarr_vectors.multiresolution.registry` (raises if that
            package is not installed).
        options: Extra keywords for a registered ``method``, forwarded
            verbatim.  A strategy's own knobs (a polyline coarsener's
            ``coarsen_mode``, a codec, a worker pool) were unreachable
            through this entry point, so a caller who wanted one had to
            bypass the dispatch and import the strategy directly —
            defeating the registry.  Ignored by the built-in
            ``"per_object"`` method, which takes no extra keywords; passing
            options with it raises rather than silently dropping them.

    Returns:
        Summary dict.  Always includes ``method``,
        ``preserves_object_ids``, ``vertex_count``.
    """
    if method == COARSEN_PER_OBJECT:
        if options:
            raise CoarseningError(
                f"method='{COARSEN_PER_OBJECT}' takes no extra options; got "
                f"{sorted(options)}. Those keywords belong to a registered "
                f"strategy — pass method= as well."
            )
        strategy = _per_object_coarsen
    else:
        # Advanced coarsening methods live in zarr-vectors-tools.
        from zarr_vectors.multiresolution.registry import require_coarsen_strategy
        strategy = require_coarsen_strategy(method)
    # Before any write, and for registered methods too: an octree level's
    # chunks are leaves, which the coarseners would read as uniform cells,
    # and the cross-level links they write would address its rows by
    # leaf -- which to_uniform then leaves naming the wrong vertices.
    _refuse_octree_levels(store_path, [source_level, target_level], "coarsening")
    kwargs = dict(
        store_path=store_path,
        source_level=source_level,
        target_level=target_level,
        coarsen_factor=coarsen_factor,
        sparsity_factor=sparsity_factor,
        chunk_scale_factor=chunk_scale_factor,
        sparsity_strategy=sparsity_strategy,
        sparsity_seed=sparsity_seed,
        cross_level_storage=cross_level_storage,
    )
    if sparsity_attribute is not None:
        kwargs["sparsity_attribute"] = sparsity_attribute
        kwargs["sparsity_attribute_mode"] = sparsity_attribute_mode
    if strategy is _per_object_coarsen:
        summary = _per_object_coarsen(**kwargs)
        _refresh_arrays_present(store_path, (source_level, target_level))
        return summary
    # A registered strategy writes through its own code, so the step's
    # rollback is the store-level one: whatever it created or rewrote is
    # undone if it raises, as the built-in step undoes its own.
    with _rollback_build_on_failure(store_path):
        return strategy(**kwargs, **(options or {}))


def _refuse_octree_levels(store_path: Any, levels: list[int] | None, what: str) -> None:
    """Refuse when any of ``levels`` (all when ``None``) has octree chunks;
    a store that does not open is left for the coarsener to report."""
    from zarr_vectors.core.store import open_store
    from zarr_vectors.exceptions import StoreError
    from zarr_vectors.octree_chunks.guard import refuse_octree_levels

    try:
        root = open_store(store_path)
    except (StoreError, FileNotFoundError):
        return
    refuse_octree_levels(root, levels, what)


def _refresh_arrays_present(
    store_path: str | Path | Group, levels,
) -> None:
    """Re-derive ``arrays_present`` on ``levels`` from what is on disk."""
    from zarr_vectors.building import refresh_arrays_present

    root = open_store(store_path, mode="r+")
    present = set(list_resolution_levels(root))
    for level in levels:
        if level in present:
            refresh_arrays_present(get_resolution_level(root, level))


def _per_object_coarsen(
    *,
    store_path: str | Path | Group,
    source_level: int,
    target_level: int,
    coarsen_factor: float,
    sparsity_factor: float,
    chunk_scale_factor: int | tuple[int, ...] = 1,
    sparsity_strategy: str,
    sparsity_seed: int | None,
    cross_level_storage: str = XLEVEL_NONE,
    sparsity_attribute: str | None = None,
    sparsity_attribute_mode: str = "max",
) -> dict[str, Any]:
    """Per-object pyramid: aggregate within-bin source vertices into
    shared metavertices, preserving each surviving object's OID and
    its trajectory through the new metavertices.

    See the 12-step implementation sketch in the plan file
    ``Provenance-preserving pyramid: shared metavertices + ID-stable
    objects`` (`schema/zarr_vectors.linkml.yaml` schema captures the
    persistent metadata side).
    """
    root = open_store(store_path, mode="r+")
    root_meta = read_root_metadata(root)
    ndim = root_meta.sid_ndim

    # Source level's chunk_shape — may itself be a per-level override.
    try:
        src_level_meta = read_level_metadata(root, source_level)
    except Exception:
        src_level_meta = None
    source_chunk_shape = get_level_chunk_shape(root_meta, src_level_meta)

    # The bin ``coarsen_factor`` multiplies is the SOURCE LEVEL's, not the
    # root's, so factors compose per level: ``[2, 2, 2]`` bins at 2x, 4x and 8x
    # the root bin rather than 2x three times over.  Level 0 carries no
    # bin_shape of its own, so the root's effective bin seeds the chain.
    _src_bin = getattr(src_level_meta, "bin_shape", None) if src_level_meta else None
    base_bin = (
        tuple(float(b) for b in _src_bin) if _src_bin
        else root_meta.effective_bin_shape
    )

    # Target level's chunk_shape = source × chunk_scale_factor (per-axis).
    if isinstance(chunk_scale_factor, (tuple, list)):
        if len(chunk_scale_factor) != ndim:
            raise CoarseningError(
                f"chunk_scale_factor rank {len(chunk_scale_factor)} "
                f"!= sid_ndim {ndim}"
            )
        chunk_scale = tuple(int(r) for r in chunk_scale_factor)
    else:
        chunk_scale = tuple(int(chunk_scale_factor) for _ in range(ndim))
    if any(r < 1 for r in chunk_scale):
        raise CoarseningError(
            f"chunk_scale_factor must be positive integers per axis, "
            f"got {chunk_scale}"
        )
    target_chunk_shape = tuple(
        float(s) * int(r) for s, r in zip(source_chunk_shape, chunk_scale)
    )
    # The on-disk per-level chunk_shape field is omitted when the
    # target equals root (the implicit default).  Compare via float.
    target_chunk_shape_override: tuple[float, ...] | None
    if all(
        abs(t - r) < 1e-9
        for t, r in zip(target_chunk_shape, root_meta.chunk_shape)
    ):
        target_chunk_shape_override = None
    else:
        target_chunk_shape_override = target_chunk_shape
    chunk_shape = target_chunk_shape  # used for assign_chunks below

    src_group = get_resolution_level(root, source_level)

    # The docstring has always said the target must not exist; nothing
    # checked, and ``create_resolution_level`` uses require_group, so a
    # second run merged into the first.  Refusing is also what lets a
    # failed run below roll back everything it wrote: all of it is new.
    if target_level in list_resolution_levels(root):
        raise CoarseningError(
            f"level {target_level} already exists; coarsening into it would "
            f"merge into what is there. Remove it first with "
            f"remove_resolution_level(root, {target_level})."
        )

    # A level chunked by an attribute puts a bin index first in every
    # chunk key.  The coarse level keeps the same bins, so both ends of a
    # cross-level link have one rank, and a metavertex never mixes bins,
    # or a categorical read of a coarse level would return vertices from
    # other categories.  ``ndim`` stays the coordinate width, which is
    # what every read and row count below needs; ``key_ndim`` is the rank
    # of a chunk key, which is what the object index and links need.
    leading = _leading_grid_axes(src_group, src_level_meta, ndim)
    if len(leading) > 1:
        raise CoarseningError(
            f"level {source_level} has {len(leading)} leading grid axes; "
            f"coarsening supports at most one (a single chunk_by_attribute "
            f"or rechunk bin axis)"
        )
    key_ndim = ndim + len(leading)
    src_keys = list_chunk_keys(src_group, VERTICES)
    if src_keys and len(src_keys[0]) != key_ndim:
        raise CoarseningError(
            f"level {source_level}'s chunk keys have {len(src_keys[0])} "
            f"components but its grid has rank {key_ndim}; the level is "
            f"inconsistent (validate(store, level=1) reports where)"
        )
    bin_meta: dict[str, Any] = {}
    if leading:
        bin_meta = {
            name: getattr(src_level_meta, name, None)
            for name in (
                "chunk_dims", "chunk_attribute_name", "chunk_attribute_values",
            )
        }

    # --- Step 0: read source manifests + vertex positions ----------------
    # Read source vertex positions, indexed by (chunk_coords, fragment_idx).
    # One prefetch for the level: read chunk by chunk, each read opened
    # its own one-cell prefetch, and two thousand of those cost 14 s of
    # a 45 s pyramid -- more than the coarsening itself.
    src_fragment_positions: dict[tuple[ChunkCoords, int], npt.NDArray] = {}
    # The declared dtype once, not once per chunk: unasked, every read
    # resolved the ``vertices`` node again to look it up.
    src_dtype = vertices_dtype(src_group)
    with _level_prefetch(src_group):
        for cc in src_keys:
            try:
                fragments = read_chunk_vertices(src_group, cc, dtype=src_dtype, ndim=ndim)
            except ArrayError:
                continue
            for fragment_idx, fragment in enumerate(fragments):
                src_fragment_positions[(cc, fragment_idx)] = fragment

    src_has_objects = "object_index" in src_group
    src_ids: npt.NDArray[np.int64] | None = None
    if src_has_objects:
        # Ids alongside rows: ``keep_oids`` below indexes the manifest
        # list, which is row order, and the object the coarse level must
        # carry forward is named by the id at that row -- the same thing
        # only while a level stores its objects densely from zero.
        src_ids, src_manifests = read_object_manifest_rows(src_group)
    else:
        # No object_index — treat the level as one implicit object whose
        # manifest enumerates every fragment in chunk-major order.
        implicit: list[tuple[ChunkCoords, int]] = []
        for cc in src_keys:
            fragment_idx = 0
            while (cc, fragment_idx) in src_fragment_positions:
                implicit.append((cc, fragment_idx))
                fragment_idx += 1
        src_manifests = [implicit] if implicit else []
    n_src_objects = len(src_manifests)
    if n_src_objects == 0:
        return {
            "vertex_count": 0,
            "object_count": 0,
            "objects_kept": 0,
            "method": COARSEN_PER_OBJECT,
            "preserves_object_ids": True,
        }

    # --- Step 1: drop a fraction of source objects ----------------------
    # Nested: draw only from objects the source level still holds.
    keep_oids: list[int]
    candidates = [row for row, m in enumerate(src_manifests) if m]
    # 1.0 unless a selection actually ran (a lone implicit object never is).
    sparsity_applied = sparsity_factor > 1.0 and len(candidates) > 1
    step_sparsity = (1.0 / sparsity_factor) if sparsity_applied else 1.0
    if sparsity_applied:
        keep_frac = 1.0 / sparsity_factor
        ctx: dict[str, Any] = {}
        if sparsity_strategy != "random":
            ctx = _selection_context(
                src_group, candidates, src_manifests, src_fragment_positions,
                ndim=ndim,
                geometry_types=root_meta.geometry_types,
                attribute=sparsity_attribute,
            )
        kept = apply_sparsity(
            len(candidates), keep_frac, sparsity_strategy,
            seed=sparsity_seed,
            bin_shape=base_bin,
            attribute_mode=sparsity_attribute_mode,
            **ctx,
        )
        keep_oids = sorted(candidates[int(i)] for i in kept)
    else:
        keep_oids = list(range(n_src_objects))

    # --- Step 2-3: build (source vertex → bin → metavertex) map ---------
    # Per-object source-vertex counts, in ``keep_oids`` order, alongside
    # the flat concatenation of the positions themselves.
    #
    # Only the counts are kept per object, not the positions: step 7
    # below walks the flat array in per-object slices and needs the slice
    # lengths, so holding each object's own copy as well meant a second
    # full copy of the level's vertices alive at the same time as
    # ``all_pos``. On a million vertices the peak was 68 times the data.
    per_object_count: dict[int, int] = {}
    flat_positions: list[np.ndarray] = []
    # Each vertex's bin, as run lengths in ``all_pos`` order: the bin is
    # the leading component of the key its fragment was read from, and a
    # fragment lies in one cell, so one run per fragment.
    run_bins: list[int] = []
    run_lengths: list[int] = []
    for oid in keep_oids:
        manifest = src_manifests[oid]
        parts: list[np.ndarray] = []
        for cc, fragment_idx in manifest:
            fragment = src_fragment_positions.get((cc, fragment_idx))
            if fragment is None or len(fragment) == 0:
                continue
            parts.append(np.asarray(fragment, dtype=np.float32))
            if leading:
                run_bins.append(int(cc[0]))
                run_lengths.append(len(fragment))
        if not parts:
            per_object_count[oid] = 0
            continue
        obj_positions = np.concatenate(parts, axis=0)
        per_object_count[oid] = int(obj_positions.shape[0])
        flat_positions.append(obj_positions)

    # The source fragments have been copied into the flat array and are
    # not read again; releasing them here keeps the source level and the
    # working copy from being resident at once.
    src_fragment_positions.clear()

    if not flat_positions:
        # Surviving objects had no vertices.  Write an empty level.
        with _rollback_level_on_failure(root, source_level, target_level):
            _write_empty_preserve_level(
                root, source_level, target_level,
                base_bin=base_bin,
                root_meta=root_meta,
                coarsen_factor=coarsen_factor,
                sparsity_factor=sparsity_factor if sparsity_applied else 1.0,
                inherited_num_objects=n_src_objects,
                chunk_shape=chunk_shape,
                chunk_shape_override=target_chunk_shape_override,
                leading=leading,
                bin_meta=bin_meta,
            )
        return {
            "vertex_count": 0,
            "object_count": 0,
            "objects_kept": len(keep_oids),
            "method": COARSEN_PER_OBJECT,
            "preserves_object_ids": True,
            "shared_fragments": True,
        }

    all_pos = np.concatenate(flat_positions, axis=0)
    # ``all_pos`` owns the data now; the per-object arrays were its only
    # other reference.
    flat_positions.clear()

    # Target bin shape: source bin_shape × coarsen_factor.
    # Target bin shape: the SOURCE level's bin_shape x coarsen_factor, so the
    # factor is a per-level ratio and successive levels compound.
    target_bin_shape = tuple(float(b) * float(coarsen_factor) for b in base_bin)

    # Compute per-vertex bin coords: (N, ndim) int64.
    bin_shape_arr = np.asarray(target_bin_shape, dtype=np.float64)
    bin_coords = np.floor(all_pos / bin_shape_arr).astype(np.int64)
    all_bins: npt.NDArray[np.int64] | None = None
    if leading:
        # The attribute bin leads the grouping key, so vertices of two
        # bins that share a spatial bin become two metavertices.
        all_bins = np.repeat(
            np.asarray(run_bins, dtype=np.int64),
            np.asarray(run_lengths, dtype=np.int64),
        )
        bin_coords = np.concatenate([all_bins[:, None], bin_coords], axis=1)
    # Combine each bin coord tuple into a single sort-key for np.unique.
    bin_keys = np.ascontiguousarray(bin_coords).view(
        np.dtype((np.void, bin_coords.dtype.itemsize * bin_coords.shape[1]))
    ).ravel()
    unique_keys, inverse = np.unique(bin_keys, return_inverse=True)
    inverse = inverse.astype(np.int64, copy=False)
    n_metavertices = int(inverse.max()) + 1 if inverse.size > 0 else 0
    # Each metavertex's attribute bin: all its members share one.
    mv_bin: npt.NDArray[np.int64] | None = None
    if all_bins is not None:
        mv_bin = np.empty(n_metavertices, dtype=np.int64)
        mv_bin[inverse] = all_bins
        del all_bins
    # bin_coords and the view over it are one int64 per axis per source
    # vertex -- twice all_pos -- and were held to the end of the function
    # purely so the cross-level step could recompute this np.unique on
    # them. It is the same answer, so pass it and let the source-sized
    # arrays go now.
    del bin_coords, bin_keys

    # --- Step 3 (continued): centroid per bin --------------------------
    # Sum each bin's member positions, then divide by its population.
    #
    # ``np.bincount``, not ``np.add.at``: the latter is numpy's
    # unbuffered scatter-add and takes the slow path on every element,
    # which at a million source vertices is a million of them. bincount
    # is the same reduction expressed as a histogram with weights, and
    # runs in C. The accumulation is in float64 so a densely populated
    # bin does not lose precision to float32 before the divide.
    bin_counts = np.bincount(inverse, minlength=n_metavertices).astype(
        np.int64, copy=False,
    )
    meta_positions = np.empty((n_metavertices, ndim), dtype=np.float32)
    for _axis in range(ndim):
        meta_positions[:, _axis] = (
            np.bincount(
                inverse,
                weights=all_pos[:, _axis].astype(np.float64, copy=False),
                minlength=n_metavertices,
            )
            / np.maximum(bin_counts, 1)
        )

    # --- Step 4: chunk-assign metavertices ------------------------------
    chunk_assignments = assign_chunks(meta_positions, chunk_shape)
    if mv_bin is not None:
        chunk_assignments = _split_by_bin(chunk_assignments, mv_bin)

    # --- Step 5: per-chunk fragment layout (one fragment per metavertex) ------------
    per_chunk_groups: dict[ChunkCoords, list[np.ndarray]] = {}
    # Where each metavertex ended up, as two dense arrays rather than a
    # dict with one tuple-valued entry per metavertex: at a million of
    # them that dict was ~150 MB of interpreter objects to express a map
    # from range(M).
    mv_chunk_slot = np.full(n_metavertices, -1, dtype=np.int64)
    mv_fragment_idx = np.full(n_metavertices, -1, dtype=np.int64)
    chunk_slots: list[ChunkCoords] = []
    for slot, (cc, indices) in enumerate(sorted(chunk_assignments.items())):
        # ``indices`` are metavertex indices that fell in this chunk.
        idx = np.asarray(indices, dtype=np.int64)
        chunk_slots.append(cc)
        mv_chunk_slot[idx] = slot
        mv_fragment_idx[idx] = np.arange(idx.size, dtype=np.int64)
        per_chunk_groups[cc] = list(np.split(meta_positions[idx], idx.size))

    # Everything from here writes.  A failure part-way used to leave a
    # half-built level behind, which a retry then merged into.
    with _rollback_level_on_failure(root, source_level, target_level):
        # --- Step 6: write per-chunk fragments --------------------------
        arrays_present = [VERTICES, "object_index"] if src_has_objects else [VERTICES]
        level_meta_initial = LevelMetadata(
            level=target_level,
            vertex_count=int(n_metavertices),
            arrays_present=arrays_present,
            bin_shape=target_bin_shape,
            # Fold-change relative to LEVEL 0, not to the source level: this is
            # what becomes the NGFF ``scale`` transform. With per-level coarsen
            # factors the two differ — [2, 2] is ratio 2 then 4 — so it has to be
            # derived from the bin shapes rather than echoing coarsen_factor.
            bin_ratio=tuple(
                max(1, int(round(float(t) / float(r))))
                for t, r in zip(target_bin_shape, root_meta.effective_bin_shape)
            ),
            chunk_shape=target_chunk_shape_override,
            object_sparsity=step_sparsity,
            coarsening_method=COARSEN_PER_OBJECT,
            parent_level=source_level,
            preserves_object_ids=src_has_objects,
            inherited_num_objects=n_src_objects if src_has_objects else 0,
            shared_fragments=True,
            **bin_meta,
        )
        level_group = create_resolution_level(root, target_level, level_meta_initial)
        with _coarse_grid(level_group, root_meta, chunk_shape, leading):
            create_vertices_array(level_group, dtype="float32")
            if src_has_objects:
                create_object_index_array(level_group)

            # One batch for the whole level. Unbatched, each cell write is a
            # parse-insert-sort-rewrite of the array's presence manifest, so
            # writing C cells costs O(C^2) -- 32,768 cells took 207s to write
            # through this path and 262,144 did not finish in 25 minutes.
            # Batched, the cells go out in one gather and presence is stamped
            # once for the array.
            with level_group.batched_writes():
                for cc, groups in sorted(per_chunk_groups.items()):
                    write_chunk_vertices(level_group, cc, groups, dtype=np.float32)

        # --- Step 7: emit per-object manifests ------------------------------
        # We need to map each source vertex back to its metavertex_index.
        # Walk per-object slices of the flat ``inverse`` array.
        cursor = 0
        new_manifests: dict[int, list[tuple[ChunkCoords, int]]] = {}

        def _id_of(row: int) -> int:
            """The object id at a source row -- the row itself when the
            source stored its objects densely from zero."""
            return int(src_ids[row]) if src_ids is not None else int(row)

        for oid in keep_oids:
            n = per_object_count[oid]
            if n == 0:
                cursor += 0
                new_manifests[_id_of(oid)] = []
                continue
            mv_seq = inverse[cursor:cursor + n]
            cursor += n
            # Drop consecutive duplicates, preserving order -- vectorised,
            # because this runs once per source vertex across the level.
            if mv_seq.size > 1:
                keep = np.concatenate(([True], mv_seq[1:] != mv_seq[:-1]))
                mv_seq = mv_seq[keep]
            new_manifests[_id_of(oid)] = [
                (chunk_slots[slot], int(frag))
                for slot, frag in zip(
                    mv_chunk_slot[mv_seq].tolist(),
                    mv_fragment_idx[mv_seq].tolist(),
                )
            ]

        # --- Step 9: emit object_index (dropped OIDs stay addressable) ------
        if src_has_objects:
            # Every source id gets a row, so a sparsified level keeps the
            # ids it dropped addressable -- as empty manifests, exactly as
            # the old slot padding did, but named rather than implied by
            # position. ``total_objects`` is deliberately not passed: it
            # declares the id space as range(n), which is only the source's
            # id space when that source numbered its objects densely.
            ids_for_index = (
                src_ids.tolist() if src_ids is not None
                else list(range(n_src_objects))
            )
            write_object_index(
                level_group,
                {int(oid): new_manifests.get(int(oid), []) for oid in ids_for_index},
                sid_ndim=key_ndim,
            )

        # --- Step 10: per-object attributes with present_mask ---------------
        src_obj_attr_group_name = f"{OBJECT_ATTRIBUTES}"
        if src_obj_attr_group_name in src_group:
            src_obj_attr_group = src_group[src_obj_attr_group_name]
            # children() covers both layouts: legacy per-chunk-array groups
            # under group_keys() and standalone arrays under array_keys().
            attr_names = src_obj_attr_group.children()
        else:
            attr_names = []
        for attr_name in attr_names:
            try:
                src_data = read_object_attributes(src_group, attr_name)
            except ArrayError:
                continue
            # Dense (O, C) or (O,) padded to the inherited OID space, with
            # rows for survivors copied over.  Layout matches the source's
            # OID space (which already equals n_src_objects).
            out_data = np.zeros_like(src_data)
            # One scatter each, rather than a Python iteration per surviving
            # object over a column that is already an array.
            keep_arr = np.asarray(keep_oids, dtype=np.int64)
            keep_arr = keep_arr[keep_arr < len(src_data)]
            if keep_arr.size:
                out_data[keep_arr] = src_data[keep_arr]
            mask = np.zeros(n_src_objects, dtype=np.uint8)
            mask[np.asarray(keep_oids, dtype=np.int64)] = 1
            create_object_attributes_array(level_group, attr_name)
            write_object_attributes(level_group, attr_name, out_data, present_mask=mask)

        # --- Step 12: stamp root capability tokens --------------------------
        if src_has_objects:
            _stamp_root_capability(root, CAP_PRESERVED_OBJECT_IDS)
        _stamp_root_capability(root, CAP_SHARED_FRAGMENTS)

        # --- Step 13: emit inline ±1 cross-level link arrays ----------------
        # Must stay after step 6's create_resolution_level: the anchor's
        # scale factors are read off the target level's metadata.
        if cross_level_storage != XLEVEL_NONE and n_metavertices > 0:
            _emit_inline_cross_level_links(
                root,
                src_group=src_group,
                level_group=level_group,
                source_level=source_level,
                ndim=ndim,
                n_leading=len(leading),
                bin_shape_arr=bin_shape_arr,
                unique_keys=unique_keys,
                coarse_chunk_assignments_mv=chunk_assignments,
                storage=cross_level_storage,
            )

    return {
        "vertex_count": int(n_metavertices),
        "object_count": len(keep_oids),
        "objects_kept": len(keep_oids),
        "source_objects": n_src_objects,
        "method": COARSEN_PER_OBJECT,
        "preserves_object_ids": True,
        "shared_fragments": True,
    }


_PATH_GEOMETRIES = frozenset({
    GEOM_LINE, GEOM_POLYLINE, GEOM_STREAMLINE, GEOM_SKELETON,
})


def _selection_context(
    src_group,
    candidates: list[int],
    manifests: list,
    fragment_positions: dict[tuple[ChunkCoords, int], npt.NDArray],
    *,
    ndim: int,
    geometry_types: list[str],
    attribute: str | None,
) -> dict[str, Any]:
    """``representative_points`` (middle vertex), ``lengths`` (path length,
    or vertex count for non-path geometry) and ``attribute_values`` for a
    selection strategy, aligned with ``candidates``."""
    n = len(candidates)
    rep = np.zeros((n, ndim), dtype=np.float64)
    lengths = np.zeros(n, dtype=np.float64)
    path_like = bool(set(geometry_types or ()) & _PATH_GEOMETRIES)
    for slot, row in enumerate(candidates):
        parts = [
            fragment_positions[key] for key in manifests[row]
            if key in fragment_positions and len(fragment_positions[key])
        ]
        if not parts:
            continue
        pts = np.concatenate(parts, axis=0).astype(np.float64, copy=False)
        rep[slot] = pts[len(pts) // 2]
        if path_like:
            lengths[slot] = float(
                np.sqrt((np.diff(pts, axis=0) ** 2).sum(axis=1)).sum()
            )
        else:
            lengths[slot] = float(len(pts))
    ctx: dict[str, Any] = {"representative_points": rep, "lengths": lengths}
    if attribute is not None:
        try:
            values = read_object_attributes(src_group, attribute)
        except ArrayError as exc:
            raise CoarseningError(
                f"sparsity_attribute {attribute!r} is not an object "
                f"attribute of the source level"
            ) from exc
        ctx["attribute_values"] = np.asarray(values)[
            np.asarray(candidates, dtype=np.int64)
        ]
    return ctx


def _emit_inline_cross_level_links(
    root,
    *,
    src_group,
    level_group,
    source_level: int,
    ndim: int,
    n_leading: int = 0,
    bin_shape_arr: npt.NDArray[np.float64],
    unique_keys: npt.NDArray,
    coarse_chunk_assignments_mv: dict[ChunkCoords, npt.NDArray[np.int64]],
    storage: str,
) -> None:
    """Emit the ``±1`` link families for one coarsen step.

    Re-walks the source level in chunk-major order, re-bins each
    vertex against ``bin_shape_arr`` -- prefixed with the first
    ``n_leading`` components of its chunk key, the attribute bin, exactly
    as the grouping key was built -- and looks up the matching
    metavertex via the ``bin_key`` ↔ ``mv_idx`` map implicit in
    ``np.unique(bin_keys, return_inverse=inverse)``.  Translates
    metavertex IDs to chunk-major-flat coarse indices via the
    just-written coarse-level chunks, then dispatches to
    :func:`_write_cross_level_edges`.

    ORDERING CONSTRAINT: the target level must already exist on disk
    with its ``LevelMetadata`` — including any ``chunk_shape`` override
    — before this runs.  ``write_links`` derives ``(r_src, r_trg)`` via
    ``arrays._derive_level_scales``, which falls back to ALL-ONES when it
    cannot read the target level.  All-ones is right only for a pyramid
    built at the default ``chunk_scale_factor=1``; on a scaled pyramid it
    silently mis-anchors every cross-level record.  Callers must keep
    this after the ``create_resolution_level`` for ``source_level + 1``
    (step 6 of :func:`_per_object_coarsen`).
    """
    # ``unique_keys`` arrives from the caller, which already computed it
    # binning the source. Metavertex ids are positions in it, which is
    # what lets the per-vertex lookup below be a searchsorted rather than
    # a dict with one bytes key per metavertex.

    # mv_idx → chunk-major-flat coarse index.
    coarse_chunk_assignments, n_coarse = _reconstruct_chunk_assignments(
        level_group, ndim,
    )
    # Dense map, so an array rather than a dict with one entry per
    # metavertex: at a million metavertices the dict was ~150 MB of
    # interpreter objects to express a permutation of range(M).
    mv_to_coarse_global = np.full(len(unique_keys), -1, dtype=np.int64)
    for cc, mv_indices_for_chunk in sorted(coarse_chunk_assignments_mv.items()):
        mv_idx_arr = np.asarray(mv_indices_for_chunk, dtype=np.int64)
        if mv_idx_arr.size == 0:
            continue
        mv_to_coarse_global[mv_idx_arr] = np.asarray(
            coarse_chunk_assignments[cc], dtype=np.int64,
        )[: mv_idx_arr.size]

    # Build fine→coarse parent[] by re-walking source in chunk-major order.
    fine_chunk_assignments, n_fine = _reconstruct_chunk_assignments(
        src_group, ndim,
    )
    parent = np.full(n_fine, -1, dtype=np.int64)
    cursor = 0
    key_dtype = np.dtype((
        np.void,
        (int(bin_shape_arr.shape[0]) + n_leading) * np.dtype(np.int64).itemsize,
    ))
    # Read at the declared dtype, then binned in float32 as the grouping
    # was: a float64 level read as float32 decodes to garbage.
    src_dtype = vertices_dtype(src_group)
    with _level_prefetch(src_group):
        for cc in list_chunk_keys(src_group, VERTICES):
            try:
                fragments = read_chunk_vertices(
                    src_group, cc, dtype=src_dtype, ndim=ndim,
                )
            except ArrayError:
                continue
            for fragment in fragments:
                n_local = int(fragment.shape[0])
                if n_local == 0:
                    continue
                local_bins = np.floor(
                    np.asarray(fragment, dtype=np.float32) / bin_shape_arr,
                ).astype(np.int64)
                if n_leading:
                    local_bins = np.concatenate([
                        np.broadcast_to(
                            np.asarray(cc[:n_leading], dtype=np.int64),
                            (n_local, n_leading),
                        ),
                        local_bins,
                    ], axis=1)
                local_keys = np.ascontiguousarray(local_bins).view(key_dtype).ravel()
                # One searchsorted per fragment, not one dict lookup per
                # vertex. ``unique_keys`` is np.unique output and therefore
                # sorted, so the position it returns IS the metavertex index.
                # The old form allocated a bytes object per vertex, which was
                # the hottest Python loop in the coarsener.
                pos = np.searchsorted(unique_keys, local_keys)
                np.clip(pos, 0, len(unique_keys) - 1, out=pos)
                # A key the coarse level never produced has no parent; the
                # caller relies on those staying -1.
                hit = unique_keys[pos] == local_keys
                if hit.any():
                    parent[cursor + np.flatnonzero(hit)] = mv_to_coarse_global[
                        pos[hit]
                    ]
                cursor += n_local

    _write_cross_level_edges(
        root,
        fine_level=source_level,
        delta=1,
        fine_chunk_assignments=fine_chunk_assignments,
        coarse_chunk_assignments=coarse_chunk_assignments,
        n_fine=n_fine,
        n_coarse=n_coarse,
        parent=parent,
        storage=storage,
    )


def _write_empty_preserve_level(
    root,
    source_level: int,
    target_level: int,
    *,
    base_bin: tuple[float, ...],
    root_meta: Any,
    coarsen_factor: float,
    sparsity_factor: float,
    inherited_num_objects: int,
    chunk_shape: tuple[float, ...],
    chunk_shape_override: tuple[float, ...] | None,
    leading: tuple[int, ...] = (),
    bin_meta: dict[str, Any] | None = None,
) -> None:
    """Write an empty ID-preserving level when no surviving object has vertices.

    ``base_bin`` is the SOURCE level's bin (what ``coarsen_factor`` multiplies);
    the root's is needed for the level-0-relative ``bin_ratio``.  The level
    is otherwise the one a populated coarsen would have written: the same
    ``chunk_shape`` override, and the same leading bin axis, so a later
    level coarsened from it -- or an array added to it -- lands on the
    grid its siblings have.
    """
    ndim = len(base_bin)
    target_bin_shape = tuple(float(b) * float(coarsen_factor) for b in base_bin)
    level_meta = LevelMetadata(
        level=target_level,
        vertex_count=0,
        arrays_present=[VERTICES, "object_index"],
        bin_shape=target_bin_shape,
        # Level-0-relative, as above — it is the NGFF scale, not the per-level
        # factor.
        bin_ratio=tuple(
            max(1, int(round(float(t) / float(r))))
            for t, r in zip(target_bin_shape, root_meta.effective_bin_shape)
        ),
        chunk_shape=chunk_shape_override,
        object_sparsity=(1.0 / sparsity_factor),
        coarsening_method=COARSEN_PER_OBJECT,
        parent_level=source_level,
        preserves_object_ids=True,
        inherited_num_objects=inherited_num_objects,
        shared_fragments=True,
        **(bin_meta or {}),
    )
    level_group = create_resolution_level(root, target_level, level_meta)
    with _coarse_grid(level_group, root_meta, chunk_shape, leading):
        create_vertices_array(level_group, dtype="float32")
        create_object_index_array(level_group)
    # Empty object_index with the inherited size — all manifests are [].
    write_object_index(
        level_group, {}, sid_ndim=ndim + len(leading),
        total_objects=inherited_num_objects,
    )
    _stamp_root_capability(root, CAP_PRESERVED_OBJECT_IDS)


def _split_by_bin(
    assignments: dict[ChunkCoords, npt.NDArray],
    mv_bin: npt.NDArray[np.int64],
) -> dict[ChunkCoords, npt.NDArray]:
    """``{(z, y, x): idx}`` -> ``{(bin, z, y, x): idx[mv_bin[idx] == bin]}``,
    keeping order within a chunk (it fixes each fragment index)."""
    out: dict[ChunkCoords, npt.NDArray] = {}
    for scc, idx in assignments.items():
        idx = np.asarray(idx)
        bins = mv_bin[idx]
        for b in np.unique(bins):
            out[(int(b), *scc)] = idx[bins == b]
    return out


def _coarse_grid(
    level_group, root_meta: Any, chunk_shape: tuple[float, ...],
    leading: tuple[int, ...],
):
    """The allocation context for a coarse level's per-chunk arrays: none for
    a spatial level; an explicit grid when there is a leading bin axis
    (its values may be unrecorded, so derivation could be a rank short)."""
    if not leading:
        return nullcontext()
    from zarr_vectors.core.arrays import level_grid_layout

    origin, grid = level_grid_layout(root_meta.bounds, chunk_shape)
    grid = (*leading, *grid)
    return level_group.native_sharded_arrays(
        normalise_shard_shape(root_meta.shard_shape, len(grid), bin_axis=True),
        grid,
        origin=(*((0,) * len(leading)), *origin),
    )


@contextmanager
def _rollback_level_on_failure(root, source_level: int, target_level: int):
    """Undo one coarsen step if it raises: drop the target level and any new
    ``links/+1`` family, restore root/source attrs.  A ``links/+1`` family the
    source already had (left by a half-removed pyramid) is copied aside first
    and put back, since the step's ``write_links(mode="replace")`` rewrites
    it.  A cleanup failure is added as a note on the original error."""
    src = get_resolution_level(root, source_level)
    # Deep copies: ``to_dict`` is shallow, and the stamps below edit the
    # nested ``zarr_vectors`` object in place, which would otherwise edit
    # the snapshot too and leave nothing to roll back to.
    root_before = copy.deepcopy(root.attrs.to_dict())
    src_before = copy.deepcopy(src.attrs.to_dict())
    had_links = src.array_exists(LINKS)
    plus_one = links_group_path(1)
    had_plus_one = src.array_exists(plus_one)
    saved_plus_one = (
        _copy_out(src, plus_one) | _copy_out_key(src, f"{LINKS}/zarr.json")
        if had_plus_one else {}
    )
    try:
        yield
    except BaseException as exc:
        try:
            if target_level in list_resolution_levels(root):
                remove_resolution_level(root, target_level)
            src = get_resolution_level(root, source_level)
            if not had_plus_one:
                stray = plus_one if had_links else LINKS
                if src.array_exists(stray):
                    src.delete_subtree(stray)
            else:
                # Removing the target took the rewritten family with it
                # (it points at the target); this puts the old one back.
                if src.array_exists(plus_one):
                    src.delete_subtree(plus_one)
                _copy_back(src, saved_plus_one, (LINKS,))
            for group, before in ((root, root_before), (src, src_before)):
                _restore_attrs(group, before)
        except Exception as cleanup:
            exc.add_note(
                f"rolling back level {target_level} also failed: {cleanup!r}"
            )
        raise


# -------------------------------------------------------------------
# Raw copies of store nodes, for rollback
# -------------------------------------------------------------------

def _store_key(group, name: str) -> str:
    return "/".join(p for p in (group.prefix.strip("/"), name) if p)


def _copy_out(group, name: str) -> dict[str, Any]:
    """Every stored key under ``group/name``, read into memory.

    Store-generic (a directory move is not), and only ever used on
    cross-level link families that exist *before* a build, which only a
    half-removed pyramid leaves behind -- not on anything the build itself
    writes, so the copy does not scale with the pyramid.
    """
    from zarr.core.buffer import default_buffer_prototype
    from zarr.core.sync import sync

    store = group.zarr_group.store
    base = _store_key(group, name)

    async def _collect() -> dict[str, Any]:
        proto = default_buffer_prototype()
        out: dict[str, Any] = {}
        async for key in store.list_prefix(f"{base}/"):
            value = await store.get(key, prototype=proto)
            if value is not None:
                out[key] = value
        return out

    return sync(_collect())


def _copy_out_key(group, name: str) -> dict[str, Any]:
    """One stored key (a group's ``zarr.json``), or nothing if absent."""
    from zarr.core.buffer import default_buffer_prototype
    from zarr.core.sync import sync

    store = group.zarr_group.store
    key = _store_key(group, name)
    value = sync(store.get(key, prototype=default_buffer_prototype()))
    return {} if value is None else {key: value}


def _copy_back(group, saved: dict[str, Any], invalidate: tuple[str, ...]) -> None:
    """Write keys saved by :func:`_copy_out` back, then drop cached nodes."""
    from zarr.core.sync import sync

    store = group.zarr_group.store

    async def _put() -> None:
        for key, value in saved.items():
            await store.set(key, value)

    if saved:
        sync(_put())
    for name in invalidate:
        group._invalidate_node(name)


def _restore_attrs(group, before: dict[str, Any]) -> None:
    """Make ``group``'s attributes exactly ``before`` again, dropping keys a
    failed build added rather than only resetting the ones it changed."""
    if group.attrs.to_dict() != before:
        group.zarr_group.attrs.put(before)


def _cross_level_families(level_group) -> list[str]:
    """Paths of the level's ``links/±k`` and ``link_attributes/<n>/±k``."""
    out: list[str] = []
    if level_group.array_exists(LINKS):
        out += [f"{LINKS}/{n}" for n in level_group[LINKS]
                if n[:1] in "+-"]
    if level_group.array_exists(LINK_ATTRIBUTES):
        for name in level_group[LINK_ATTRIBUTES]:
            fam = f"{LINK_ATTRIBUTES}/{name}"
            out += [f"{fam}/{n}" for n in level_group[fam] if n[:1] in "+-"]
    return out


def _link_groups(level_group) -> list[str]:
    """The groups holding link families: ``links``, ``link_attributes`` and
    ``link_attributes/<n>``, parents first."""
    out = [g for g in (LINKS, LINK_ATTRIBUTES) if level_group.array_exists(g)]
    if LINK_ATTRIBUTES in out:
        out += [f"{LINK_ATTRIBUTES}/{n}" for n in level_group[LINK_ATTRIBUTES]]
    return out


class _PyramidSnapshot:
    """What :func:`build_pyramid` may change, taken before it starts.

    That is the root's and every existing level's attributes (NGFF
    ``multiscales``, cross-level depth/storage, capabilities,
    ``arrays_present``) and every existing cross-level link family, which
    the inline ``+1`` and the finalize pass's ``±N`` writes replace.
    :meth:`restore` deletes the levels the build created and puts the rest
    back.  Same-level links (``links/0``) are never touched by a build, so
    they are not copied.
    """

    def __init__(self, root) -> None:
        self.levels = set(list_resolution_levels(root))
        self.root_attrs = root.attrs.to_dict()
        self.level_attrs: dict[int, dict[str, Any]] = {}
        self.groups: dict[int, list[str]] = {}
        self.saved: dict[int, dict[str, Any]] = {}
        for lvl in self.levels:
            lg = get_resolution_level(root, lvl)
            self.level_attrs[lvl] = lg.attrs.to_dict()
            self.groups[lvl] = _link_groups(lg)
            saved: dict[str, Any] = {}
            for grp in self.groups[lvl]:
                saved |= _copy_out_key(lg, f"{grp}/zarr.json")
            for fam in _cross_level_families(lg):
                saved |= _copy_out(lg, fam)
            self.saved[lvl] = saved

    def restore(self, root) -> None:
        from zarr_vectors.constants import RESOLUTION_PREFIX

        for lvl in sorted(set(list_resolution_levels(root)) - self.levels,
                          reverse=True):
            # Directly, not via remove_resolution_level: that refuses a
            # level with another above it, and what it also tidies (the
            # finer levels' families pointing here, multiscales) is put
            # back from the snapshot below anyway.
            root.delete_subtree(f"{RESOLUTION_PREFIX}{lvl}")
        for lvl in sorted(self.levels):
            lg = get_resolution_level(root, lvl)
            for fam in _cross_level_families(lg):
                lg.delete_subtree(fam)
            for grp in reversed(_link_groups(lg)):
                if grp not in self.groups[lvl] and lg.array_exists(grp):
                    lg.delete_subtree(grp)
            _copy_back(lg, self.saved[lvl], (LINKS, LINK_ATTRIBUTES))
            _restore_attrs(lg, self.level_attrs[lvl])
        _restore_attrs(root, self.root_attrs)


@contextmanager
def _rollback_build_on_failure(store_path):
    """Make a multi-level build all-or-nothing (see :class:`_PyramidSnapshot`).

    A store that does not open is left for the build to report."""
    from zarr_vectors.exceptions import StoreError

    try:
        root = open_store(store_path, mode="r+")
        snapshot = _PyramidSnapshot(root)
    except (StoreError, FileNotFoundError):
        yield
        return
    try:
        yield
    except BaseException as exc:
        try:
            snapshot.restore(open_store(store_path, mode="r+"))
        except Exception as cleanup:
            exc.add_note(f"rolling back the pyramid also failed: {cleanup!r}")
        raise


def _stamp_root_capability(root_group, cap: str) -> None:
    """Add ``cap`` to root metadata's ``format_capabilities`` (idempotent)."""
    attrs = root_group.attrs.to_dict()
    zv = attrs.get("zarr_vectors", {})
    caps = list(zv.get("format_capabilities", []))
    if cap not in caps:
        caps.append(cap)
        zv["format_capabilities"] = caps
        root_group.attrs.update({"zarr_vectors": zv})


def _stamp_root_cross_level(
    root_group, *, depth: int, storage: str,
) -> None:
    """Persist cross_level_depth/cross_level_storage on root metadata."""
    attrs = root_group.attrs.to_dict()
    zv = attrs.get("zarr_vectors", {})
    zv["cross_level_depth"] = int(depth)
    zv["cross_level_storage"] = storage
    root_group.attrs.update({"zarr_vectors": zv})


def _level_prefetch(level_group):
    """One batched read of every ``vertices`` and ``vertex_fragments``
    cell in the level, for a loop that would otherwise open one
    single-cell prefetch per chunk.

    A no-op inside an outer prefetch or an offline replay, like
    :func:`~zarr_vectors.core.arrays._maybe_batched_reads`.
    """
    from zarr_vectors.core.arrays import _chunk_key, _maybe_batched_reads

    keys = [_chunk_key(cc) for cc in list_chunk_keys(level_group, VERTICES)]
    return _maybe_batched_reads(level_group, [
        (VERTICES, keys), (VERTEX_FRAGMENTS, keys),
    ])


def _reconstruct_chunk_assignments(
    level_group, ndim: int,
) -> tuple[dict[ChunkCoords, npt.NDArray[np.int64]], int]:
    """Rebuild ``{chunk_coords: vertex_indices}`` from on-disk vertex chunks.

    The "vertex index" assigned to each vertex is the position it would
    occupy in a flat enumeration that walks chunks in
    ``list_chunk_keys`` order and concatenates each chunk's vertex
    groups in order.  This matches the convention used by
    ``build_vertex_chunk_mapping`` for in-memory edge partitioning.

    Returns the assignments dict and the total vertex count.

    Counts come from the size of each stored blob, not from decoding it.
    The old form called ``read_chunk_vertices`` on every chunk purely to
    sum ``fragment.shape[0]`` -- a full decode of the level's coordinate
    data to learn how many rows it had. This runs twice per coarsen step
    and once per level again in the finalize pass, so a pyramid paid for
    several complete decodes it never looked at.
    """
    from zarr_vectors.spatial.boundary import chunk_local_to_global_offsets

    offsets, chunk_keys, total = chunk_local_to_global_offsets(
        level_group, ndim,
    )
    assignments: dict[ChunkCoords, npt.NDArray[np.int64]] = {}
    for i, cc in enumerate(chunk_keys):
        start = offsets[cc]
        end = offsets[chunk_keys[i + 1]] if i + 1 < len(chunk_keys) else total
        if end <= start:
            # An empty chunk contributes no vertices, and the old form
            # skipped it rather than storing an empty range.
            continue
        assignments[cc] = np.arange(start, end, dtype=np.int64)
    return assignments, total


def _decode_parent_from_plus_one(
    fine_lg,
    *,
    fine_assn: dict[ChunkCoords, npt.NDArray[np.int64]],
    coarse_assn: dict[ChunkCoords, npt.NDArray[np.int64]],
    n_fine: int,
) -> npt.NDArray[np.int64] | None:
    """Decode a fine→coarse ``parent`` array from the already-written ``+1`` family.

    Reads every ``links/<+1>/<offsets>/`` record at the fine level and
    converts each ``(chunk, local_idx)`` endpoint to a global flat index
    via the supplied chunk-assignment dicts.  Endpoint 0 is the fine side
    and endpoint 1 the coarse side — :func:`write_links` keeps that order
    for ``delta != 0``.  Intra- and cross-chunk records arrive together:
    they differ only by which offsets array holds them, and ``read_links``
    already re-anchored each one back to absolute chunk coords.  Returns
    ``None`` when the family is absent or empty.
    """
    parent = np.full(n_fine, -1, dtype=np.int64)

    try:
        chunks, vi = read_link_arrays(fine_lg, delta=1)
    except (ArrayError, KeyError):
        return None
    if vi.shape[0] == 0 or vi.shape[1] != 2:
        return None
    # Each level's assignment for a chunk is a contiguous range, so the
    # global index of an endpoint is the range's start plus its local
    # index -- one gather per side rather than two dict lookups and an
    # int() per record.
    fine_start = {cc: int(rows[0]) for cc, rows in fine_assn.items() if rows.size}
    coarse_start = {cc: int(rows[0]) for cc, rows in coarse_assn.items() if rows.size}
    fine_idx = link_endpoints_to_rows(chunks[:, :1], vi[:, :1], fine_start)[:, 0]
    coarse_idx = link_endpoints_to_rows(chunks[:, 1:], vi[:, 1:], coarse_start)[:, 0]
    valid = (fine_idx >= 0) & (coarse_idx >= 0)
    if not valid.any():
        return None
    parent[fine_idx[valid]] = coarse_idx[valid]
    return parent


def _finalize_cross_level_for_store(
    store_path: str | Path | Group,
    *,
    cross_level_depth: int,
    cross_level_storage: str,
) -> None:
    """Persist root cross-level metadata and emit ``±N`` (N ≥ 2) link arrays.

    Adjacent ``±1`` arrays are emitted inline during coarsening (see
    :func:`_emit_inline_cross_level_links`).  This finalize pass walks
    every adjacent (fine, coarse) level pair, decodes the on-disk
    ``+1`` parent map back into a flat fine→coarse array, then composes
    step-by-step to produce ``+N``/``-N`` link arrays for N ≥ 2 up to
    ``cross_level_depth``.

    ``cross_level_depth=-1`` means "walk all available level pairs".
    """
    root = open_store(store_path, mode="r+")
    _stamp_root_cross_level(
        root, depth=cross_level_depth, storage=cross_level_storage,
    )
    if cross_level_storage == XLEVEL_NONE or cross_level_depth == 0:
        return

    meta = read_root_metadata(root)
    ndim = meta.sid_ndim
    levels = sorted(list_resolution_levels(root))
    if len(levels) < 2:
        return

    _stamp_root_capability(root, CAP_MULTISCALE_LINKS)

    # Build per-level chunk_assignments + total counts once.
    per_level: dict[int, tuple[dict[ChunkCoords, npt.NDArray[np.int64]], int]] = {}
    for lvl in levels:
        lg = get_resolution_level(root, lvl)
        per_level[lvl] = _reconstruct_chunk_assignments(lg, ndim)

    max_delta = (
        max(levels) - min(levels)
        if cross_level_depth == -1
        else int(cross_level_depth)
    )
    if max_delta < 2:
        return  # +1/-1 was already emitted inline

    # Cache each adjacent (fine_level, fine_level+1) parent array.
    adjacent_parent: dict[int, npt.NDArray[np.int64]] = {}
    for fine_level in levels[:-1]:
        coarse_level = fine_level + 1
        if coarse_level not in per_level:
            continue
        fine_assn, n_fine = per_level[fine_level]
        coarse_assn, _ = per_level[coarse_level]
        if n_fine == 0:
            continue
        fine_lg = get_resolution_level(root, fine_level)
        parent = _decode_parent_from_plus_one(
            fine_lg,
            fine_assn=fine_assn,
            coarse_assn=coarse_assn,
            n_fine=n_fine,
        )
        if parent is not None:
            adjacent_parent[fine_level] = parent

    # Compose deeper-delta parents and emit.
    for fine_level in levels[:-1]:
        if fine_level not in adjacent_parent:
            continue
        fine_assn, n_fine = per_level[fine_level]
        parent = adjacent_parent[fine_level].copy()
        for step in range(2, max_delta + 1):
            coarse_level = fine_level + step
            if coarse_level not in per_level:
                break
            inter_level = coarse_level - 1
            if inter_level not in adjacent_parent:
                break
            inter_parent = adjacent_parent[inter_level]
            coarse_assn, n_coarse = per_level[coarse_level]
            if n_coarse == 0:
                break

            composed = np.full(n_fine, -1, dtype=np.int64)
            valid = parent >= 0
            composed[valid] = inter_parent[parent[valid]]
            parent = composed
            if not np.any(parent >= 0):
                break

            _write_cross_level_edges(
                root,
                fine_level=fine_level,
                delta=step,
                fine_chunk_assignments=fine_assn,
                coarse_chunk_assignments=coarse_assn,
                n_fine=n_fine,
                n_coarse=n_coarse,
                parent=parent,
                storage=cross_level_storage,
            )


def _write_cross_level_edges(
    root_group,
    *,
    fine_level: int,
    delta: int,
    fine_chunk_assignments: dict[ChunkCoords, npt.NDArray[np.int64]],
    coarse_chunk_assignments: dict[ChunkCoords, npt.NDArray[np.int64]],
    n_fine: int,
    n_coarse: int,
    parent: npt.NDArray[np.int64],
    storage: str,
) -> None:
    """Materialize ``delta``-step cross-level edges between two adjacent levels.

    ``parent[i]`` is the metanode index in the coarser level that fine
    vertex ``i`` belongs to.  The cross-level edges are trivially
    ``(i, parent[i])`` for each fine vertex.

    Writes the ``+delta`` family under the fine level.  When
    ``storage='explicit'`` also writes the matching ``-delta`` family
    under the coarse level by swapping endpoint roles.

    Records go to :func:`write_links` in global ``(chunk_coords,
    vertex_idx)`` form; it routes each one to the offsets array for the
    gap between its endpoints, so intra- and cross-chunk edges are one
    call.  Crucially it anchors that gap through
    :func:`~zarr_vectors.spatial.boundary.anchor_chunk` using the two
    levels' real ``chunk_shape`` scales, which is the only correct way
    to difference chunk coords when ``chunk_scale_factor > 1`` gives the
    levels different chunk grids.  Both calls therefore require the
    level they reference across to already carry its metadata — see the
    ordering note on :func:`_emit_inline_cross_level_links`.
    """
    if storage == XLEVEL_NONE or delta == 0:
        return

    # Drop orphaned fine vertices (parent < 0) before building edges.
    valid_mask = parent >= 0
    if not np.any(valid_mask):
        return
    fine_global = np.flatnonzero(valid_mask).astype(np.int64)
    parent_valid = parent[valid_mask].astype(np.int64)

    # Build chunk-mapping tables for both levels.
    fine_vchunks, fine_vlocal, fine_chunk_list = build_vertex_chunk_mapping(
        fine_chunk_assignments, n_fine, sorted(fine_chunk_assignments.keys()),
    )
    coarse_vchunks, coarse_vlocal, coarse_chunk_list = build_vertex_chunk_mapping(
        coarse_chunk_assignments, n_coarse, sorted(coarse_chunk_assignments.keys()),
    )

    # Kept as arrays. build_vertex_chunk_mapping already returns the
    # per-vertex chunk and local indices as int64 arrays, so taking them
    # apart into a Python tuple per endpoint -- once per fine vertex, and
    # again for the mirrored family -- only to have the partitioner put
    # them back together was the dominant cost of a pyramid build.
    fine_chunk_arr = np.asarray(fine_chunk_list, dtype=np.int64)
    coarse_chunk_arr = np.asarray(coarse_chunk_list, dtype=np.int64)
    # The key rank, read off the keys rather than the root's sid_ndim: a
    # level chunked by an attribute has one more axis than the spatial
    # rank, and both ends of a link must have the same number.
    sid_ndim = int(fine_chunk_arr.shape[1])
    if coarse_chunk_arr.shape[1] != sid_ndim:
        raise CoarseningError(
            f"level {fine_level} has rank-{sid_ndim} chunk keys but level "
            f"{fine_level + delta} has rank-{coarse_chunk_arr.shape[1]}; "
            f"cross-level links need both ends on one grid rank"
        )
    fine_cc = fine_chunk_arr[fine_vchunks[fine_global]]
    fine_vi = fine_vlocal[fine_global]
    coarse_cc = coarse_chunk_arr[coarse_vchunks[parent_valid]]
    coarse_vi = coarse_vlocal[parent_valid]

    # Endpoint 0 leads and stays at the owning level, so each call's
    # anchor uses that level's scale as ``r_src``.  ``directed=True``:
    # fine→coarse parenthood is data, not an undirected pair.
    fine_lg = get_resolution_level(root_group, fine_level)
    # One batch for the family. Unbatched, each cell write is a
    # read-modify-write of the array's whole presence manifest, so
    # writing C cells costs O(C^2) -- the same bug already fixed for
    # this module's vertex writes and for shard_store, and the reason
    # the comment on step 6 records 207 s for 32k cells.
    with fine_lg.batched_writes():
        write_cross_level_links(
            fine_lg, fine_cc, fine_vi, coarse_cc, coarse_vi, sid_ndim,
            delta=delta,
        )

    if storage == XLEVEL_EXPLICIT:
        # Mirror at the coarse level under -delta: the coarse endpoint
        # leads, so the anchor's scales swap with it.  No re-partitioning
        # by hand — write_links re-derives the offsets from the coarse
        # grid, which is what the fine-side split cannot speak to.
        coarse_lg = get_resolution_level(root_group, fine_level + delta)
        with coarse_lg.batched_writes():
            write_cross_level_links(
                coarse_lg, coarse_cc, coarse_vi, fine_cc, fine_vi, sid_ndim,
                delta=-delta,
            )


# ===================================================================
# Full pyramid builder
# ===================================================================

def build_pyramid(
    store_path: str | Path | Group,
    *,
    factors: list[tuple[float, float]],
    chunk_scale_factors: list[int | tuple[int, ...]] | None = None,
    sparsity_strategy: str = "random",
    sparsity_seed: int | None = None,
    cross_level_depth: int = DEFAULT_CROSS_LEVEL_DEPTH,
    cross_level_storage: str = DEFAULT_CROSS_LEVEL_STORAGE,
    method: str = COARSEN_PER_OBJECT,
    options: dict[str, Any] | None = None,
    sparsity_attribute: str | None = None,
    sparsity_attribute_mode: str = "max",
) -> dict[str, Any]:
    """Build a multi-resolution pyramid for an existing store.

    Pass ``factors=[(coarsen_2, sparsity_3), ...]`` where ``factors[i]``
    is applied to produce level ``i+1`` from level ``i``.  Either factor
    at ``1.0`` opts out of that axis.  Uses the per-object pyramid:
    each surviving object's vertices are aggregated into bin centroids
    (metavertices); metavertices may be shared between objects and OIDs
    are preserved across levels.  A store chunked by an attribute keeps
    its bins at every level (see :func:`coarsen_level`).

    The build is all-or-nothing: if any step or the finalize pass raises,
    the levels it created are removed, and the root's and the existing
    levels' attributes and cross-level link families (including a stale
    ``links/+1`` left by a half-removed pyramid) are put back as they were
    before the call, before the error propagates.

    Args:
        store_path: Path to the store with level 0.
        factors: List of ``(coarsen_factor, sparsity_factor)`` tuples,
            one per coarser level.  ``coarsen_factor`` is a **per-level ratio
            against the level below**, so factors compound: ``[(2, 1), (2, 1),
            (2, 1)]`` bins at 2x, 4x and 8x the root bin.
        chunk_scale_factors: Optional per-level multipliers applied to
            the source level's ``chunk_shape`` to derive each target
            level's ``chunk_shape``.  Aligned with ``factors`` (same
            length).  Each entry is either a scalar int (uniform per
            axis) or a per-axis tuple.  ``None`` (default) means
            all-ones: every level inherits root ``chunk_shape``.
        sparsity_strategy: Object selection strategy — ``"random"`` (core)
            or a name registered by ``zarr-vectors-tools``.
        sparsity_seed: Random seed.
        sparsity_attribute / sparsity_attribute_mode: Per-object attribute
            handed to the selection strategy as ``attribute_values`` (see
            :func:`coarsen_level`).
        method: Coarsening method; ``"per_object"`` (core default) or a
            ``zarr-vectors-tools``-registered method (see
            :func:`coarsen_level`).
        cross_level_depth: Maximum absolute level delta for materialized
            cross-pyramid-level link arrays.  ``0`` = none, whatever
            ``cross_level_storage`` says, ``N`` = up
            to ``±N`` per pair (or ``+N`` only when
            ``cross_level_storage='implicit'``), ``-1`` = walk all
            available level pairs.  Default ``1``.
        cross_level_storage: ``"none"`` / ``"implicit"`` / ``"explicit"``.
            ``"explicit"`` materializes both ``+N`` (at the finer level)
            and ``-N`` (at the coarser level); ``"implicit"`` writes
            only ``+N``.  Default ``"explicit"``.

    Returns:
        Summary dict.
    """
    if cross_level_storage not in VALID_XLEVEL_STORAGE:
        raise ValueError(
            f"cross_level_storage={cross_level_storage!r} not in "
            f"{sorted(VALID_XLEVEL_STORAGE)}"
        )
    if cross_level_depth < -1:
        raise ValueError(
            f"cross_level_depth must be ≥ -1 (got {cross_level_depth})"
        )
    if chunk_scale_factors is not None and len(chunk_scale_factors) != len(factors):
        raise ValueError(
            f"chunk_scale_factors length {len(chunk_scale_factors)} != "
            f"factors length {len(factors)}",
        )
    # Every level, not only those coarsened: the cross-level pass below
    # writes links into any level pair it finds.
    _refuse_octree_levels(store_path, None, "building a pyramid")

    with _rollback_build_on_failure(store_path):
        summaries = _build_levels(
            store_path,
            factors=factors,
            chunk_scale_factors=chunk_scale_factors,
            sparsity_strategy=sparsity_strategy,
            sparsity_seed=sparsity_seed,
            cross_level_depth=cross_level_depth,
            cross_level_storage=cross_level_storage,
            method=method,
            options=options,
            sparsity_attribute=sparsity_attribute,
            sparsity_attribute_mode=sparsity_attribute_mode,
        )

    return {
        "levels_created": len(summaries),
        "level_specs": summaries,
        # The method actually used, not the built-in: this reported
        # "per_object" even when every level had been produced by a
        # registered strategy, so the one field naming what built the
        # pyramid was wrong exactly when it mattered.
        "method": method,
        "cross_level_depth": cross_level_depth,
        "cross_level_storage": cross_level_storage,
    }


def _build_levels(
    store_path: str | Path | Group,
    *,
    factors: list[tuple[float, float]],
    chunk_scale_factors: list[int | tuple[int, ...]] | None,
    sparsity_strategy: str,
    sparsity_seed: int | None,
    cross_level_depth: int,
    cross_level_storage: str,
    method: str,
    options: dict[str, Any] | None,
    sparsity_attribute: str | None,
    sparsity_attribute_mode: str,
) -> list[dict[str, Any]]:
    """The steps and finalize pass of :func:`build_pyramid`, unguarded."""
    summaries: list[dict[str, Any]] = []
    for i, fac in enumerate(factors):
        if isinstance(fac, (tuple, list)) and len(fac) == 2:
            cf, sf = float(fac[0]), float(fac[1])
        else:
            raise ValueError(
                f"factors[{i}] must be a (coarsen_factor, sparsity_factor) "
                f"tuple; got {fac!r}"
            )
        chunk_scale = (
            chunk_scale_factors[i] if chunk_scale_factors is not None else 1
        )
        summaries.append(coarsen_level(
            store_path,
            source_level=i,
            target_level=i + 1,
            coarsen_factor=cf,
            sparsity_factor=sf,
            chunk_scale_factor=chunk_scale,
            sparsity_strategy=sparsity_strategy,
            sparsity_seed=sparsity_seed,
            # Depth 0 asks for no cross-level links, but the storage mode
            # was all the inline ±1 emission checked, so it wrote them
            # anyway while the root recorded depth 0.
            cross_level_storage=(
                XLEVEL_NONE if cross_level_depth == 0 else cross_level_storage
            ),
            method=method,
            options=options,
            sparsity_attribute=sparsity_attribute,
            sparsity_attribute_mode=sparsity_attribute_mode,
        ))

    # Compose deeper-delta cross-level links from the inline-emitted +1
    # arrays.  Also stamps root cross-level metadata + the multiscale
    # links capability.
    _finalize_cross_level_for_store(
        store_path,
        cross_level_depth=cross_level_depth,
        cross_level_storage=cross_level_storage,
    )
    # The finalize pass adds deeper link families after the per-step refresh.
    if cross_level_depth not in (0, 1) and cross_level_storage != XLEVEL_NONE:
        _refresh_arrays_present(store_path, range(len(factors) + 1))
    return summaries
