"""Create, write, and read ZV per-level arrays.

Each "array" is a subdirectory within a resolution-level group.  Chunk
data is stored as raw binary files named by their spatial chunk
coordinates (e.g. ``vertices/0.0.0``).  Array metadata is in the
``attributes`` of ``<array>/zarr.json``.

This module is the single point of contact for all array I/O — type
modules (``types/*.py``) call these functions rather than touching
the store or encoding modules directly.
"""

from __future__ import annotations

import itertools
import warnings
from collections.abc import Iterable, Iterator, Mapping, Sequence
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any, Literal

import numpy as np
import numpy.typing as npt
from zarr.codecs import VLenBytesCodec
from zarr.errors import UnstableSpecificationWarning

from zarr_vectors.constants import (
    FRAGMENT_ATTRIBUTES,
    GROUP_ATTRIBUTES,
    GROUPS,
    LINK_ATTRIBUTES,
    LINK_FRAGMENTS,
    LINKS,
    OBJECT_ATTRIBUTES,
    OBJECT_INDEX,
    VERTEX_ATTRIBUTES,
    VERTEX_FRAGMENTS,
    VERTICES,
)
from zarr_vectors.core import convention as _zvc

# Group, not FsGroup: FsGroup is a no-op subclass that create_store and
# open_store return only when the backing store happens to be a
# LocalStore, so annotating these functions with it was already wrong for
# every cloud-backed store. Annotation-only change; nothing moves.
from zarr_vectors.core.group import _LEVEL_META_KEY, Group
from zarr_vectors.core.paths import (
    format_delta,
    format_offsets,
    intra_offsets,
    is_intra,
    link_attributes_group_path,
    link_attributes_path,
    links_group_path,
    links_path,
    parse_delta,
    parse_offsets,
)
from zarr_vectors.core.store import FsGroup  # noqa: F401  (re-exported for callers)
from zarr_vectors.encoding.fragments import (
    ChunkFragmentIndex,
    classify_fragments_csr,
    concat_fragment_sections,
    decode_fragments,
    decode_object_manifest_blocks,
    decode_object_manifests_csr,
    decode_object_manifests_many,
    encode_fragments,
    encode_object_manifest_blocks,
    encode_object_manifests_csr,
    encode_object_manifests_many,
    fragment_sections_from_index,
    pack_fragment_sections,
    range_fragment_sections,
)
from zarr_vectors.encoding.ragged import (
    decode_ragged_blob,
    encode_ragged_blob,
    encode_ragged_floats,
    encode_ragged_ints,
)
from zarr_vectors.exceptions import ArrayError, MetadataError, StoreError
from zarr_vectors.typing import (
    ChunkCoords,
    CrossChunkLink,
    ObjectManifest,
)

# Sentinel for read-side ``default=...`` soft-fail kwargs.  Lets callers
# distinguish "did not pass default" (caller wants the raise) from
# "passed default=None" (caller wants None back on miss).
_UNSET: Any = object()


# Discriminator written into ``object_index`` group attrs to identify
# the ragged-array layout (one vlen-bytes zarr array named ``manifests``,
# one entry per object_id).  Absent on legacy stores, which used a pair
# of single-chunk ``data`` + ``offsets`` byte blobs.
OBJECT_INDEX_LAYOUT_V1 = "vlen_manifests_v1"

#: Layout in which object ids are *stored* rather than implied by row
#: position.
#:
#: Under V1 an object id IS its row index, so the array is as long as the
#: largest id plus one and an id of twenty million allocates twenty
#: million rows for one object.  Segmentation-style 64-bit ids do not fit
#: at all, which is why ``types/skeletons.py`` -- whose ids are segment
#: ids -- has to hand-roll a sorted attribute column and binary-search it.
#:
#: Under V2 the ids live in a sibling ``object_ids`` array, one entry per
#: row, and rows are dense.  Ids may be arbitrary, sparse, and huge.
#:
#: Both layouts read through one code path, because **a V1 store is
#: simply one whose id table is the identity** -- so there is no format
#: cut here and 0.9.x stores keep reading unchanged.
OBJECT_INDEX_LAYOUT_V2 = "vlen_manifests_v2"

#: Layout in which manifests are fixed-width integer arrays rather than
#: vlen blobs; see :mod:`zarr_vectors.core.dense_manifests`. Ids are
#: stored as under V2.
OBJECT_INDEX_LAYOUT_DENSE = "dense_manifests_v1"
_LAYOUT_DENSE = OBJECT_INDEX_LAYOUT_DENSE

#: Name of the row-to-id array under ``object_index/``.
OBJECT_IDS_ARRAY = "object_ids"

#: Set on ``object_index`` when the stored ids ascend, which lets a
#: lookup binary-search them directly instead of sorting first.  Bulk
#: writers emit ids in order, so this is the common case.
OBJECT_IDS_SORTED_ATTR = "object_ids_sorted"

# Objects per zarr chunk of ``object_index/manifests``.  A single-object
# read fetches only the chunk containing the requested oid, so this sets
# the read amplification ceiling (~16K manifest blobs per fetch).
#
# Applied UNCONDITIONALLY by every writer of that array -- never clamped to
# the blob count of whichever write happens to create it.  ``resize`` cannot
# change a chunk shape, so the creating write fixes this number for the life
# of the store; see ``_write_object_index_manifests``.
OBJECT_INDEX_MANIFEST_BUCKET = 16_384

#: Most empty rows a declared id space may add to ``object_index``.
#:
#: This was a ceiling on the index's length, from when an object id was
#: the **row index** of its manifest: one object with id 20,000,000
#: allocated twenty million rows, and every whole-index operation then
#: scaled with the ids rather than the objects. Ids are stored now
#: (``object_index/object_ids``) and rows are dense, so an id sets no
#: row count, and every writer adds one row per object it is handed --
#: a ceiling on rows had become a ceiling on objects, which a whole-brain
#: build (~1.5e9) crosses with nothing wrong.
#:
#: One writer still lets an id set the row count: ``write_object_index``
#: with ``total_objects=``, which declares ``0..total_objects-1`` all
#: present, empty or not. Rows that declaration adds with no object
#: behind them are what this bounds, checked before any of them is
#: materialised: a count past 2**26 means a label or hash was passed as
#: a slot count, and building that range would hang instead of fail.
OBJECT_INDEX_MAX_ROWS = 1 << 26

#: Emit a sparsity warning once an index is this long and this empty.
_OBJECT_INDEX_SPARSE_FLOOR = 1 << 20
_OBJECT_INDEX_SPARSE_RATIO = 64

# One object manifest naming no fragments.  ``encode_object_manifest_blocks``
# emits a bare block count for an empty list, so this is the same four bytes
# whatever ``sid_ndim`` the store uses — which is what lets an append pad a
# gap without being told the coordinate rank.
_EMPTY_MANIFEST_BLOB = encode_object_manifest_blocks([], sid_ndim=1)

# Rows per zarr chunk of an ``object_attributes/<name>`` column.  Sets what an
# append rewrites: with a single chunk (the pre-0.9 layout) that is the whole
# column, so a per-spatial-chunk writer pays O(objects) on every flush.
OBJECT_ATTRIBUTE_ROW_BUCKET = 65_536


#: Rows an object-layer shard holds a whole number of. Both row buckets
#: (16,384 manifest rows, 65,536 attribute rows) tile it, so every
#: object-layer array can share one shard size.
OBJECT_SHARD_ROW_MULTIPLE = OBJECT_ATTRIBUTE_ROW_BUCKET

#: Object-layer arrays whose sharding is the level's, probed in this order.
_OBJECT_LAYER_PROBES = (
    f"{OBJECT_INDEX}/manifests",
    f"{OBJECT_INDEX}/manifest_spans",
    f"{OBJECT_INDEX}/object_ids",
    f"{OBJECT_INDEX}/manifest_blocks",
)


def check_object_shard_rows(rows: Any) -> int:
    """``rows`` as an object-layer shard size, or :class:`ArrayError`."""
    try:
        n = int(rows)
    except (TypeError, ValueError):
        n = 0
    if n <= 0 or n % OBJECT_SHARD_ROW_MULTIPLE:
        raise ArrayError(
            f"object-layer shard rows must be a positive multiple of "
            f"{OBJECT_SHARD_ROW_MULTIPLE}; got {rows!r}"
        )
    return n


def object_shard_rows(level_group: Group) -> int | None:
    """Rows per shard of the level's object layer, or ``None`` if unsharded.

    Read from the arrays' own ``zarr.json`` (``sharding_indexed``). Writers
    ask this first so a newly created object-layer array follows the
    level's existing layout.
    """
    import zarr

    def _rows(path: str) -> int | None:
        node = level_group._lookup_node(path)
        if isinstance(node, zarr.Array) and node.shards is not None:
            return int(node.shards[0])
        return None

    for path in _OBJECT_LAYER_PROBES:
        rows = _rows(path)
        if rows is not None:
            return rows
    if level_group.array_exists(OBJECT_ATTRIBUTES):
        for name in sorted(level_group[OBJECT_ATTRIBUTES].children()):
            rows = _rows(f"{OBJECT_ATTRIBUTES}/{name}")
            if rows is not None:
                return rows
    return None


def object_layer_arrays(level_group: Group) -> list[str]:
    """Paths of the level's object index arrays and object attribute columns."""
    import zarr

    paths = [
        p for p in _OBJECT_LAYER_PROBES
        if isinstance(level_group._lookup_node(p), zarr.Array)
    ]
    if level_group.array_exists(OBJECT_ATTRIBUTES):
        for name in sorted(level_group[OBJECT_ATTRIBUTES].children()):
            path = f"{OBJECT_ATTRIBUTES}/{name}"
            if isinstance(level_group._lookup_node(path), zarr.Array):
                paths.append(path)
    return paths


def _object_shards(
    level_group: Group, chunks: Sequence[int], shard_rows: int | None = None,
) -> tuple[int, ...] | None:
    """The ``shards=`` for an object-layer array chunked at ``chunks``."""
    rows = shard_rows if shard_rows is not None else object_shard_rows(level_group)
    return None if rows is None else (int(rows), *(int(c) for c in chunks[1:]))


# ===================================================================
# Helpers
# ===================================================================

def _chunk_key(coords: ChunkCoords) -> str:
    """Convert chunk coordinates to a dot-separated key string.

    ``(0, 1, 2)`` → ``"0.1.2"``
    """
    return ".".join(str(c) for c in coords)


def _parse_chunk_key(key: str) -> ChunkCoords:
    """Parse a dot-separated chunk key back to coordinates.

    ``"0.1.2"`` → ``(0, 1, 2)``
    """
    return tuple(int(x) for x in key.split("."))


def _device_result(fn=None, *, on_device: bool = False):
    """Add a keyword-only ``device=`` to a reader; moves numpy results there.

    See :mod:`zarr_vectors._xp`. Non-array results pass through untouched.
    With ``on_device``, a ``"cuda"`` read first tries the reader of the same
    name in :mod:`zarr_vectors.gpu._readers` (through ``read_cells``' device
    path), which returns ``NotImplemented`` -- or raises ``ArrayError`` or
    ``StoreError`` -- wherever the host reader should answer instead.
    """
    import functools
    import inspect

    from zarr_vectors import _xp

    if fn is None:
        return functools.partial(_device_result, on_device=on_device)

    sig = inspect.signature(fn)

    @functools.wraps(fn)
    def wrapper(*args: Any, device: str | None = None, **kwargs: Any) -> Any:
        target = _xp.resolve_device(device)
        if target == "cuda" and on_device:
            _xp._gpu()  # the extension, or the install hint
            from zarr_vectors.gpu import _readers

            bound = sig.bind(*args, **kwargs)
            bound.apply_defaults()
            try:
                got = getattr(_readers, fn.__name__)(**bound.arguments)
            except (ArrayError, StoreError):
                got = NotImplemented
            if got is not NotImplemented:
                return got
        out = fn(*args, **kwargs)
        if target == "cpu":
            return out
        if isinstance(out, np.ndarray):
            return _xp.to_device(out, target)
        if isinstance(out, tuple) and all(isinstance(o, np.ndarray) for o in out):
            return tuple(_xp.to_device(o, target) for o in out)
        return out

    params = list(sig.parameters.values())
    params.append(inspect.Parameter(
        "device", inspect.Parameter.KEYWORD_ONLY, default=None,
        annotation="str | None",
    ))
    wrapper.__signature__ = sig.replace(parameters=params)  # type: ignore[attr-defined]
    return wrapper


@contextmanager
def _maybe_batched_reads(
    level_group: Group,
    plan: list[tuple[str, list[str]]],
):
    """Open a single-chunk prefetch unless one is already active.

    Wraps :meth:`FsGroup.batched_reads` for the common "I'm about to
    read N>1 sibling arrays for one chunk" case: it fans the reads out
    in one ``asyncio.gather`` instead of paying N sequential
    round-trips.  When the caller has already entered an outer
    :meth:`batched_reads` context (i.e. a multi-chunk loop), this is a
    no-op so the outer plan stays in charge.
    """
    if level_group._prefetch_cache is not None:
        yield
        return
    with level_group.batched_reads(plan):
        yield


def _short_circuit_existing(
    level_group: Group,
    full_name: str,
    exist_ok: bool,
) -> bool:
    """Return True when ``create_*_array`` should no-op because the array
    already exists and ``exist_ok=True``.  Raises :class:`ArrayError` when
    the array exists and ``exist_ok=False``.

    Detects both layouts: the legacy group-with-chunk-arrays form
    (``array_exists``) and the single-standard-Zarr-v3-array layout
    (``standalone_array_exists``).

    When the caller is running inside
    :meth:`Group.native_sharded_arrays` and the existing node is a
    legacy group at a per-chunk-array path, *do not*
    short-circuit — the create call needs to replace the legacy group
    with a native-sharded Zarr array.  This matters when the store
    was warmed via :func:`create_store` (which writes an empty
    ``vertices/`` group) and the caller is the first writer to request
    sharded layout.
    """
    exists_as_array = level_group.standalone_array_exists(full_name)
    exists_as_group = (
        level_group.array_exists(full_name) and not exists_as_array
    )
    if not (exists_as_array or exists_as_group):
        return False

    # Legacy group at a per-chunk-array path, inside a sharded
    # writer — fall through so ``_ensure_array_dir`` replaces it.
    if (
        exists_as_group
        and level_group._native_sharded_config is not None
        and _is_per_chunk_array(full_name)
    ):
        return False

    # A single vlen array already exists but an explicit session wants a
    # different layout (e.g. the warm-created unsharded ``vertices`` is
    # now being written with ``shard_shape=``).  Fall through so
    # ``_ensure_array_dir`` recreates it to match the requested layout.
    if (
        exists_as_array
        and level_group._native_sharded_config is not None
        and _is_per_chunk_array(full_name)
        and not _array_matches_layout(
            level_group, full_name, level_group._native_sharded_config
        )
    ):
        return False

    if exist_ok:
        return True
    raise ArrayError(
        f"{full_name!r} already exists; pass exist_ok=True to ignore"
    )


def _default_fill_value_for_dtype(dtype: np.dtype) -> Any:
    """Pick the conventional 'absent' sentinel for a numpy dtype.

    Returns a Python-native value used both as the in-array marker for
    rows excluded by a caller-supplied ``present_mask`` and as the Zarr
    array's persisted ``fill_value`` (so unwritten chunks read back as
    the same value).

    Conventions:
        * float dtypes → ``NaN``
        * signed-int dtypes → the dtype's minimum value
        * unsigned-int dtypes → the dtype's maximum value

    Bool and other dtypes have no in-band sentinel; callers must
    promote (e.g. ``bool`` → ``int8`` with explicit ``fill_value=-1``)
    or pass an explicit ``fill_value=`` to the writer.
    """
    if dtype.kind == "f":
        return float("nan")
    if dtype.kind == "i":
        return int(np.iinfo(dtype).min)
    if dtype.kind == "u":
        return int(np.iinfo(dtype).max)
    if dtype.kind in ("U", "S"):
        # Empty string as the absence marker.  Documented caveat:
        # collides with a legitimate empty value; callers that care
        # must pass ``fill_value=`` explicitly.
        return ""
    raise ArrayError(
        f"no default 'absent' fill_value for dtype {dtype!r}; "
        f"pass fill_value= explicitly (or promote bool → int8)"
    )


_UNSET = object()


def _leading_grid_axes(
    level_group: Group, level_meta: Any, spatial_rank: int,
) -> tuple[int, ...]:
    """Extents of the level's non-spatial leading grid axes (``()`` if none).

    Taken from the allocated ``vertices`` array's extra axes, else from
    ``len(chunk_attribute_values)``; ``chunk_dims`` is not consulted.
    """
    arr = level_group._sharded_chunk_array(VERTICES)
    if arr is not None and arr.ndim > spatial_rank:
        return tuple(int(x) for x in arr.shape[: arr.ndim - spatial_rank])

    values = getattr(level_meta, "chunk_attribute_values", None)
    if values:
        return (len(values),)

    return ()


def _derive_native_config(level_group: Group) -> dict[str, Any] | None:
    """Best-effort single-array grid config from the store's metadata.

    Lets writers that don't open an explicit
    :func:`open_write_session` (multiresolution coarsen, rechunk, lazy
    append, in-place edits that add a new array) still produce the
    single vlen-array layout.  Derives ``(origin, grid_shape)`` from the
    root ``bounds`` and the level's effective ``chunk_shape``.

    Returns ``None`` when that metadata can't be read — e.g. a bare
    ``Group`` with no root metadata.  There is no per-cell group
    primitive to fall back to: :meth:`Group.write_bytes` requires an
    allocated chunk array and raises otherwise.  A ``None`` here therefore
    means a grid-shaped array cannot be allocated at all, which is
    intrinsic rather than incidental — the grid is precisely what the
    missing metadata would have supplied.

    Cached on the ``level_group`` instance for the object's lifetime.
    """
    cached = level_group.__dict__.get("_derived_native_config", _UNSET)
    if cached is not _UNSET:
        return cached

    cfg: dict[str, Any] | None
    try:
        import zarr

        from zarr_vectors.core.metadata import (
            LevelMetadata,
            get_level_chunk_shape,
            normalise_shard_shape,
        )
        from zarr_vectors.core.store import read_root_metadata

        store = level_group._zarr.store
        root_zarr = zarr.open_group(store, path="/", mode="r", zarr_format=3)
        root_group = type(level_group)._from_zarr(root_zarr)
        root_meta = read_root_metadata(root_group)
        try:
            level_meta = LevelMetadata.from_dict(level_group.attrs.to_dict())
        except (MetadataError, KeyError, ValueError, TypeError):
            # Narrow: a blanket except here drops the bin axis below and
            # silently allocates at the spatial rank, which is the bug
            # this function's leading-axis handling exists to fix.
            level_meta = None
        chunk_shape = get_level_chunk_shape(root_meta, level_meta)
        origin, grid_shape = level_grid_layout(root_meta.bounds, chunk_shape)
        # A level chunked by an attribute carries leading bin axes that
        # the spatial derivation above knows nothing about.  Prepending
        # them here is what makes an array allocated WITHOUT a write
        # session -- an attribute array created by a decentralised worker,
        # a links segment created by an edit -- come out at the same rank
        # as the level's own keys.  Mirrors ``open_write_session``'s
        # ``bin_count`` handling, including anchoring the bin axis at 0.
        leading = _leading_grid_axes(level_group, level_meta, len(grid_shape))
        origin = (*((0,) * len(leading)), *origin)
        grid_shape = (*leading, *grid_shape)
        cfg = {
            "origin": origin,
            "grid_shape": grid_shape,
            # The store's declared packing. Reading it HERE is what
            # reaches the arrays nobody passed it to: a links segment or
            # attribute array allocated on first write, in a worker that
            # never saw create_store's arguments. Without it a store came
            # out sharded in whatever the coordinator made and flat in
            # everything else.
            "shard_shape": normalise_shard_shape(
                root_meta.shard_shape, len(grid_shape),
                bin_axis=bool(leading),
            ),
        }
    except (StoreError, MetadataError, KeyError, ValueError, TypeError):
        # Narrow deliberately. This branch means "the grid cannot be
        # derived", and it used to swallow everything -- including a
        # failure to read the shard declaration, which would silently
        # produce flat arrays in a store that asked to be sharded. That
        # is the bug this function exists to fix, so it must not be the
        # way the fix fails.
        cfg = None

    level_group.__dict__["_derived_native_config"] = cfg
    return cfg


def _derive_level_scales(
    level_group: Group, delta: int,
) -> tuple[tuple[int, ...], tuple[int, ...]]:
    """Return ``(scale_src, scale_trg)`` for records spanning ``delta`` levels.

    Each is the per-axis integer multiple of the root ``chunk_shape`` that
    the relevant level's ``chunk_shape`` represents — ``r_src`` for the
    owning level, ``r_trg`` for ``owning + delta``.
    :func:`zarr_vectors.spatial.boundary.anchor_chunk` needs both to make
    a cross-level chunk offset well-defined: when the two levels carry
    different ``chunk_shape`` (a per-level override written by
    ``coarsen`` under ``chunk_scale_factor > 1``) their chunk coords index
    grids of different cell sizes and cannot be differenced directly.

    Returns all-ones for both when the metadata cannot be read, or when
    the target level does not exist yet.  All-ones is exactly right for a
    default pyramid (``chunk_scale_factor=1``), where every level inherits
    the root ``chunk_shape`` — and it makes the anchor a no-op, which is
    the pre-merge behaviour.  It is *wrong* for a scaled pyramid, so this
    mirrors :func:`_derive_native_config`'s best-effort contract: callers
    on a scaled store must be reachable from real metadata.
    """
    ndim_fallback: tuple[int, ...]
    try:
        import zarr

        from zarr_vectors.core.metadata import (
            LevelMetadata,
            chunk_scale_from_root,
        )
        from zarr_vectors.core.store import read_root_metadata

        store = level_group._zarr.store
        root_zarr = zarr.open_group(store, path="/", mode="r", zarr_format=3)
        root_group = type(level_group)._from_zarr(root_zarr)
        root_meta = read_root_metadata(root_group)
        ndim_fallback = tuple(1 for _ in root_meta.chunk_shape)

        src_meta = LevelMetadata.from_dict(level_group.attrs.to_dict())
        scale_src = chunk_scale_from_root(root_meta, src_meta)
        if delta == 0:
            return scale_src, scale_src

        from zarr_vectors.core.store import (
            get_resolution_level,
            read_level_metadata,
        )

        target_idx = int(src_meta.level) + int(delta)
        try:
            get_resolution_level(root_group, target_idx)
            trg_meta = read_level_metadata(root_group, target_idx)
        except Exception:
            # Target level not written yet (pyramid still being built):
            # fall back to the source's own scale, which is correct
            # whenever the pyramid is uniform.
            return scale_src, scale_src
        return scale_src, chunk_scale_from_root(root_meta, trg_meta)
    except Exception:
        try:
            ndim_fallback
        except NameError:
            ndim_fallback = (1, 1, 1)
        return ndim_fallback, ndim_fallback


def _refuse_octree_allocation(level_group: Group, array_name: str) -> None:
    """Refuse allocating an array on a level with octree chunks, before
    anything is created (see :mod:`zarr_vectors.octree_chunks.guard`)."""
    from zarr_vectors.octree_chunks.guard import refuse_octree_write

    refuse_octree_write(level_group, f"allocating {array_name}")


def _ensure_array_dir(
    level_group: Group,
    array_name: str,
    *,
    attributes: dict[str, Any] | None = None,
) -> None:
    """Ensure an array node exists within a level group.

    For per-spatial-chunk arrays (vertices, fragments,
    ``links/<delta>/<offsets>``, attribute arrays) this allocates a single
    multidim vlen-bytes Zarr array (one cell per spatial chunk) — the
    default single-array layout.  The grid comes from the active
    :func:`open_write_session` when one is open, else it is derived from
    the store's metadata (so coarsen / rechunk / edit paths get
    single-array too).

    Non-per-chunk names (``object_index``, the ``links/<delta>`` family
    group, attribute *namespace* groups) become plain Zarr groups.  Which
    is which is decided by :func:`_is_per_chunk_array`, and it is
    depth-aware: ``links/0`` is a group, ``links/0/0.0.+1`` an array.
    Under an
    active :meth:`Group.batched_writes`, the sync ``require_group``
    round-trip is skipped — the metadata flush PUTs the parent
    ``zarr.json`` directly.

    ``attributes`` is the array's own metadata block.  Passing it here
    rather than calling :meth:`Group.write_array_meta` afterwards is what
    keeps allocation to a single store write: the attrs ride along with
    the ``create_array`` that writes ``zarr.json`` anyway, instead of
    rewriting the whole object a second time.  A writer that allocates one
    array per offsets segment pays that saving per segment.  When the
    array already exists it is *not* recreated, so the metadata is applied
    with a normal write — same end state either way.
    """
    _refuse_octree_allocation(level_group, array_name)
    explicit_cfg = level_group._native_sharded_config
    cfg = explicit_cfg
    if cfg is None and _is_per_chunk_array(array_name):
        # No explicit session — derive the grid from metadata so this
        # write path still produces a single vlen array.
        cfg = _derive_native_config(level_group)
    if cfg is not None and _is_per_chunk_array(array_name):
        if level_group.standalone_array_exists(array_name):
            # An array is already here.  Under the derived path (no
            # explicit session) always reuse it — recreating would drop
            # existing cells (e.g. an edit adding a chunk).  Under an
            # explicit session, reuse only when the on-disk layout
            # already matches the requested grid/sharding; otherwise
            # recreate to honor the writer's intent (e.g. a store whose
            # ``vertices`` was warm-created unsharded but is now being
            # written with ``shard_shape=``).
            if explicit_cfg is None or _array_matches_layout(
                level_group, array_name, explicit_cfg
            ):
                # Reused as-is: the attrs can't ride a create_array that
                # isn't happening, so apply them directly.
                if attributes:
                    level_group.write_array_meta(array_name, attributes)
                return
        # Honor the session compressor so the array's codec pipeline
        # matches the batched default (no compression) unless the
        # caller asked for zstd/blosc.
        compressors = None
        if level_group._active_codecs is not None:
            from zarr_vectors.encoding.compression import (
                codecs_for_create_array,
            )
            compressors = codecs_for_create_array(
                level_group._active_codecs
            )
        level_group.create_sharded_chunk_array(
            array_name,
            grid_shape=cfg["grid_shape"],
            shard_shape=cfg.get("shard_shape"),
            origin=cfg.get("origin"),
            compressors=compressors,
            attributes=attributes,
        )
        return
    # A group node, not a chunk array: nothing to ride along with, so any
    # metadata is written normally rather than dropped.
    if attributes:
        level_group.write_array_meta(array_name, attributes)
        return
    if level_group._pending_array_metas is not None:
        return
    level_group.require_group(array_name)


def _ensure_chunk_arrays(
    level_group: Group,
    arrays: Sequence[tuple[str, dict[str, Any] | None]],
) -> None:
    """:func:`_ensure_array_dir` for several per-chunk arrays at once.

    The grid is derived once and every array that has to be created is
    created in one gather; an array that already holds the requested
    layout is reused and only has its metadata applied, exactly as the
    singular form does.  Names that are not per-chunk arrays fall
    through to the singular form.
    """
    if not arrays:
        return
    _refuse_octree_allocation(level_group, arrays[0][0])
    explicit_cfg = level_group._native_sharded_config
    cfg = explicit_cfg if explicit_cfg is not None else _derive_native_config(level_group)
    to_create: list[tuple[str, dict[str, Any] | None]] = []
    replace: set[str] = set()
    for array_name, attributes in arrays:
        if cfg is None or not _is_per_chunk_array(array_name):
            _ensure_array_dir(level_group, array_name, attributes=attributes)
            continue
        if level_group.standalone_array_exists(array_name):
            if explicit_cfg is None or _array_matches_layout(
                level_group, array_name, explicit_cfg
            ):
                if attributes:
                    level_group.write_array_meta(array_name, attributes)
                continue
            replace.add(array_name)
        to_create.append((array_name, attributes))
    if not to_create:
        return
    compressors = None
    if level_group._active_codecs is not None:
        from zarr_vectors.encoding.compression import codecs_for_create_array

        compressors = codecs_for_create_array(level_group._active_codecs)
    level_group.create_sharded_chunk_arrays(
        to_create,
        grid_shape=cfg["grid_shape"],
        shard_shape=cfg["shard_shape"],
        origin=cfg.get("origin"),
        compressors=compressors,
        replace=replace,
    )


def _array_matches_layout(
    level_group: Group, array_name: str, cfg: dict[str, Any],
) -> bool:
    """Whether an existing vlen array is reused rather than recreated to match ``cfg``.

    Empty arrays (checked in the store, not just ``nonempty_chunks``) are
    recreated; arrays holding data are always reused, with a warning on mismatch.
    """
    existing = level_group._sharded_chunk_array(array_name)
    if existing is None:
        return False

    # A "no" from the manifest can't be trusted (record_presence=False,
    # lost updates), so only that answer is checked against the store.
    if _zvc.get_field(existing.attrs, "nonempty_chunks"):
        has_data = True
    else:
        has_data = level_group._array_has_stored_data(array_name)

    # Recreate even if grid and sharding agree, to apply the session's codecs.
    if not has_data:
        return False

    desired_sharded = cfg.get("shard_shape") is not None
    existing_sharded = getattr(existing, "shards", None) is not None
    if (
        tuple(existing.shape) == tuple(cfg["grid_shape"])
        and existing_sharded == desired_sharded
    ):
        return True

    warnings.warn(
        f"{array_name!r} in {level_group._zarr.path or '<root>'} already "
        f"holds data with a different layout "
        f"(grid {tuple(existing.shape)}, "
        f"{'sharded' if existing_sharded else 'unsharded'}) than this write "
        f"session requests (grid {tuple(cfg['grid_shape'])}, "
        f"{'sharded' if desired_sharded else 'unsharded'}); reusing it as-is. "
        f"Recreating it would delete the data. Use "
        f"zarr_vectors.sharding.reshard() to change an existing store's "
        f"layout.",
        RuntimeWarning,
        stacklevel=3,
    )
    return True


def level_grid_layout(
    bounds: tuple[list[float], list[float]],
    chunk_shape: tuple[float, ...],
) -> tuple[tuple[int, ...], tuple[int, ...]]:
    """Return ``(origin, grid_shape)`` for a level's single vlen arrays.

    :func:`zarr_vectors.spatial.chunking.assign_chunks` maps a position
    to the *absolute* coord ``floor(pos / chunk_shape)``.  When the data
    extends below the origin (negative positions), those coords are
    negative — which a 0-indexed Zarr array cannot hold directly.  We
    therefore anchor the array at ``origin = floor(min_corner /
    chunk_shape)`` (per axis) and store that offset on the array, so
    cell ``index = coord - origin`` and the array only needs to span
    ``floor(max_corner / chunk_shape) - origin + 1`` cells.  Using
    ``ceil(max_corner / chunk_shape)`` would also be one short whenever a
    point lands exactly on a chunk boundary — ``floor(..) + 1`` is exact.
    """
    from zarr_vectors.spatial.chunking import grid_layout

    # One definition, in the pure-numpy module, so the api's Grid can
    # predict this allocation by calling it rather than by restating it.
    return grid_layout((bounds[0], bounds[1]), chunk_shape)


@contextmanager
def open_write_session(
    level_group: Group,
    *,
    compressor: Any = None,
    shard_shape: int | tuple[int, ...] | None | Literal["inherit"] = "inherit",
    bounds: tuple[list[float], list[float]] | None = None,
    chunk_shape: tuple[float, ...] | None = None,
    bin_count: int | None = None,
    durable: bool | str = False,
):
    """Open the write session used by every type writer.

    Always activates the single-array layout: each per-spatial-chunk
    array (vertices, vertex_fragments, links/<delta>, link_fragments,
    vertex_attributes/<name>, …) is one multidim vlen-bytes Zarr array
    whose cells are spatial chunks (files at ``<array>/c/i/j/k``), and a
    batched-write context flushes every cell of an array in one
    concurrent :meth:`~zarr.Array.set_coordinate_selection`.

    ``bounds`` and ``chunk_shape`` are required so the chunk-grid extent
    (and origin offset, for data with negative coords) can be sized
    upfront — that's the shape of each vlen array.

    Args:
        level_group: The resolution-level group.
        compressor: Forwarded to :meth:`Group.batched_writes`; also
            determines each array's on-disk codec pipeline (``None`` →
            no compression, the default).
        shard_shape: ``"inherit"`` (the default) takes the store's own
            declaration, so a session opened against a sharded store
            stays sharded without every caller having to repeat the
            argument.  An int (broadcast to every axis) or a per-axis
            tuple wraps the cells in the ``sharding_indexed`` codec so
            many chunks pack into one storage object.  ``None`` means
            *explicitly* unsharded, one storage object per spatial chunk.

            The ``"inherit"`` sentinel keeps "I did not say" apart from
            "I said no": only an explicit ``None`` asks for an unsharded
            array.
        bounds: ``(min_corner, max_corner)`` for the level — used to
            compute the chunk grid extent and origin.
        chunk_shape: Physical chunk size per axis — paired with
            ``bounds`` for the grid extent.
        bin_count: When the writer chunks by an attribute, every chunk
            key gains a leading attr-bin axis; pass the number of bins
            so the vlen array grid gets that extra leading axis
            (origin 0, extent ``bin_count``).
        durable: Forwarded to :meth:`Group.batched_writes`: on a local
            store, everything the session wrote is fsynced -- each cell
            object before its rename -- before the block returns.
            ``"deferred"`` writes atomically without fsyncing; the caller
            makes the writes durable later with
            :func:`zarr_vectors.building.sync_store`.
    """
    from contextlib import ExitStack

    from zarr_vectors.octree_chunks.guard import refuse_octree_write

    # Before anything is allocated or stamped: a session addresses
    # uniform cells, which an octree level does not have.
    refuse_octree_write(level_group, "a write session")
    if bounds is None or chunk_shape is None:
        raise ArrayError(
            "open_write_session requires `bounds` and `chunk_shape` so "
            "the per-axis chunk-grid extent can be computed"
        )

    origin, grid_shape = level_grid_layout(bounds, chunk_shape)
    if bin_count is not None:
        # chunk_by_attribute prepends a 0-based bin axis to every key.
        origin = (0, *origin)
        grid_shape = (int(bin_count), *grid_shape)

    from zarr_vectors.core.metadata import normalise_shard_shape

    if shard_shape == "inherit":
        cfg = _derive_native_config(level_group)
        declared = cfg.get("shard_shape") if cfg else None
        # Already normalised against the SPATIAL grid by the derive; the
        # bin axis, if any, is prepended below by the same rule.
        shard_shape = list(declared) if declared is not None else None
    ss = normalise_shard_shape(
        shard_shape, len(grid_shape), bin_axis=bin_count is not None,
    )

    _warn_on_cell_count(grid_shape, sharded=ss is not None)

    stack = ExitStack()
    with stack:
        stack.enter_context(
            level_group.batched_writes(compressor=compressor, durable=durable),
        )
        stack.enter_context(
            level_group.native_sharded_arrays(ss, grid_shape, origin=origin)
        )
        yield


#: Cell count above which a level's chunk_shape is worth questioning.
#:
#: An unsharded cell is one object in the store, and the per-cell cost of
#: writing one is fixed -- it does not shrink because the cell is nearly
#: empty.  Past this many cells the layout, not the data, is what a write
#: is spending its time on.
_CELL_COUNT_WARN = 100_000


def _warn_on_cell_count(grid_shape: tuple[int, ...], *, sharded: bool) -> None:
    """Say so when a chunk_shape allocates an unworkable number of cells.

    The automatic :class:`~zarr_vectors.api.schema.Layout` already targets
    a cell size rather than a cell count, but a caller-supplied
    ``chunk_shape`` gets no such check, and the failure mode is silent:
    the write simply takes a very long time and leaves a directory tree
    with one file per cell.
    """
    total = 1
    for s in grid_shape:
        total *= int(s)
    if total <= _CELL_COUNT_WARN:
        return
    remedy = (
        "Consider a coarser chunk_shape"
        if sharded else
        "Consider a coarser chunk_shape, or shard_store() to pack cells "
        "into shard objects"
    )
    warnings.warn(
        f"This chunk_shape allocates a {'x'.join(str(s) for s in grid_shape)} "
        f"grid = {total:,} cells"
        f"{'' if sharded else ', each a separate object in the store'}. "
        f"The per-cell cost of a write is fixed, so it is the cell count "
        f"rather than the vertex count that sets the time. {remedy}.",
        RuntimeWarning,
        stacklevel=4,
    )


def _is_per_chunk_array(name: str) -> bool:
    """Whether ``name`` is a per-spatial-chunk array.

    These become a single vlen-bytes Zarr array whose shape is the
    level's chunk grid — one cell per spatial chunk (file at
    ``<name>/c/i/j/k``).  Object-level arrays (``object_index``,
    ``object_attributes/...``, ``groups``, ``group_attributes/...``) are
    plain single arrays that do **not** use this grid layout.

    The test is **depth-aware**, not a prefix match, because the link
    families nest a group above their arrays: ``links/<delta>`` is a
    *group* whose children are one array per relative-offset segment
    (``links/<delta>/<offsets>``).  A prefix test would match both and
    :func:`_ensure_array_dir` would clobber the group with an array.

        vertices                                    array
        links/0                                     GROUP
        links/0/0.0.+1                              array
        link_attributes/weight/0                    GROUP
        link_attributes/weight/0/0.0.+1             array

    Note this predicate does double duty: :mod:`zarr_vectors.sharding.io`
    imports it to decide what ``shard_store`` may migrate.  Both link
    families are rank-D grids now, so they shard like any other.
    """
    if name in {VERTICES, VERTEX_FRAGMENTS, LINK_FRAGMENTS}:
        return True
    parts = name.split("/")
    # Composite stores namespace one vertices array per geometry kind,
    # ``vertices_<geometry_type>``.  Same chunk grid and same vlen-bytes
    # layout as ``vertices`` -- only the name is qualified -- so the same
    # answer has to come back for it, or ``_ensure_array_dir`` allocates a
    # group and every later ``write_bytes`` to it raises.
    if len(parts) == 1 and name.startswith(VERTICES + "_"):
        return True
    if len(parts) == 2 and parts[0] in (VERTEX_ATTRIBUTES, FRAGMENT_ATTRIBUTES):
        return True
    # links/<delta>/<offsets>
    if len(parts) == 3 and parts[0] == LINKS:
        return True
    # link_attributes/<name>/<delta>/<offsets>
    if len(parts) == 4 and parts[0] == LINK_ATTRIBUTES:
        return True
    return False


def read_zv_array_tag(meta: dict) -> str | None:
    """Return the discriminator string from an array's attributes dict.

    Looks under ``zv_array`` first and falls back to ``zvf_array``, the
    key older stores carry.  Use
    this helper instead of indexing the dict directly so that conformance
    / validation code keeps working against existing-on-disk stores.
    """
    return meta.get("zv_array", meta.get("zvf_array"))


# ===================================================================
# Array creation (set up directory + metadata)
# ===================================================================

def create_vertices_array(
    level_group: Group,
    dtype: str = "float32",
    encoding: str = "raw",
    *,
    exist_ok: bool = True,
) -> None:
    """Create the ``vertices/`` array within a resolution level.

    Args:
        level_group: The resolution level FsGroup.
        dtype: Numpy dtype string for vertex positions.
        encoding: ``"raw"`` or ``"draco"``.
        exist_ok: When True (default), no-op if the array already exists.
            When False, raise :class:`ArrayError` on conflict.
    """
    if _short_circuit_existing(level_group, VERTICES, exist_ok):
        return
    _ensure_array_dir(level_group, VERTICES)
    _ensure_array_dir(level_group, VERTEX_FRAGMENTS)
    level_group.write_array_meta(VERTICES, {
        "zv_array": "vertices",
        "dtype": dtype,
        "encoding": encoding,
    })
    level_group.write_array_meta(VERTEX_FRAGMENTS, {
        "zv_array": VERTEX_FRAGMENTS,
        "encoding": "fragment_index_v1",
    })


def links_has_perm(
    offsets: Sequence[ChunkCoords],
    *,
    delta: int,
    directed: bool,
    store: str,
) -> bool:
    """Whether ``links/<delta>/<offsets>/`` rows carry a ``perm_idx`` column.

    ``perm_idx`` exists only to undo a canonical sort, so it is needed
    exactly when :func:`zarr_vectors.spatial.boundary._cell_placements`
    may return a non-identity permutation.  Storing it unconditionally
    would add 8 bytes to every intra-chunk link — the overwhelming
    majority of rows — for a value that is always 0.

    Keep this in lockstep with ``_cell_placements``: it is the single
    definition the writer and reader both consult to agree on the record
    width (``L`` columns, or ``1 + L`` when this returns True).
    """
    if is_intra(offsets):
        # Every endpoint in the source chunk: identity placement, input
        # order preserved.  This is what keeps the all-zero-offsets array
        # byte-identical to the pre-merge ``links/<delta>/``.
        return False
    if delta != 0:
        # Cross-level: endpoints are distinguished by level, so the source
        # is always input endpoint 0 and the placement is the identity.
        return False
    if store == "duplicate":
        # Each copy leads with a different endpoint, so sigma varies.
        return True
    return not directed


def create_links_family(
    level_group: Group,
    *,
    delta: int = 0,
    link_width: int = 2,
    sid_ndim: int | None = None,
    directed: bool = False,
    store: str = "canonical",
) -> None:
    """Stamp the ``links/<delta>/`` family group's policy, nothing else.

    ``directed`` / ``store`` / ``link_width`` / ``sid_ndim`` are
    family-wide: every offsets array under the delta decodes against them,
    which is why they live on the group and why
    :func:`write_links` refuses to flip them under surviving siblings.

    Use this when the policy must exist before any offsets array does —
    principally the decentralized flow, where a coordinator fixes the
    policy up front and workers then create only the offsets arrays their
    own records land in.  :func:`create_links_array` would otherwise force
    a family to materialise an arbitrary (usually intra) array purely to
    carry the group stamp, which a cross-only family does not want.

    Idempotent, and merges rather than overwrites: an existing group keeps
    any counts :func:`finalize_links` left on it.

    Raises:
        ArrayError: If ``store`` is not ``"canonical"`` or ``"duplicate"``,
            or if the family already exists with a conflicting policy —
            silently re-stamping would strand every array already written
            under the old one.
    """
    if store not in ("canonical", "duplicate"):
        raise ArrayError(
            f"store must be 'canonical' or 'duplicate', got {store!r}"
        )
    family = links_group_path(delta)
    existing = (
        level_group.read_array_meta(family) or {}
        if level_group.array_exists(family) else {}
    )
    if existing:
        _check_link_family_policy(
            existing, delta=delta, link_width=link_width, sid_ndim=sid_ndim,
            directed=directed, store=store, action="re-stamp",
        )
    meta = dict(existing)
    meta.update({
        "zv_array": "links_family",
        "level_delta": int(delta),
        "link_width": int(link_width),
        "directed": bool(directed),
        "store": str(store),
    })
    if sid_ndim is not None:
        meta["sid_ndim"] = int(sid_ndim)
    _ensure_array_dir(level_group, family)
    level_group.write_array_meta(family, meta)


def create_links_array(
    level_group: Group,
    link_width: int,
    dtype: str = "int64",
    *,
    delta: int = 0,
    sid_ndim: int | None = None,
    offsets: Sequence[ChunkCoords] | None = None,
    directed: bool = False,
    store: str = "canonical",
    exist_ok: bool = True,
) -> None:
    """Create a ``links/<delta>/<offsets>/`` array and its family group.

    To stamp the family policy *without* materialising any offsets array
    — a cross-only family, or a coordinator fixing policy before workers
    run — use :func:`create_links_family` instead.

    Each ``<delta>`` segment is a group; its children are one rank-D vlen
    array per distinct relative-offset segment, each cell holding the
    records whose **source** chunk is that cell.  ``offsets`` all-zero is
    the intra-chunk array (what was a standalone ``links/<delta>/`` array
    before the offset layout); non-zero offsets hold records whose other
    endpoints sit that far away — what used to be ``cross_chunk_links/``.

    Family-wide policy (``directed``, ``store``, ``sid_ndim``,
    ``link_width``) is stamped on the ``<delta>`` **group**, since several
    arrays now live under it and must agree.  Per-array meta carries only
    what is needed to decode that array's own cells.

    Args:
        level_group: The resolution level FsGroup.
        link_width: Number of vertex indices per link entry (L).
            1 for skeleton parents, 2 for edges, 3 for triangle faces.
        dtype: Integer dtype.
        delta: Level delta; see :mod:`zarr_vectors.core.paths`.
        sid_ndim: Spatial index dims.  Required when ``offsets`` is None
            so the intra segment can be derived.
        offsets: The ``link_width - 1`` relative offsets naming this
            array.  Defaults to the all-zero (intra-chunk) offsets.
        directed: Endpoint order is data; see
            :func:`zarr_vectors.spatial.boundary._cell_placements`.
        store: ``"canonical"`` or ``"duplicate"``.
        exist_ok: When True (default), no-op if the array already exists.
            When False, raise :class:`ArrayError` on conflict.
    """
    if store not in ("canonical", "duplicate"):
        raise ArrayError(
            f"store must be 'canonical' or 'duplicate', got {store!r}"
        )
    if offsets is None:
        if sid_ndim is None:
            raise ArrayError(
                "create_links_array requires sid_ndim when offsets is None "
                "(needed to derive the intra-chunk offsets segment)"
            )
        offsets = intra_offsets(sid_ndim, link_width)
    if sid_ndim is None and offsets:
        sid_ndim = len(offsets[0])

    family = links_group_path(delta)
    full_name = links_path(delta, offsets)
    if _short_circuit_existing(level_group, full_name, exist_ok):
        return
    # Capture whether the family group's policy meta already exists BEFORE
    # allocating the offsets array (which creates the group as a side effect).
    # Re-stamping the family group's zarr.json on every offsets-array creation
    # makes concurrent decentralized writers (each creating a DIFFERENT offsets
    # array) collide on the group's atomic-rename — a Windows hard-fail.  A
    # coordinator (:func:`create_links_family`) or the first creator establishes
    # the policy; later creators only add their offsets array under it.
    existing_family = (
        level_group.read_array_meta(family) or {}
        if level_group.array_exists(family) else {}
    )
    if existing_family:
        _check_link_family_policy(
            existing_family, delta=delta, link_width=link_width,
            sid_ndim=sid_ndim, directed=directed, store=store,
            action="append to",
        )
    # Hand the array's metadata to the allocation itself: one offsets
    # array per distinct offset means this runs once per segment, and
    # writing the meta separately would double the store writes for it.
    _ensure_array_dir(level_group, full_name, attributes={
        "zv_array": "links",
        "dtype": dtype,
        "offsets": [list(int(c) for c in o) for o in offsets],
        "has_perm": links_has_perm(
            offsets, delta=delta, directed=directed, store=store,
        ),
        "link_width": link_width,
        "level_delta": int(delta),
    })
    if not existing_family:
        family_meta: dict[str, Any] = {
            "zv_array": "links_family",
            "level_delta": int(delta),
            "link_width": int(link_width),
            "directed": bool(directed),
            "store": str(store),
        }
        if sid_ndim is not None:
            family_meta["sid_ndim"] = int(sid_ndim)
        level_group.write_array_meta(family, family_meta)

    # Allocate the fragment sidecar next to the intra array, mirroring how
    # create_vertices_array allocates vertex_fragments next to vertices.  The
    # intra array at delta 0 is the only one that uses it (see
    # write_chunk_links), which would otherwise create it lazily on first
    # write — from inside a worker, where concurrent creators race on its
    # zarr.json.  Allocating here keeps creation a coordinator concern.
    if (
        delta == 0
        and is_intra(offsets)
        and not level_group.array_exists(LINK_FRAGMENTS)
    ):
        _ensure_array_dir(level_group, LINK_FRAGMENTS)
        level_group.write_array_meta(LINK_FRAGMENTS, {
            "zv_array": LINK_FRAGMENTS,
            "encoding": "fragment_index_v1",
        })


def _create_links_arrays(
    level_group: Group,
    offsets_list: Sequence[Sequence[ChunkCoords]],
    *,
    link_width: int,
    dtype: str,
    delta: int,
    sid_ndim: int,
    directed: bool,
    store: str,
) -> None:
    """:func:`create_links_array` for every offsets segment of one write.

    Same checks, same metadata, one allocation: the family policy is
    checked once, every array that does not yet exist is created in a
    single gather (see :meth:`Group.create_sharded_chunk_arrays`), and
    the family group and fragment sidecar are stamped once.
    """
    if not offsets_list:
        return
    family = links_group_path(delta)
    existing_family = (
        level_group.read_array_meta(family) or {}
        if level_group.array_exists(family) else {}
    )
    if existing_family:
        _check_link_family_policy(
            existing_family, delta=delta, link_width=link_width,
            sid_ndim=sid_ndim, directed=directed, store=store,
            action="append to",
        )
    wanted: list[tuple[str, dict[str, Any]]] = []
    seen: set[str] = set()
    for offsets in offsets_list:
        full_name = links_path(delta, offsets)
        if full_name in seen:
            continue
        seen.add(full_name)
        # A family that does not exist yet has no arrays under it, so
        # the two store probes an existence check costs per segment are
        # skipped for it: on a fresh family of 1,700 segments they were
        # 2.5 s of the write.
        if existing_family and _short_circuit_existing(level_group, full_name, True):
            continue
        wanted.append((full_name, {
            "zv_array": "links",
            "dtype": dtype,
            "offsets": [list(int(c) for c in o) for o in offsets],
            "has_perm": links_has_perm(
                offsets, delta=delta, directed=directed, store=store,
            ),
            "link_width": link_width,
            "level_delta": int(delta),
        }))
    if not wanted:
        return
    _ensure_chunk_arrays(level_group, wanted)
    if not existing_family:
        family_meta: dict[str, Any] = {
            "zv_array": "links_family",
            "level_delta": int(delta),
            "link_width": int(link_width),
            "directed": bool(directed),
            "store": str(store),
        }
        if sid_ndim is not None:
            family_meta["sid_ndim"] = int(sid_ndim)
        level_group.write_array_meta(family, family_meta)
    if (
        delta == 0
        and any(is_intra(o) for o in offsets_list)
        and not level_group.array_exists(LINK_FRAGMENTS)
    ):
        _ensure_array_dir(level_group, LINK_FRAGMENTS)
        level_group.write_array_meta(LINK_FRAGMENTS, {
            "zv_array": LINK_FRAGMENTS,
            "encoding": "fragment_index_v1",
        })


def create_attribute_array(
    level_group: Group,
    name: str,
    dtype: str = "float32",
    channel_names: list[str] | None = None,
    ncols: int | None = None,
    extra_meta: dict[str, Any] | None = None,
    *,
    exist_ok: bool = True,
    register_family: bool = False,
) -> None:
    """Create a vertex attribute array ``attributes/<name>/``.

    Args:
        level_group: The resolution level FsGroup.
        name: Attribute name (e.g. ``"radius"``, ``"gene_expression"``).
        dtype: Numpy dtype string.
        channel_names: Optional list of channel names.  Supplying
            these declares the width; ``ncols`` is only needed for a
            multi-column attribute whose channels are unnamed.
        ncols: Columns per row.  ``None`` (default) infers from
            ``channel_names``, else 1.
        extra_meta: Additional JSON-serialisable fields merged into the
            array metadata.  Used for the dictionary-encoding
            convention (``encoding="dictionary"``, ``categories``,
            ``ordered``, ``_FillValue``) and other userspace
            extensions.  Keys collide-check against the core fields
            (``zv_array``, ``name``, ``dtype``, ``channel_names``).
    """
    full_name = f"{VERTEX_ATTRIBUTES}/{name}"
    if register_family:
        # Before the short-circuit, not after: an array that exists but was
        # never advertised is exactly the state this repairs, and returning
        # early would leave it unrepaired.
        from zarr_vectors.core.store import update_level_metadata

        update_level_metadata(level_group, add_arrays_present=VERTEX_ATTRIBUTES)
    if _short_circuit_existing(level_group, full_name, exist_ok):
        return
    _ensure_array_dir(level_group, full_name)
    meta: dict[str, Any] = {
        "zv_array": "attribute",
        "name": name,
        "dtype": dtype,
    }
    if channel_names is not None:
        if ncols is not None and len(channel_names) != int(ncols):
            raise ArrayError(
                f"channel_names has {len(channel_names)} entries but "
                f"ncols={ncols}; they describe the same width and must "
                f"agree. Pass one or the other, or make them match."
            )
        meta["channel_names"] = channel_names
    # ``ncols`` defaults to whatever channel_names implies, so naming the
    # channels keeps working as the only declaration of width; it is only
    # needed for an UNNAMED multi-column attribute, which previously had
    # no way to record its width at all.
    width = int(ncols) if ncols is not None else (
        len(channel_names) if channel_names else 1
    )
    # ``row_shape`` is the tail dims per row (``[]`` for a scalar column) --
    # the same spelling the link-attribute writers already stamp. Without
    # it the width was recoverable only by counting channel_names, so an
    # unnamed multi-column attribute read back as width*N scalar rows with
    # no error anywhere.
    meta["row_shape"] = [] if width == 1 else [width]
    if extra_meta:
        reserved = {"zv_array", "name", "dtype", "channel_names"}
        clobber = reserved & set(extra_meta)
        if clobber:
            raise ArrayError(
                f"extra_meta cannot override core attribute fields: {sorted(clobber)}"
            )
        meta.update(extra_meta)
    level_group.write_array_meta(full_name, meta)


def create_fragment_attribute_array(
    level_group: Group,
    name: str,
    dtype: str = "float32",
    channel_names: list[str] | None = None,
    ncols: int | None = None,
    extra_meta: dict[str, Any] | None = None,
    *,
    exist_ok: bool = True,
    register_family: bool = False,
) -> None:
    """Create a fragment attribute array ``fragment_attributes/<name>/``.

    Per-chunk dense byte blob storing one row per fragment in the chunk;
    row count is derived from ``vertex_fragments/<chunk>`` at read time.
    Optional storage layer — the common opt-in use case is materializing
    parent-IDs as attributes (e.g. the OID owning each fragment as a
    fragment attribute ``object_id``).

    Args:
        level_group: The resolution level FsGroup.
        name: Attribute name (e.g. ``"object_id"``).
        dtype: Numpy dtype string.
        channel_names: Optional list of channel names.  Supplying
            these declares the width; ``ncols`` is only needed for a
            multi-column attribute whose channels are unnamed.
        ncols: Columns per row.  ``None`` (default) infers from
            ``channel_names``, else 1.  When provided,
            row shape becomes ``(num_fragments, len(channel_names))``;
            otherwise rows are scalar.
        extra_meta: Additional JSON-serialisable fields merged into the
            array metadata.  Same collision rules as
            :func:`create_attribute_array`.
        register_family: Add the family to the level's ``arrays_present``.
            Off by default and deliberately so: that list lives in the
            level's single shared attrs blob, so writing it from an
            allocator puts a read-modify-write of shared state inside the
            worker path -- the same race ``record_presence=False`` exists
            to avoid.  Coordinators should prefer
            :func:`zarr_vectors.building.refresh_arrays_present`, which
            derives the whole list once.  Use this only for a serial
            writer that wants allocation and advertisement to stay in step.
        exist_ok: When True (default), no-op if the array already exists.
            When False, raise :class:`ArrayError` on conflict.
    """
    full_name = f"{FRAGMENT_ATTRIBUTES}/{name}"
    if register_family:
        # Before the short-circuit, not after: an array that exists but was
        # never advertised is exactly the state this repairs, and returning
        # early would leave it unrepaired.
        from zarr_vectors.core.store import update_level_metadata

        update_level_metadata(level_group, add_arrays_present=FRAGMENT_ATTRIBUTES)
    if _short_circuit_existing(level_group, full_name, exist_ok):
        return
    _ensure_array_dir(level_group, full_name)
    meta: dict[str, Any] = {
        "zv_array": "fragment_attribute",
        "name": name,
        "dtype": dtype,
    }
    if channel_names is not None:
        if ncols is not None and len(channel_names) != int(ncols):
            raise ArrayError(
                f"channel_names has {len(channel_names)} entries but "
                f"ncols={ncols}; they describe the same width and must "
                f"agree. Pass one or the other, or make them match."
            )
        meta["channel_names"] = channel_names
    # ``ncols`` defaults to whatever channel_names implies, so naming the
    # channels keeps working as the only declaration of width; it is only
    # needed for an UNNAMED multi-column attribute, which previously had
    # no way to record its width at all.
    width = int(ncols) if ncols is not None else (
        len(channel_names) if channel_names else 1
    )
    # ``row_shape`` is the tail dims per row (``[]`` for a scalar column) --
    # the same spelling the link-attribute writers already stamp. Without
    # it the width was recoverable only by counting channel_names, so an
    # unnamed multi-column attribute read back as width*N scalar rows with
    # no error anywhere.
    meta["row_shape"] = [] if width == 1 else [width]
    if extra_meta:
        reserved = {"zv_array", "name", "dtype", "channel_names"}
        clobber = reserved & set(extra_meta)
        if clobber:
            raise ArrayError(
                f"extra_meta cannot override core fragment_attribute fields: "
                f"{sorted(clobber)}"
            )
        meta.update(extra_meta)
    level_group.write_array_meta(full_name, meta)


def create_object_index_array(
    level_group: Group,
    *,
    exist_ok: bool = True,
) -> None:
    """Create the ``object_index/`` array.

    Args:
        level_group: Resolution level group.
        exist_ok: When True (default), no-op if the array already exists.
            When False, raise :class:`ArrayError` on conflict.
    """
    if _short_circuit_existing(level_group, OBJECT_INDEX, exist_ok):
        return
    _ensure_array_dir(level_group, OBJECT_INDEX)
    level_group.write_array_meta(OBJECT_INDEX, {
        "zv_array": "object_index",
    })


def create_object_attributes_array(
    level_group: Group,
    name: str,
    dtype: str = "float32",
    num_channels: int = 1,
    *,
    exist_ok: bool = True,
) -> None:
    """Reserve the ``object_attributes/<name>/`` slot.

    Under the 0.8.1 layout :func:`write_object_attributes` creates the
    Zarr array on first write (it needs the shape and dtype of the data
    in hand), so this function only performs the ``exist_ok`` conflict
    check — ``dtype`` and ``num_channels`` are accepted for API
    compatibility but not persisted at create-time.

    Args:
        level_group: The resolution level FsGroup.
        name: Attribute name.
        dtype: Numpy dtype string (informational only in 0.8.1).
        num_channels: Number of channels (informational only in 0.8.1).
        exist_ok: When True (default), no-op if the array already exists.
            When False, raise :class:`ArrayError` on conflict.
    """
    del dtype, num_channels  # informational only; see docstring.
    full_name = f"{OBJECT_ATTRIBUTES}/{name}"
    if _short_circuit_existing(level_group, full_name, exist_ok):
        return
    # Reserve the slot as an empty Zarr group; :func:`write_object_attributes`
    # replaces it with the real chunked array on first write.  The
    # placeholder lets a subsequent ``exist_ok=False`` create call detect
    # the conflict.
    _ensure_array_dir(level_group, full_name)


def create_groupings_array(
    level_group: Group,
    *,
    exist_ok: bool = True,
) -> None:
    """Reserve the ``groups/`` slot.

    Under the 0.8.1 layout :func:`write_groupings` creates the vlen
    Zarr array on first write, so this function only performs the
    ``exist_ok`` conflict check.

    Args:
        level_group: Resolution level group.
        exist_ok: When True (default), no-op if the array already exists.
            When False, raise :class:`ArrayError` on conflict.
    """
    if _short_circuit_existing(level_group, GROUPS, exist_ok):
        return
    _ensure_array_dir(level_group, GROUPS)


def create_groupings_attributes_array(
    level_group: Group,
    name: str,
    dtype: str = "float32",
    num_channels: int = 1,
    *,
    exist_ok: bool = True,
) -> None:
    """Reserve the ``group_attributes/<name>/`` slot.

    Under the 0.8.1 layout :func:`write_groupings_attributes` creates
    the Zarr array on first write, so this function only performs the
    ``exist_ok`` conflict check.

    Args:
        level_group: Resolution level group.
        name: Attribute name.
        dtype: Informational only in 0.8.1.
        num_channels: Informational only in 0.8.1.
        exist_ok: When True (default), no-op if the array already exists.
            When False, raise :class:`ArrayError` on conflict.
    """
    del dtype, num_channels
    full_name = f"{GROUP_ATTRIBUTES}/{name}"
    if _short_circuit_existing(level_group, full_name, exist_ok):
        return
    _ensure_array_dir(level_group, full_name)


def create_link_attributes_array(
    level_group: Group,
    name: str,
    dtype: str = "float32",
    *,
    delta: int = 0,
    sid_ndim: int | None = None,
    link_width: int = 2,
    offsets: Sequence[ChunkCoords] | None = None,
    exist_ok: bool = True,
    row_shape: Sequence[int] | None = None,
) -> None:
    """Create a ``link_attributes/<name>/<delta>/<offsets>/`` array.

    Mirrors the matching ``links/<delta>/<offsets>/`` array exactly —
    same delta, same offsets segment, same cells, same per-cell row
    order — so attribute rows align 1:1 with link records without
    storing a row id.  There is no separate cross-chunk attribute
    family: an intra-chunk link's attributes live under the all-zero
    offsets segment, just like the links themselves.

    ``exist_ok=True`` (default) makes the call idempotent; pass
    ``exist_ok=False`` to raise :class:`ArrayError` on conflict.

    ``row_shape`` is the tail shape of one row (``[]`` for a scalar
    column, ``[k]`` for ``k`` channels).  Readers need it to reshape a
    bare cell, and the cell writers stamp it if it is missing; passing
    it here settles the array's metadata in the one write that creates
    it, so later writes have nothing to restamp.
    """
    if offsets is None:
        if sid_ndim is None:
            raise ArrayError(
                "create_link_attributes_array requires sid_ndim when "
                "offsets is None (needed to derive the intra segment)"
            )
        offsets = intra_offsets(sid_ndim, link_width)
    full_name = link_attributes_path(name, delta, offsets)
    if _short_circuit_existing(level_group, full_name, exist_ok):
        return
    meta: dict[str, Any] = {
        "zv_array": "link_attribute",
        "name": name,
        "dtype": dtype,
        "offsets": [list(int(c) for c in o) for o in offsets],
        "level_delta": int(delta),
    }
    if row_shape is not None:
        meta["row_shape"] = [int(d) for d in row_shape]
    # The metadata rides on the create rather than following it: a
    # second write of the same ``zarr.json`` per segment was half of
    # what allocating a segment cost.
    _ensure_array_dir(level_group, full_name, attributes=meta)
    _write_array_meta_if_changed(
        level_group, link_attributes_group_path(name, delta), {
            "zv_array": "link_attribute_family",
            "name": name,
            "level_delta": int(delta),
        },
    )


def _neighbour_offsets(sid_ndim: int, *, positive_only: bool) -> list[ChunkCoords]:
    """Non-zero chunk offsets of a delta-0 neighbour record.

    With ``positive_only``, the lexicographically positive half (canonical placement).
    """
    return [
        tuple(d) for d in itertools.product((-1, 0, 1), repeat=int(sid_ndim))
        if any(d) and not (positive_only and next(x for x in d if x) < 0)
    ]


def create_link_segments(
    level_group: Group,
    *,
    sid_ndim: int,
    directed: bool = False,
    store: str = "canonical",
    dtype: str = "int64",
    include_intra: bool = True,
    intra_dtype: str | None = None,
    attributes: Mapping[str, Any] | None = None,
    intra_attributes: Mapping[str, Any] | None = None,
) -> list[str]:
    """Allocate every segment a delta-0, two-endpoint link family writes.

    Run by a coordinator before workers start, since concurrent array creation
    races on ``zarr.json``. Idempotently creates the family policy, one
    ``links/0/<offsets>`` array per neighbour offset (positive half for an
    undirected canonical family), the intra segment and its fragment sidecar
    with ``include_intra``, and the parallel ``link_attributes`` arrays for
    ``attributes`` / ``intra_attributes`` (``{name: dtype}`` or
    ``{name: (dtype, row_shape)}``).

    Returns:
        Every array path ensured: links first, then attributes.
    """
    if store not in ("canonical", "duplicate"):
        raise ArrayError(f"store must be 'canonical' or 'duplicate'; got {store!r}")
    nd = int(sid_ndim)
    cross = [(o,) for o in _neighbour_offsets(
        nd, positive_only=not directed and store == "canonical",
    )]
    intra = [intra_offsets(nd, 2)] if include_intra else []
    policy = {"link_width": 2, "delta": 0, "sid_ndim": nd,
              "directed": bool(directed), "store": str(store)}
    _create_links_arrays(level_group, cross, dtype=str(np.dtype(dtype)), **policy)
    if intra:
        _create_links_arrays(
            level_group, intra,
            dtype=str(np.dtype(intra_dtype if intra_dtype is not None else dtype)),
            **policy,
        )
    created = [links_path(0, o) for o in cross + intra]

    wanted: list[tuple[str, dict[str, Any]]] = []
    families: set[str] = set()
    for segments, specs in ((cross, attributes), (intra, intra_attributes)):
        for name, spec in (specs or {}).items():
            attr_dtype, row_shape = spec if isinstance(spec, tuple) else (spec, None)
            families.add(name)
            for offsets in segments:
                full_name = link_attributes_path(name, 0, offsets)
                created.append(full_name)
                if _short_circuit_existing(level_group, full_name, True):
                    continue
                meta: dict[str, Any] = {
                    "zv_array": "link_attribute",
                    "name": name,
                    "dtype": str(np.dtype(attr_dtype)),
                    "offsets": [list(int(c) for c in o) for o in offsets],
                    "level_delta": 0,
                }
                if row_shape is not None:
                    meta["row_shape"] = [int(d) for d in row_shape]
                wanted.append((full_name, meta))
    _ensure_chunk_arrays(level_group, wanted)
    for name in sorted(families):
        _write_array_meta_if_changed(
            level_group, link_attributes_group_path(name, 0), {
                "zv_array": "link_attribute_family",
                "name": name,
                "level_delta": 0,
            },
        )
    return created


def _write_array_meta_if_changed(
    level_group: Group, array_name: str, meta: dict[str, Any],
) -> bool:
    """:meth:`Group.write_array_meta`, skipped when no key in ``meta`` would change.

    Returns whether it wrote.
    """
    current = level_group.read_array_meta(array_name)
    if all(current.get(k) == v for k, v in meta.items()):
        return False
    level_group.write_array_meta(array_name, meta)
    return True


# ===================================================================
# Writing data
# ===================================================================

def write_chunk_vertices(
    level_group: Group,
    chunk_coords: ChunkCoords,
    groups: list[npt.NDArray[np.floating]],
    dtype: np.dtype | str = np.float32,
    *,
    record_presence: bool = True,
) -> npt.NDArray[np.int64]:
    """Write fragments to a spatial chunk.

    Encodes the groups as a contiguous byte buffer in ``vertices/`` and
    writes a v0.6 fragment-index to ``vertex_fragments/`` describing each
    group as a contiguous range of vertex rows in source order.

    Args:
        level_group: Resolution level group.
        chunk_coords: Spatial chunk coordinates.
        groups: List of arrays, each ``(N_k, D)``.
        dtype: Numpy dtype for serialisation.

    Returns:
        ``(K,)`` int64 array of vertex byte offsets (kept for backwards-
        compatible signature; callers that need the v0.6 fragment-index
        should use :func:`read_vertex_fragment_index`).
    """
    dtype = np.dtype(dtype)
    raw_bytes, vertex_byte_offsets = encode_ragged_floats(groups, dtype)
    counts = np.fromiter(
        (int(np.asarray(g).shape[0]) for g in groups), dtype=np.int64, count=len(groups),
    )
    _write_vertex_cell(
        level_group, _chunk_key(chunk_coords), raw_bytes, counts,
        record_presence=record_presence,
    )
    return vertex_byte_offsets


def write_chunk_vertex_runs(
    level_group: Group,
    chunk_coords: ChunkCoords,
    vertices: npt.NDArray[np.floating],
    counts: npt.NDArray[np.integer],
    dtype: np.dtype | str = np.float32,
    *,
    record_presence: bool = True,
) -> None:
    """:func:`write_chunk_vertices` for fragments already laid end to end:
    ``vertices`` is ``(N, D)``, ``counts`` each fragment's row count, in
    order.  Writes the same bytes."""
    _write_vertex_cell(
        level_group, _chunk_key(chunk_coords),
        np.ascontiguousarray(vertices, dtype=np.dtype(dtype)).tobytes(),
        np.asarray(counts, dtype=np.int64),
        record_presence=record_presence,
    )


def _write_vertex_cell(
    level_group: Group,
    key: str,
    raw_bytes: bytes,
    counts: npt.NDArray[np.int64],
    *,
    record_presence: bool,
) -> None:
    """Write one vertex cell and its fragment index, each fragment the
    next ``counts[k]`` rows."""
    # record_presence: see write_chunk_attributes.  nonempty_chunks is
    # array-wide, so stamping it rewrites the shared zarr.json once per
    # cell; concurrent writers over disjoint cells still collide there.
    level_group.write_bytes(
        VERTICES, key, raw_bytes, record_presence=record_presence,
    )

    # Express each group as a contiguous (start_row, count) fragment.
    cumulative = int(counts.sum())
    level_group.write_bytes(
        VERTEX_FRAGMENTS, key,
        pack_fragment_sections(
            range_fragment_sections(np.cumsum(counts) - counts, counts),
        ),
        record_presence=record_presence,
    )
    # Tell the level how many rows this cell now holds, so the tiling
    # stamp can check the fragment index against it without reading the
    # buffer back.  See :meth:`Group.note_vertex_rows`.
    level_group.note_vertex_rows(key, cumulative)


def _infer_link_width(link_groups: Sequence[npt.NDArray[np.integer]]) -> int:
    """Best-effort ``L`` from a list of ``(M_k, L)`` link groups."""
    for g in link_groups:
        arr = np.asarray(g)
        if arr.ndim == 2:
            return int(arr.shape[1])
    return 2


def write_chunk_links(
    level_group: Group,
    chunk_coords: ChunkCoords,
    link_groups: list[npt.NDArray[np.integer]],
    dtype: np.dtype | str = np.int64,
    *,
    delta: int = 0,
    offsets: Sequence[ChunkCoords] | None = None,
    link_width: int | None = None,
    record_presence: bool = True,
) -> npt.NDArray[np.int64]:
    """Write link rows to one cell of ``links/<delta>/<offsets>/``.

    ``chunk_coords`` is the **source** chunk — the cell — and ``offsets``
    names which array under ``links/<delta>/`` receives them.  Defaults to
    the all-zero (intra-chunk) offsets, which is the array that holds
    records whose endpoints all share the source chunk.

    This is the low-level per-cell writer: ``link_groups`` rows are
    written as given.  Choosing the source chunk, computing the offsets
    and prepending any ``perm_idx`` column is the caller's job — see
    :func:`zarr_vectors.spatial.boundary.partition_records_by_offset`.

    Two encodings, selected by ``delta == 0 and is_intra(offsets)``:

    - **flat + ``link_fragments/`` sidecar** for intra-chunk links at
      delta 0.  Readers derive per-group byte offsets from the cumulative
      group sizes (see :func:`read_chunk_links`); link groups need not be
      1:1 with the chunk's vertex fragments.
    - **inline self-describing ragged blob** otherwise — cross-offset
      records at any delta, and every cross-level record.  These carry no
      fragment sidecar.

    That condition reproduces both pre-merge layouts exactly: the intra
    array is byte-identical to the old ``links/<delta>/``, and every other
    offset array matches the old ``cross_chunk_links/<delta>/`` cells.

    Args:
        level_group: Resolution level group.
        chunk_coords: **Source** chunk coordinates (the array cell).
        link_groups: List of arrays, each ``(M_k, L)``.
        dtype: Integer dtype.
        delta: Level delta; see :mod:`zarr_vectors.core.paths`.
        offsets: Relative offsets naming the target array.  ``None``
            (default) means the all-zero intra-chunk offsets.
        link_width: Only used to derive the intra offsets segment when
            ``offsets`` is None and ``link_groups`` is empty.
        record_presence: Whether to stamp this cell into the array's
            ``nonempty_chunks`` manifest.  Decentralized workers pass
            False: the manifest is array-wide state, so stamping it is a
            read-modify-write that two workers racing on *disjoint* cells
            still lose keys to.  They leave it to a coordinator's
            :func:`finalize_links`, which rebuilds it from the store
            listing once every worker has finished.

    Returns:
        ``(K,)`` int64 array of link byte offsets.
    """
    dtype = np.dtype(dtype)
    key = _chunk_key(chunk_coords)
    if offsets is None:
        if link_width is None:
            link_width = _infer_link_width(link_groups)
        offsets = intra_offsets(len(chunk_coords), link_width)
    full_name = links_path(delta, offsets)

    # NOTE: link groups are no longer required to be 1:1 with the chunk's
    # vertex fragments. A downstream graph pipeline stores streamlines as vertex-fragments and the
    # node graph as link-fragments, so a chunk legitimately has many vertex
    # fragments (Core-1 range + polyline twins) but few link groups (the node
    # graph). Readers derive per-group link ranges from ``link_fragments/``
    # (not from ``vertex_fragments``), so no write-time 1:1 guard is needed.

    if delta == 0 and is_intra(offsets):
        # v0.6 intra-level: flat concatenated link data + sibling
        # link_fragments/ describing per-group row ranges.
        data_bytes, link_byte_offsets = encode_ragged_ints(link_groups, dtype)
        level_group.write_bytes(
            full_name, key, data_bytes, record_presence=record_presence,
        )

        link_row_size = dtype.itemsize * (
            int(np.asarray(link_groups[0]).shape[1]) if (
                link_groups and np.asarray(link_groups[0]).ndim == 2
            ) else 1
        )
        # Fragment per group as a contiguous range of link rows.
        link_counts = np.fromiter(
            (
                int(np.asarray(g).shape[0]) if np.asarray(g).ndim >= 1 else 0
                for g in link_groups
            ),
            dtype=np.int64, count=len(link_groups),
        )
        link_fragments = range_fragment_sections(
            np.cumsum(link_counts) - link_counts, link_counts,
        )
        # Ensure the sibling array container exists.  Routes through
        # ``_ensure_array_dir`` so that native-sharded writers allocate
        # a multidim vlen-bytes array at this path instead of the
        # legacy per-chunk-array group.
        #
        # ``link_fragments/<chunk>`` is keyed by chunk ALONE — it carries
        # no delta and no offsets segment — and this write is an
        # unconditional replace.  It is therefore only correct because the
        # enclosing branch admits exactly one array per chunk: the intra
        # one at delta 0.  If a non-intra offset ever reached here it would
        # silently clobber the intra array's fragment index.  Keep the
        # branch condition and this write together.
        if not level_group.array_exists(LINK_FRAGMENTS):
            _ensure_array_dir(level_group, LINK_FRAGMENTS)
            level_group.write_array_meta(LINK_FRAGMENTS, {
                "zv_array": LINK_FRAGMENTS,
                "encoding": "fragment_index_v1",
            })
        # Thread record_presence through to the sidecar too: without this the
        # links cell honours the opt-out but link_fragments still stamps its
        # array-wide manifest on every cell, so concurrent per-chunk writers
        # collide on link_fragments/zarr.json (a Windows hard-fail) even
        # though the caller asked to defer manifest maintenance.
        level_group.write_bytes(
            LINK_FRAGMENTS, key, pack_fragment_sections(link_fragments),
            record_presence=record_presence,
        )
        del link_row_size  # silence unused-variable warning
        return link_byte_offsets

    # Cross-offset and/or cross-level: inline self-describing ragged blob,
    # no fragment sidecar.  Matches the pre-merge ``cross_chunk_links/``
    # cell encoding and the old ``links/<delta!=0>/`` layout.
    blob = encode_ragged_blob(link_groups, dtype)
    level_group.write_bytes(full_name, key, blob, record_presence=record_presence)
    _, link_byte_offsets = encode_ragged_ints(link_groups, dtype)
    return link_byte_offsets


def write_chunk_fragments(
    level_group: Group,
    chunk_coords: ChunkCoords,
    new_fragments: list | None = None,
    *,
    csr: tuple[Any, Any] | None = None,
    target: Literal["vertex", "link"] = "vertex",
    mode: Literal["replace", "append"] = "replace",
    force_explicit: bool = False,
    record_presence: bool = True,
) -> list[int] | tuple[int, int]:
    """Write fragment-index entries to ``vertex_fragments/`` or ``link_fragments/``.

    Fragments come as ``new_fragments`` (``(start, count)`` tuples and 1-D index
    arrays) or ``csr=(indices, offsets)``; bytes match :func:`encode_fragments`.
    ``mode="append"`` concatenates after the stored fragments without
    re-encoding them (``"replace"`` if none exist). Read-modify-write, last
    writer wins: serialise appends per chunk, and not inside ``batched_reads``.

    Returns:
        List form: the new fragment indices (``[]`` for an empty append, which
        leaves the blob alone). ``csr`` form: ``(n_existing, n_new)``.

    Raises:
        ArrayError: Invalid ``target``/``mode``, not exactly one fragment form,
            or malformed fragments.
    """

    if target == "vertex":
        constant = VERTEX_FRAGMENTS
    elif target == "link":
        constant = LINK_FRAGMENTS
    else:
        raise ArrayError(
            f"target must be 'vertex' or 'link', got {target!r}"
        )
    if mode not in ("replace", "append"):
        raise ArrayError(
            f"mode must be 'replace' or 'append', got {mode!r}"
        )
    if (new_fragments is None) == (csr is None):
        raise ArrayError(
            "give the fragments as new_fragments or as csr=(indices, offsets), "
            "exactly one of them"
        )

    key = _chunk_key(chunk_coords)
    as_csr = csr is not None
    if as_csr:
        indices, offsets = csr  # type: ignore[misc]
        new = classify_fragments_csr(
            indices, offsets,
            force_explicit=force_explicit,
        )
    else:
        new_list = list(new_fragments)  # type: ignore[arg-type]
        if mode == "append" and not new_list:
            return []   # no-op append — don't touch the blob
        encoded = encode_fragments(new_list, force_explicit=force_explicit)
        if mode == "replace":
            level_group.write_bytes(
                constant, key, encoded, record_presence=record_presence,
            )
            return list(range(len(new_list)))
        new = fragment_sections_from_index(decode_fragments(encoded))
    n_new = new.num_fragments

    def _done(n_before: int) -> list[int] | tuple[int, int]:
        if as_csr:
            return (n_before, n_new)
        return list(range(n_before, n_before + n_new))

    if mode == "replace":
        level_group.write_bytes(
            constant, key, pack_fragment_sections(new),
            record_presence=record_presence,
        )
        return _done(0)

    try:
        raw = level_group.read_bytes(constant, key)
    except StoreError:
        raw = b""
    # An allocated-but-never-written cell reads back b"" (the vlen fill
    # value): nothing there yet.
    existing = (
        fragment_sections_from_index(decode_fragments(raw)) if raw
        else range_fragment_sections([], [])
    )
    if n_new:
        level_group.write_bytes(
            constant, key,
            pack_fragment_sections(concat_fragment_sections(existing, new)),
            record_presence=record_presence,
        )
    return _done(existing.num_fragments)


def write_chunk_attributes(
    level_group: Group,
    attr_name: str,
    chunk_coords: ChunkCoords,
    attr_groups: list[npt.NDArray],
    dtype: np.dtype | str = np.float32,
    *,
    record_presence: bool = True,
) -> None:
    """Write vertex attribute data for groups in a spatial chunk.

    Attribute groups align 1:1 with fragments, so per-group byte
    offsets are derived at read time from ``vertex_fragments`` and
    the attribute dtype/ncols.  No sibling ``_offsets`` blob is written.

    Args:
        level_group: Resolution level group.
        attr_name: Attribute name (e.g. ``"radius"``).
        chunk_coords: Spatial chunk coordinates.
        attr_groups: List of arrays aligned with fragments.
            Each array is ``(N_k,)`` for scalar or ``(N_k, C)`` for
            multi-channel attributes.
        dtype: Numpy dtype.
        record_presence: Whether to stamp this cell into the array's
            ``nonempty_chunks`` manifest.  Pass False when fanning
            per-chunk writes out concurrently, then rebuild the manifest
            once with :meth:`Group.derive_nonempty_chunks`.
    """
    dtype = np.dtype(dtype)
    key = _chunk_key(chunk_coords)
    full_name = f"{VERTEX_ATTRIBUTES}/{attr_name}"
    # The array must already exist: this is a per-cell write, and callers
    # fan it out across chunks (sometimes concurrently), so allocating
    # here would both race and re-create the array on every chunk —
    # ``_ensure_array_dir`` drops and rebuilds an array whose
    # ``nonempty_chunks`` is still empty.  Allocate once up front instead.
    #
    # ``record_presence=False`` is for exactly that concurrent fan-out:
    # ``nonempty_chunks`` lives on the array, so stamping it rewrites the
    # shared ``zarr.json`` once per cell.  Two tasks writing *disjoint*
    # cells still collide there — on Windows as a rename race over
    # ``zarr.json``, elsewhere as a silently dropped key.  Callers that
    # fan out pass False and rebuild once via
    # :meth:`Group.derive_nonempty_chunks`.
    raw_bytes, _ = encode_ragged_floats(attr_groups, dtype)
    level_group.write_bytes(
        full_name, key, raw_bytes, record_presence=record_presence,
    )


def write_chunk_fragment_attributes(
    level_group: Group,
    attr_name: str,
    chunk_coords: ChunkCoords,
    data: npt.NDArray,
    dtype: np.dtype | str = np.float32,
    *,
    record_presence: bool = True,
) -> None:
    """Write per-fragment attribute data for a spatial chunk.

    The on-disk layout is a single dense byte blob whose row count
    equals ``num_fragments_in_chunk``.  Fragment count is not validated
    against ``vertex_fragments/<chunk>`` at write time — the read side
    fails loudly on byte-length mismatch, so callers are trusted to
    pass a correctly-sized array.  Replace-only at the chunk level.

    Args:
        level_group: Resolution level group.
        attr_name: Attribute name (e.g. ``"object_id"``).
        chunk_coords: Spatial chunk coordinates.
        data: ``(F,)`` for scalar or ``(F, C)`` for multi-channel,
            where ``F`` is the number of fragments in this chunk.
        dtype: Numpy dtype to cast ``data`` to before writing.
        record_presence: Whether to stamp this cell into the array's
            ``nonempty_chunks`` manifest.  Pass ``False`` from concurrent
            per-chunk writers (the manifest is one array-wide attribute, so
            stamping it is a read-modify-write that races across processes)
            and re-derive it once afterwards via
            :meth:`FsGroup.derive_nonempty_chunks`.  See
            :func:`write_chunk_vertices` for the same pattern.
    """
    dtype = np.dtype(dtype)
    key = _chunk_key(chunk_coords)
    full_name = f"{FRAGMENT_ATTRIBUTES}/{attr_name}"
    arr = np.ascontiguousarray(np.asarray(data).astype(dtype, copy=False))
    level_group.write_bytes(
        full_name, key, arr.tobytes(), record_presence=record_presence,
    )


def write_chunk_link_attributes(
    level_group: Group,
    attr_name: str,
    chunk_coords: ChunkCoords,
    attr_groups: list[npt.NDArray],
    dtype: np.dtype | str = np.float32,
    *,
    delta: int = 0,
    offsets: Sequence[ChunkCoords] | None = None,
    link_width: int = 2,
) -> None:
    """Write one cell of ``link_attributes/<name>/<delta>/<offsets>/``.

    Mirrors :func:`write_chunk_links` cell-for-cell: ``chunk_coords`` is
    the **source** chunk and ``offsets`` names the same array under
    ``link_attributes/<name>/<delta>/`` that ``links/<delta>/`` receives
    the parallel records in.  Rows are written as given, in the same
    order — that positional alignment is the whole contract, so there is
    no row id.

    Unlike the link cell there is no encoding branch: the payload is
    always a flat dense blob of ``sum(M_k)`` rows.  Per-group boundaries
    are recovered at read time from the parallel link cell — the
    ``link_fragments/<chunk>`` sidecar for the intra array at delta 0,
    the links blob's own inline header otherwise (see
    :func:`read_chunk_link_attributes`).

    Args:
        level_group: Resolution level group.
        attr_name: Attribute name (e.g. ``"weight"``).
        chunk_coords: **Source** chunk coordinates (the array cell).
        attr_groups: List of arrays, each ``(M_k,)`` or ``(M_k, C)``,
            aligned with the link groups in the parallel links cell.
        dtype: Numpy dtype.
        delta: Level delta; see :mod:`zarr_vectors.core.paths`.
        offsets: Relative offsets naming the target array.  ``None``
            (default) means the all-zero intra-chunk offsets.
        link_width: Only used to derive the intra offsets segment when
            ``offsets`` is None.
    """
    dtype = np.dtype(dtype)
    key = _chunk_key(chunk_coords)
    if offsets is None:
        offsets = intra_offsets(len(chunk_coords), link_width)
    full_name = link_attributes_path(attr_name, delta, offsets)
    raw_bytes, _ = encode_ragged_floats(attr_groups, dtype)
    level_group.write_bytes(full_name, key, raw_bytes)


def _check_object_index_size(size: int, n_present: int) -> None:
    """Raise :class:`ArrayError` if empty id-space padding (``size - n_present``)
    exceeds :data:`OBJECT_INDEX_MAX_ROWS`; warn when the index is mostly padding.
    """
    padding = size - n_present
    if padding > OBJECT_INDEX_MAX_ROWS:
        raise ArrayError(
            f"A declared id space of {size:,} rows holds {n_present:,} "
            f"object(s), so {padding:,} rows would be empty padding -- past "
            f"the {OBJECT_INDEX_MAX_ROWS:,}-row ceiling on padding. A slot "
            f"count that large is usually an address from elsewhere (a "
            f"segmentation label, a hash). Ids are stored beside their "
            f"rows, so write the objects without total_objects and their "
            f"ids may be anything."
        )
    if (
        size >= _OBJECT_INDEX_SPARSE_FLOOR
        and n_present
        and size > n_present * _OBJECT_INDEX_SPARSE_RATIO
    ):
        warnings.warn(
            f"Object index allocates {size:,} manifest rows for "
            f"{n_present:,} object(s): {100 * (1 - n_present / size):.1f}% of "
            f"it is empty padding, and every whole-index read pays for it. "
            f"The padding is the slots total_objects declares with no "
            f"object; ids are stored beside their rows, so leaving it out "
            f"keeps the index proportional to the data.",
            RuntimeWarning,
            stacklevel=3,
        )


def write_object_index(
    level_group: Group,
    manifests: dict[int, ObjectManifest],
    sid_ndim: int,
    *,
    total_objects: int | None = None,
    layout: str | None = None,
    block_dtype: Any = None,
) -> None:
    """Write object index: object_id → ordered fragment references.

    Args:
        level_group: Resolution level group.
        manifests: ``{object_id: [(chunk_coords, fragment_index), ...], ...}``.
            Sparse — OIDs absent from the dict get empty manifests.
        sid_ndim: Number of spatial index dimensions.
        total_objects: Number of OID slots to write.  When provided,
            the dense manifest list spans ``range(total_objects)`` even
            if the largest OID present is smaller — used by the
            ID-preserving pyramid regime, where surviving OIDs are a
            sparse subset of the parent's OID space.  When ``None``
            (default), there is one row per id in ``manifests``.
        layout: ``"vlen"`` or ``"dense"`` (see
            :mod:`zarr_vectors.core.dense_manifests`). ``None`` keeps the
            index's current layout, or takes the store's
            ``manifest_layout`` for a new one.
        block_dtype: Dense only: ``"int64"`` or ``"int32"`` for
            ``manifest_blocks``. ``None`` keeps a dense index's current
            dtype, or takes the store's ``manifest_block_dtype``. This
            rewrites every array, so it may change it.

    Raises:
        ArrayError: When ``total_objects`` would add more than
            :data:`OBJECT_INDEX_MAX_ROWS` rows with no object in them, or
            a block does not fit an ``int32`` index.
    """
    from zarr_vectors.core.dense_manifests import check_block_dtype

    check_block_dtype(block_dtype)
    if not manifests and total_objects is None:
        return

    # Rows are dense and the ids are stored alongside them, so an id may
    # be arbitrary, sparse or 64-bit without allocating anything for the
    # gaps. ``total_objects`` still widens the id space, which the
    # id-preserving pyramid regime uses to keep dropped objects
    # addressable -- those become present-but-empty rows exactly as
    # before, just without the padding between them.
    row_ids = sorted(int(o) for o in manifests)
    if total_objects is not None:
        # Preserve the historical contract: a caller declaring a slot
        # count means ids 0..total-1 all exist, empty or not. The rows
        # that adds are counted before the range is built, so a count
        # that is really an address fails here instead of hanging.
        total = int(total_objects)
        outside = sum(1 for o in row_ids if not 0 <= o < total)
        _check_object_index_size(max(total, 0) + outside, len(manifests))
        declared = set(range(total))
        row_ids = sorted(declared.union(row_ids))
    manifest_list: list[list[tuple[tuple[int, ...], int]]] = [
        manifests.get(oid, []) for oid in row_ids
    ]
    if _index_layout_for_write(level_group, layout) == "dense":
        from zarr_vectors.core import dense_manifests as dense

        offsets, coords, frags = dense.csr_from_manifests(manifest_list, sid_ndim)
        write_object_index_csr(
            level_group, row_ids, offsets, coords, frags, sid_ndim,
            layout="dense", block_dtype=block_dtype,
        )
        return

    # v0.6 manifest-block encoding.  Each old (chunk, fragment_index) tuple
    # becomes one mode-0 (single fragment) block.  Range / explicit
    # short-circuits are reserved for writers that know they produce
    # ranges or fragment-list shapes — to be plumbed through the
    # higher-level write APIs in a future change.
    manifest_blobs = encode_object_manifests_many(manifest_list, sid_ndim=sid_ndim)

    # What an absent object encodes to, from the encoder rather than from
    # a pinned literal -- a consumer had reverse-engineered this as
    # b"\x00\x00\x00\x00" and hardcoded it, which makes the encoding
    # its business instead of ours.
    _empty_manifest = encode_object_manifest_blocks([], sid_ndim=sid_ndim)

    _write_object_index_manifests(level_group, manifest_blobs, layout="vlen")
    _write_object_id_table(level_group, row_ids)
    level_group.write_array_meta(OBJECT_INDEX, {
        "zv_array": "object_index",
        "num_objects": len(row_ids),
        # How many of those slots actually hold an object.  ``num_objects``
        # is the SLOT count: a sparsified pyramid level deliberately keeps
        # dropped objects as empty manifests so ids stay stable across
        # levels, so the two differ by exactly the dropped ones.  Without
        # this, "which objects are really here" costs a full manifest
        # decode -- ~51.6 us per object, which is 18 minutes on a 21M-object
        # store, to answer a question the writer already knew.
        "num_present": sum(1 for blob in manifest_blobs if blob != _empty_manifest),
        "sid_ndim": sid_ndim,
        "layout": OBJECT_INDEX_LAYOUT_V2,
        OBJECT_IDS_SORTED_ATTR: True,
    })


def write_object_index_arrays(
    level_group: Group,
    offsets: npt.NDArray[np.integer],
    coords: npt.NDArray[np.integer],
    frags: npt.NDArray[np.integer],
    sid_ndim: int,
) -> None:
    """:func:`write_object_index_csr` for objects ``0..len(offsets)-2``,
    each row its own id."""
    offsets = np.asarray(offsets, dtype=np.int64)
    write_object_index_csr(
        level_group, np.arange(len(offsets) - 1, dtype=np.int64), offsets,
        np.asarray(coords, dtype=np.int64).reshape(-1, sid_ndim),
        np.asarray(frags, dtype=np.int64), sid_ndim,
    )


def write_object_index_csr(
    level_group: Group,
    row_ids: Any,
    offsets: npt.NDArray[np.int64],
    coords: npt.NDArray[np.int64],
    frags: npt.NDArray[np.int64],
    sid_ndim: int,
    *,
    layout: str | None = None,
    block_dtype: Any = None,
) -> None:
    """:func:`write_object_index` for manifests already held as CSR arrays.

    Row ``r`` is object ``row_ids[r]`` (sorted ascending) and owns the
    single-fragment blocks ``offsets[r]:offsets[r+1]`` of ``coords``
    (``(B, sid_ndim)``) and ``frags`` (``(B,)``).  Writes what
    :func:`write_object_index` writes for the matching manifest dict,
    without a Python step per object.
    """
    from zarr_vectors.core import dense_manifests as dense
    from zarr_vectors.core.dense_manifests import check_block_dtype

    check_block_dtype(block_dtype)
    num_present = int(np.count_nonzero(np.diff(offsets)))
    if _index_layout_for_write(level_group, layout) == "dense":
        _write_dense_index(
            level_group, offsets, coords, frags,
            mode="replace", at=None, ids=None, sid_ndim=sid_ndim, block_dtype=block_dtype,
        )
        layout_stamp = dense.OBJECT_INDEX_LAYOUT_DENSE
    else:
        _write_object_index_manifests(
            level_group,
            encode_object_manifests_csr(coords, frags, offsets, sid_ndim=sid_ndim),
            layout="vlen",
        )
        layout_stamp = OBJECT_INDEX_LAYOUT_V2
    _write_object_id_table(level_group, row_ids)
    level_group.write_array_meta(OBJECT_INDEX, {
        "zv_array": "object_index",
        "num_objects": len(row_ids),
        "num_present": num_present,
        "sid_ndim": sid_ndim,
        "layout": layout_stamp,
        OBJECT_IDS_SORTED_ATTR: True,
    })


def commit_object_index(
    level_group: Group,
    num_objects: int,
    *,
    sid_ndim: int | None = None,
    num_present: int | None = None,
    object_ids_sorted: bool | None = None,
) -> dict[str, Any]:
    """Commit the object index's metadata after manifest writes.

    Merges into the existing metadata (see :func:`write_object_manifests`):

    - ``num_objects``: the committed prefix (rows past it are residue a later
      ``at=num_objects`` append replaces); may not exceed the rows written.
    - ``layout``: kept; an unstamped vlen index is stamped V1.
    - ``sid_ndim``: the argument, else the stamp, else the level's.
    - ``num_present``: counted over committed rows unless given.
    - ``object_ids_sorted``: computed from the committed ids for an index
      that stores ids (V2 or dense), unless given.

    Returns:
        The metadata keys written.
    """
    from zarr_vectors.core import dense_manifests as dense

    n = int(num_objects)
    if n < 0:
        raise ArrayError(f"num_objects {n} is negative")
    if not level_group.array_exists(OBJECT_INDEX):
        raise ArrayError("commit_object_index: this level has no object index")
    meta = level_group.read_array_meta(OBJECT_INDEX) or {}
    is_dense = dense.is_dense(level_group, meta)
    manifests_path = f"{OBJECT_INDEX}/manifests"
    if is_dense:
        rows = dense.num_rows(level_group)
    elif level_group.array_exists(manifests_path):
        rows = int(level_group.zarr_group[manifests_path].shape[0])
    else:
        rows = 0
    if n > rows:
        raise ArrayError(
            f"commit_object_index: num_objects {n} exceeds the {rows} "
            f"manifest rows written"
        )
    if sid_ndim is None:
        sid_ndim = meta.get("sid_ndim")
    if sid_ndim is None:
        try:
            sid_ndim = _index_sid_ndim(level_group)
        except Exception as exc:  # noqa: BLE001 - reported as a missing argument
            raise ArrayError(
                "commit_object_index: the index has no sid_ndim; pass it"
            ) from exc
    layout = (
        _LAYOUT_DENSE if is_dense
        else meta.get("layout") or OBJECT_INDEX_LAYOUT_V1
    )
    if num_present is None:
        if n == 0:
            num_present = 0
        elif is_dense:
            num_present = int(dense.present_mask(level_group, stop=n).sum())
        else:
            blobs = level_group.read_vlen_array_raw(manifests_path, stop=n)
            unwritten = sum(1 for b in blobs if not b)
            if unwritten:
                raise ArrayError(
                    f"commit_object_index: {unwritten} of the {n} rows hold no "
                    f"manifest at all -- reserved or padded rows nothing wrote"
                )
            num_present = sum(1 for b in blobs if bytes(b) != _EMPTY_MANIFEST_BLOB)
    elif not 0 <= int(num_present) <= n:
        raise ArrayError(f"num_present {num_present} is outside [0, {n}]")
    out: dict[str, Any] = {
        "zv_array": "object_index",
        "num_objects": n,
        "num_present": int(num_present),
        "sid_ndim": int(sid_ndim),
        "layout": layout,
    }
    if is_dense and level_group.array_exists(dense.BLOCKS_PATH):
        # Restated from the array: a batched commit replaces the document.
        dt = np.dtype(level_group._require_array_node(dense.BLOCKS_PATH).dtype)
        if dt != np.int64 or dense.BLOCK_DTYPE_ATTR in meta:
            out[dense.BLOCK_DTYPE_ATTR] = dt.name
    table_path = f"{OBJECT_INDEX}/{OBJECT_IDS_ARRAY}"
    if layout in (OBJECT_INDEX_LAYOUT_V2, _LAYOUT_DENSE) and level_group.array_exists(table_path):
        if object_ids_sorted is None:
            # Read in pieces: only a count and an order are needed.
            node = level_group.zarr_group[table_path]
            held = min(int(node.shape[0]), n)
            if held < n:
                raise ArrayError(
                    f"commit_object_index: the id table holds {held} "
                    f"ids for {n} committed rows"
                )
            unwritten, ascending, last = 0, True, None
            for _a, piece in _id_table_pieces(node, 0, n):
                unwritten += int(np.count_nonzero(piece < 0))
                if ascending and piece.size:
                    ascending = bool(np.all(np.diff(piece) > 0)) and (
                        last is None or int(piece[0]) > last
                    )
                if piece.size:
                    last = int(piece[-1])
            if unwritten:
                raise ArrayError(
                    f"commit_object_index: {unwritten} of the {n} rows have no "
                    f"object id -- reserved rows nothing wrote"
                )
            object_ids_sorted = ascending
        out[OBJECT_IDS_SORTED_ATTR] = bool(object_ids_sorted)
    level_group.write_array_meta(OBJECT_INDEX, out)
    # Also drops the id lookup, which keys on the sorted flag.
    level_group._invalidate_node(OBJECT_INDEX)
    return out


def _write_object_id_table(
    level_group: Group, row_ids: Sequence[int], *, keep_codecs: bool = False,
) -> None:
    """Write ``object_index/object_ids``: row → object id.

    This is the tie that used to be positional only. The comment on
    ``write_object_attributes``' ``at=`` -- "nothing on disk ties a row
    to an object, so row i means object i by position alone" -- was the
    statement of the problem; this array is the answer to it.

    ``keep_codecs``: a table that exists is rewritten with its own codecs
    (an index that exists keeps them); otherwise, and for a new table,
    :func:`~zarr_vectors.core.dense_manifests.manifest_codecs`.
    """
    # Chunked at the manifest bucket, as appends extend it: written as one
    # chunk, a 10^9-object table was a single 8 GB object, rewritten whole
    # by the first append. A range (the appender's identity table) becomes
    # an arange, not a list of a billion Python ints.
    from zarr_vectors.core.dense_manifests import existing_codecs, manifest_codecs

    path = f"{OBJECT_INDEX}/{OBJECT_IDS_ARRAY}"
    codecs = (
        existing_codecs(level_group.zarr_group[path])
        if keep_codecs and level_group.array_exists(path) else manifest_codecs(level_group)
    )
    ids = (
        np.arange(row_ids.start, row_ids.stop, row_ids.step, dtype=np.int64)
        if isinstance(row_ids, range)
        else np.asarray(row_ids, dtype=np.int64) if isinstance(row_ids, np.ndarray)
        else np.fromiter(row_ids, dtype=np.int64)
    )
    level_group.write_array(
        path, ids,
        chunks=(OBJECT_INDEX_MANIFEST_BUCKET,),
        shards=_object_shards(level_group, (OBJECT_INDEX_MANIFEST_BUCKET,)),
        compressors=codecs,
    )


def patch_object_manifests(
    level_group: Group,
    updates: dict[int, ObjectManifest],
    sid_ndim: int,
) -> None:
    """Replace named rows of ``object_index/manifests``, leaving the rest.

    :func:`write_object_index` rewrites every row, so changing one
    object's manifest costs the whole index: on a 400,000-object store a
    single ``edit_vertex`` spent 3.3s and 414 MB doing it, and both
    figures grow with the object count rather than with the edit.  This
    touches only the zarr chunks the named rows fall in.

    ``num_present`` is adjusted by the difference between the rows being
    replaced and the rows replacing them, so it stays exact without a
    full decode.  The array grows when an id runs past the end, padded
    with empty manifests exactly as a full rewrite would.

    Args:
        level_group: Resolution level group.
        updates: ``{object_id: [(chunk_coords, fragment_index), ...]}``
            for the objects whose manifests changed.  An empty list
            blanks that object, which is how a removal is recorded.
        sid_ndim: Number of spatial index dimensions.
    """
    if not updates:
        return

    from zarr_vectors.core import dense_manifests as dense

    if dense.is_dense(level_group):
        _patch_dense_manifests(level_group, updates, sid_ndim)
        return
    oi_group = level_group.zarr_group.require_group(OBJECT_INDEX)
    if "manifests" not in oi_group:
        # Nothing to patch into -- this is the first index for the level.
        write_object_index(level_group, dict(updates), sid_ndim)
        return

    meta = level_group.read_array_meta(OBJECT_INDEX)
    empty_blob = encode_object_manifest_blocks([], sid_ndim=sid_ndim)
    arr = oi_group["manifests"]
    n0 = int(arr.shape[0])

    ids = sorted(int(o) for o in updates)
    blobs = {
        oid: encode_object_manifest_blocks(
            [
                (tuple(int(c) for c in cc), int(fi))
                for cc, fi in (updates[oid] or [])
            ],
            sid_ndim=sid_ndim,
        )
        for oid in ids
    }

    # Ids this level already holds keep their row; the rest are appended
    # in id order. An id is not a row, so a new one extends the index by
    # exactly one row however large the id is.
    known, known_rows = object_rows_for_ids(level_group, ids)
    row_of = dict(zip(known.tolist(), known_rows.tolist()))
    fresh = [o for o in ids if o not in row_of]
    size = n0 + len(fresh)
    for offset, oid in enumerate(fresh):
        row_of[oid] = n0 + offset

    # What those rows held before, so num_present moves by the delta
    # rather than being recounted over the whole index.  Read in row order
    # and paired in the same order: ids need not ascend with their rows
    # once an id table exists, so pairing id order against row order
    # would hand each id another object's manifest.
    held = sorted((row_of[o], o) for o in ids if row_of[o] < n0)
    previous = dict(zip(
        [o for _row, o in held],
        level_group.read_vlen_elements(
            f"{OBJECT_INDEX}/manifests", [row for row, _o in held],
        ),
    )) if held else {}

    target_rows = [row_of[o] for o in ids]
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", UnstableSpecificationWarning)
        if size > n0:
            arr.resize((size,))
        values = np.empty(len(ids), dtype=object)
        values[:] = [blobs[o] for o in ids]
        arr.set_coordinate_selection(
            (np.asarray(target_rows, dtype=np.intp),), values,
        )
    level_group._invalidate_node(f"{OBJECT_INDEX}/manifests")

    if fresh:
        table = read_object_id_table(level_group)
        if table is None:
            table = np.arange(n0, dtype=np.int64)
        _write_object_id_table(
            level_group,
            np.concatenate([table, np.asarray(fresh, dtype=np.int64)]).tolist(),
            keep_codecs=True,
        )

    was_present = sum(
        1 for o in ids if previous.get(o, empty_blob) != empty_blob
    )
    now_present = sum(1 for o in ids if blobs[o] != empty_blob)
    prior_present = int(meta.get("num_present", meta.get("num_objects", n0)))
    new_meta = {
        **meta,
        "num_objects": size,
        "num_present": max(0, prior_present - was_present + now_present),
        "sid_ndim": sid_ndim,
        "layout": OBJECT_INDEX_LAYOUT_V2,
    }
    if fresh:
        # Appended ids need not ascend, so the cheap lookup no longer
        # applies unless they happen to.
        new_meta[OBJECT_IDS_SORTED_ATTR] = bool(
            meta.get(OBJECT_IDS_SORTED_ATTR)
            and (n0 == 0 or fresh[0] > int(read_object_id_table(level_group)[n0 - 1]))
            and fresh == sorted(fresh)
        )
    level_group.write_array_meta(OBJECT_INDEX, new_meta)


def _patch_dense_manifests(
    level_group: Group, updates: dict[int, ObjectManifest], sid_ndim: int,
) -> None:
    """:func:`patch_object_manifests` for a dense index: the new blocks are
    appended and only the patched objects' span rows rewritten."""
    from zarr_vectors.core import dense_manifests as dense

    meta = level_group.read_array_meta(OBJECT_INDEX)
    n0 = dense.num_rows(level_group)
    ids = sorted(int(o) for o in updates)
    known, known_rows = object_rows_for_ids(level_group, ids)
    row_of = dict(zip(known.tolist(), known_rows.tolist()))
    fresh = [o for o in ids if o not in row_of]
    for offset, oid in enumerate(fresh):
        row_of[oid] = n0 + offset
    offsets, coords, frags = dense.csr_from_manifests(
        [updates[o] or [] for o in ids], sid_ndim,
    )
    held = dense.patch(
        level_group, np.asarray([row_of[o] for o in ids], dtype=np.int64),
        offsets, coords, frags, sid_ndim=sid_ndim,
    )
    if fresh:
        table = read_object_id_table(level_group)
        if table is None:
            table = np.arange(n0, dtype=np.int64)
        _write_object_id_table(
            level_group, np.concatenate([table, np.asarray(fresh, dtype=np.int64)]).tolist(),
            keep_codecs=True,
        )
    now = int(np.count_nonzero(np.diff(offsets)))
    prior_present = int(meta.get("num_present", meta.get("num_objects", n0)))
    new_meta = {
        **meta,
        "num_objects": n0 + len(fresh),
        "num_present": max(0, prior_present - int(held.sum()) + now),
        "sid_ndim": sid_ndim,
        "layout": dense.OBJECT_INDEX_LAYOUT_DENSE,
    }
    if fresh:
        table = read_object_id_table(level_group)
        new_meta[OBJECT_IDS_SORTED_ATTR] = bool(
            meta.get(OBJECT_IDS_SORTED_ATTR) and np.all(np.diff(table) > 0)
        )
    level_group.write_array_meta(OBJECT_INDEX, new_meta)


def _object_array(blobs: Any) -> npt.NDArray[np.object_]:
    """``blobs`` as a 1-D object array of ``bytes``, never via fixed-width bytes
    (which would strip the trailing NULs every manifest ends in).
    """
    if isinstance(blobs, np.ndarray) and blobs.dtype == object:
        return blobs.reshape(-1)
    blobs = list(blobs)
    return np.fromiter(blobs, dtype=object, count=len(blobs))


def _empty_manifests(n: int) -> npt.NDArray[np.object_]:
    """``n`` empty-manifest blobs as an object array (not ``np.full``, which strips
    the blob's NULs to ``b""``).
    """
    out = np.empty(max(int(n), 0), dtype=object)
    out.fill(_EMPTY_MANIFEST_BLOB)
    return out


def _extend_object_id_table(
    level_group: Group, keep: int, new_ids: npt.NDArray[np.int64],
) -> None:
    """Keep the first ``keep`` rows of ``object_index/object_ids`` and add ``new_ids``.

    Appends in place when bucket-chunked; otherwise rewrites with that chunking.
    """
    path = f"{OBJECT_INDEX}/{OBJECT_IDS_ARRAY}"
    node = level_group.zarr_group[path]
    n0 = int(node.shape[0])
    if n0 < keep:
        raise ArrayError(
            f"object id table holds {n0} rows; cannot keep {keep}"
        )
    last = int(node[keep - 1]) if keep else None
    if keep == n0 and int(node.chunks[0]) >= OBJECT_INDEX_MANIFEST_BUCKET:
        level_group.extend_array(path, new_ids)
    else:
        from zarr_vectors.core.dense_manifests import existing_codecs

        # Rewritten, not recreated: the table keeps its codecs.
        head = np.asarray(node[:keep], dtype=np.int64)
        level_group.write_array(
            path, np.concatenate([head, new_ids]),
            chunks=(OBJECT_INDEX_MANIFEST_BUCKET,),
            shards=_object_shards(level_group, (OBJECT_INDEX_MANIFEST_BUCKET,)),
            compressors=existing_codecs(node),
        )
    meta = level_group.read_array_meta(OBJECT_INDEX) or {}
    ascending = bool(meta.get(OBJECT_IDS_SORTED_ATTR, False)) and bool(
        np.all(np.diff(new_ids) > 0)
        and (last is None or not new_ids.size or int(new_ids[0]) > last)
    )
    if ascending != bool(meta.get(OBJECT_IDS_SORTED_ATTR, False)):
        level_group.write_array_meta(OBJECT_INDEX, {OBJECT_IDS_SORTED_ATTR: ascending})


def _ids_for_append(
    level_group: Group, start: int, n_rows: int, n_new: int, ids: Any,
) -> npt.NDArray[np.int64] | None:
    """The ids appended rows get, or ``None`` when rows are the ids (V1).

    On an index that stores ids: ``ids=`` if given, the identity if the table
    is the identity, else :class:`ArrayError`.
    """
    meta = level_group.read_array_meta(OBJECT_INDEX) if OBJECT_INDEX in level_group else {}
    table_path = f"{OBJECT_INDEX}/{OBJECT_IDS_ARRAY}"
    stored = (meta or {}).get("layout") in (
        OBJECT_INDEX_LAYOUT_V2, _LAYOUT_DENSE,
    ) and level_group.array_exists(table_path)
    new_ids = None if ids is None else np.asarray(ids, dtype=np.int64).reshape(-1)
    if new_ids is not None and new_ids.size != n_new:
        raise ArrayError(f"{new_ids.size} ids for {n_new} manifests")
    if not stored:
        if new_ids is not None and not np.array_equal(
            new_ids, np.arange(start, start + n_new),
        ):
            raise ArrayError(
                "this object index stores ids positionally (row i is object "
                "i); ids= must be the rows being written"
            )
        return None
    node = level_group.zarr_group[table_path]
    n_ids = int(node.shape[0])
    # The table is the rows themselves -- what an index built by appends
    # without ids holds -- so a row's id is its row, padding included.
    keep = min(start, n_ids)
    identity = keep == 0 or (
        bool(meta.get(OBJECT_IDS_SORTED_ATTR, False))
        and int(node[0]) == 0 and int(node[keep - 1]) == keep - 1
    )
    if start > n_rows:
        dense_identity = (
            meta.get("layout") == _LAYOUT_DENSE and identity and new_ids is None
            and n_ids == n_rows
        )
        if not dense_identity:
            raise ArrayError(
                "cannot pad an object index that stores its ids: the padding "
                "rows would have none"
            )
    if new_ids is not None:
        return new_ids
    if not identity or n_ids < start and n_ids != n_rows:
        raise ArrayError(
            "this object index stores its ids, and they are not simply the "
            "rows; pass ids= for the objects being appended"
        )
    return np.arange(start, start + n_new, dtype=np.int64)


def _index_layout_for_write(level_group: Group, requested: str | None = None) -> str:
    """``"dense"`` or ``"vlen"``: explicit request, else the existing index's
    layout, else the store's ``manifest_layout``.
    """
    from zarr_vectors.core import dense_manifests as dense

    if requested is not None:
        if requested not in ("vlen", "dense"):
            raise ArrayError(f"layout={requested!r}; expected 'vlen' or 'dense'")
        return requested
    if dense.is_dense(level_group):
        return "dense"
    if level_group.array_exists(f"{OBJECT_INDEX}/manifests"):
        return "vlen"
    return dense.store_default(level_group)


def _index_sid_ndim(level_group: Group) -> int:
    try:
        meta = level_group.read_array_meta(OBJECT_INDEX) or {}
    except Exception:
        meta = {}
    if meta.get("sid_ndim") is not None:
        return int(meta["sid_ndim"])
    # A composite level's manifests carry the source first (chunk_sources).
    from zarr_vectors.core.sources import chunk_sources

    if chunk_sources(level_group) is not None:
        dims = (level_group.attrs.get("zarr_vectors") or {}).get("chunk_dims") or []
        if dims:
            return len(dims)
    return _infer_vert_ndim(level_group)


def _write_dense_index(
    level_group: Group,
    offsets: Any,
    coords: Any,
    frags: Any,
    *,
    mode: Literal["replace", "append"],
    at: int | None,
    ids: Any,
    sid_ndim: int,
    block_dtype: Any = None,
) -> int:
    """Write CSR manifests to a dense index (:mod:`zarr_vectors.core.dense_manifests`),
    keeping its id table and ``layout`` stamp in step. Returns the first row written.
    """
    from zarr_vectors.core import dense_manifests as dense

    # Resolve the block dtype first, so a refusal fails before anything changes.
    recreate = mode == "replace" or not level_group.array_exists(dense.BLOCKS_PATH)
    dtype = dense.resolve_block_dtype(level_group, block_dtype, recreate=recreate)
    if mode == "replace" and level_group.array_exists(f"{OBJECT_INDEX}/manifests"):
        dense.fit_blocks(
            np.concatenate([
                np.asarray(coords, np.int64).reshape(-1, sid_ndim),
                np.asarray(frags, np.int64).reshape(-1, 1),
            ], axis=1), dtype, "writing object manifests",
        )
        oi = level_group.zarr_group.require_group(OBJECT_INDEX)
        for legacy in ("manifests", "data", "offsets"):
            if legacy in oi:
                del oi[legacy]
        level_group._invalidate_node(f"{OBJECT_INDEX}/manifests")
    fresh = not dense.is_dense(level_group)
    n = int(np.asarray(offsets).size) - 1
    n0 = 0 if fresh or mode == "replace" else dense.num_rows(level_group)
    start = n0 if at is None or mode == "replace" else int(at)
    new_ids = None
    if mode == "append" and not fresh:
        new_ids = _ids_for_append(level_group, start, n0, n, ids)
    first = dense.write(
        level_group, offsets, coords, frags, sid_ndim=sid_ndim, mode=mode, at=at,
        block_dtype=dtype,
    )
    meta = level_group.read_array_meta(OBJECT_INDEX) or {}
    level_group.write_array_meta(OBJECT_INDEX, {
        "zv_array": "object_index",
        **{k: v for k, v in meta.items() if k != "layout"},
        "sid_ndim": sid_ndim,
        "layout": dense.OBJECT_INDEX_LAYOUT_DENSE,
    })
    if mode == "append":
        if fresh:
            # A new index: ids are the rows unless the caller named them.
            table = (
                np.arange(first + n, dtype=np.int64) if ids is None
                else np.concatenate([
                    np.arange(first, dtype=np.int64),
                    np.asarray(ids, dtype=np.int64).reshape(-1),
                ])
            )
            level_group.write_array(
                f"{OBJECT_INDEX}/{OBJECT_IDS_ARRAY}", table,
                chunks=(OBJECT_INDEX_MANIFEST_BUCKET,),
                shards=_object_shards(level_group, (OBJECT_INDEX_MANIFEST_BUCKET,)),
                compressors=dense.manifest_codecs(level_group),
            )
            level_group.write_array_meta(OBJECT_INDEX, {
                OBJECT_IDS_SORTED_ATTR: bool(np.all(np.diff(table) > 0)),
            })
        elif new_ids is not None:
            n_ids = int(level_group.zarr_group[f"{OBJECT_INDEX}/{OBJECT_IDS_ARRAY}"].shape[0])
            if start > n_ids:
                # Padding rows of an identity table: their ids are their rows.
                new_ids = np.concatenate([np.arange(n_ids, start, dtype=np.int64), new_ids])
                _extend_object_id_table(level_group, n_ids, new_ids)
            else:
                _extend_object_id_table(level_group, start, new_ids)
    return first


def _write_object_index_manifests(
    level_group: Group,
    manifest_blobs: Any,
    *,
    mode: Literal["replace", "append"] = "replace",
    at: int | None = None,
    ids: Any = None,
    layout: str | None = None,
    block_dtype: Any = None,
) -> int:
    """Write ``object_index/manifests`` as a single ragged vlen-bytes array.

    One zarr chunk holds ``OBJECT_INDEX_MANIFEST_BUCKET`` consecutive
    objects, so a single-object read fetches at most one chunk regardless
    of total ``num_objects`` — fixing the legacy O(num_objects) read
    amplification.  Drops legacy ``object_index/{data,offsets}`` arrays
    if they exist from a prior write.

    ``mode="append"`` extends the existing array instead of recreating it,
    touching only the zarr chunks the new rows land in.  The default
    ``"replace"`` rewrites every row, which is correct but costs the whole
    index on each call — with one call per spatial chunk that is
    O(chunks x objects) over a build, and it is the write-side twin of the
    read amplification the bucketing above fixed.

    ``at`` is the row index the appended blobs must start at.  Pass it when
    the caller knows the object-id it is claiming (the index metadata's
    count) so a torn previous flush cannot silently shift ids: a short array
    is padded with empty manifests up to ``at``, and an array already longer
    than ``at`` (residue past the commit point) falls back to a full
    rewrite that truncates it.  ``None`` means "append at the current end".

    ``manifest_blobs`` may be a list of ``bytes`` or an object array of
    them. On an index that stores its object ids (V2), an append also
    extends the id table: with ``ids=`` when given, else as the identity
    when the table is the identity, else it raises (see
    :func:`_ids_for_append`). Replace mode leaves ids to the caller, as
    :func:`write_object_index` does.

    On a dense index (see :mod:`zarr_vectors.core.dense_manifests`) the
    blobs are decoded to arrays and written there instead; ``layout``
    (and ``block_dtype``) chooses for an index this call creates.

    Returns:
        The row the written blobs start at.
    """
    manifest_blobs = _object_array(manifest_blobs)
    if _index_layout_for_write(level_group, layout) == "dense":
        sid = _index_sid_ndim(level_group)
        offsets, coords, frags = decode_object_manifests_csr(list(manifest_blobs), sid)
        return _write_dense_index(
            level_group, offsets, coords, frags,
            mode=mode, at=at, ids=ids, sid_ndim=sid, block_dtype=block_dtype,
        )
    from zarr_vectors.core import dense_manifests as dense

    dense.remove(level_group)
    n = len(manifest_blobs)
    oi_group = level_group.zarr_group.require_group(OBJECT_INDEX)

    if mode == "append":
        for legacy in ("data", "offsets"):
            if legacy in oi_group:
                del oi_group[legacy]
        existing = oi_group["manifests"] if "manifests" in oi_group else None
        n0 = int(existing.shape[0]) if existing is not None else 0
        start = n0 if at is None else int(at)
        if start < 0:
            raise ArrayError(f"Append index {at} is negative")
        new_ids = _ids_for_append(level_group, start, n0, n, ids)
        if existing is None or start < n0:
            # Nothing to extend, or the array reaches past where this append
            # must begin (a torn flush). Rebuild the whole thing: the
            # truncation is what makes the ids line up again, and zarr does
            # not promise to drop chunks beyond a shrink.
            head = (
                _object_array(existing[:start]) if existing is not None
                else np.empty(0, dtype=object)
            )
            pad = _empty_manifests(start - len(head))
            _write_object_index_manifests(
                level_group, np.concatenate([head, pad, manifest_blobs]),
            )
            if new_ids is not None:
                _extend_object_id_table(level_group, start, new_ids)
            return start
        if n == 0 and start == n0:
            return start
        rows = np.concatenate([
            _empty_manifests(start - n0), manifest_blobs,
        ])
        total = n0 + len(rows)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", UnstableSpecificationWarning)
            existing.resize((total,))
            existing[n0:total] = rows
        level_group._invalidate_node(f"{OBJECT_INDEX}/manifests")
        if new_ids is not None:
            _extend_object_id_table(level_group, start, new_ids)
        return start

    # Asked before the old array goes, so a full rewrite keeps its shards.
    shards = _object_shards(level_group, (OBJECT_INDEX_MANIFEST_BUCKET,))
    for legacy in ("manifests", "data", "offsets"):
        if legacy in oi_group:
            del oi_group[legacy]

    if n == 0:
        return 0

    # A fixed bucket, NOT clamped to the current blob count -- the same rule
    # and the same reason as ``write_object_attributes`` below, and as
    # ``ObjectIndexAppender._open_manifests_truncated``, which both already
    # pass the constant unconditionally.
    #
    # Clamping here was silently catastrophic, because ``mode="append"`` on an
    # absent array routes through this branch with only the FIRST caller's
    # blobs, and every later append merely ``resize()``s -- which cannot change
    # ``chunk_shape``. In a per-spatial-chunk parallel build the first flush is
    # whichever worker won the store lock, typically a sparse edge chunk
    # emitting a few dozen objects, so a 19.5M-object index inherited a
    # ~20-blob chunk and materialised ~933,000 files in one directory instead
    # of ~1,200. That exhausted a 1,000,000-inode filesystem quota mid-run and
    # took the build down with EDQUOT. Two stores built by identical code
    # differed 20x in file count on first-write ordering alone.
    #
    # Zarr allows a chunk larger than the array, and only materialises chunks
    # that intersect the shape, so a small store still costs exactly one file.
    chunk_size = OBJECT_INDEX_MANIFEST_BUCKET
    # zarr 3.x's variable-length bytes dtype lacks a finalised V3 spec
    # (zarr-extensions tracks it); the warning is informational and Zarr Vectors
    # is alpha — accept it and silence at the call site so writes stay
    # quiet.  Revisit if the spec lands incompatibly.
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", UnstableSpecificationWarning)
        arr = oi_group.create_array(
            "manifests",
            shape=(n,),
            chunks=(chunk_size,),
            shards=shards,
            dtype="bytes",
            serializer=VLenBytesCodec(),
        )
        arr[:] = manifest_blobs
    return 0


def write_object_attributes(
    level_group: Group,
    attr_name: str,
    data: npt.NDArray,
    *,
    present_mask: npt.NDArray | None = None,
    fill_value: Any = None,
    mode: Literal["replace", "append", "place"] = "replace",
    at: int | None = None,
) -> None:
    """Write dense O×C object attribute data as a single Zarr v3 array.

    The array is stored at ``object_attributes/<attr_name>`` as a standard
    chunked Zarr v3 array.  Absent rows (selected by ``present_mask``)
    are encoded in-band using ``fill_value`` — no sibling
    ``present_mask`` child array is written.  Stock Zarr v3 tooling can
    read the array without library-specific decoding; absent positions
    are visible as the array's ``fill_value`` (also returned for any
    chunk that was never written).

    Args:
        level_group: Resolution level group.
        attr_name: Attribute name.
        data: ``(O,)`` or ``(O, C)`` array.  In ``mode="append"`` this is
            the NEW rows to append.
        present_mask: Optional ``(O,)`` byte array (``0``/``1`` per
            object) marking real rows.  When provided, absent rows
            (``mask[i] == 0``) are overwritten with ``fill_value`` before
            write; callers that already encoded sentinels in ``data``
            should leave this ``None``.
        fill_value: Sentinel for absent positions.  Defaults to NaN for
            floats, dtype-min for signed ints, dtype-max for unsigned
            ints (see :func:`_default_fill_value_for_dtype`).  Used both
            as the in-array sentinel for masked rows and as the array's
            persisted ``fill_value``.
        mode: ``"replace"`` (default) writes ``data`` as the full array.
            ``"append"`` reads the existing array, concatenates ``data``
            along axis 0, writes back.  Existing dtype wins on dtype
            mismatch (new rows are cast).  ``"append"`` against a
            missing attribute behaves like ``"replace"``.
        at: Row index the appended rows must start at (``mode="append"``
            only) — the object-id being claimed.  The attribute-side twin
            of :func:`write_object_manifests`'s ``at``, and the reason to
            pass it is the same: nothing on disk ties a row to an object,
            so row ``i`` means object ``i`` by position alone, and a
            column that drifted from the index silently rebinds every
            later append to the wrong object.  A column short of ``at`` is
            padded with ``fill_value``; a column reaching past it (the
            residue of a flush killed before it committed, whose rows no
            reader can address) is truncated back to ``at``.  ``None``
            appends at the current end.  With ``mode="place"``, the first
            of the reserved rows ``[at, at + n)`` to write in place (see
            :func:`write_object_attribute_columns`).

    Raises:
        ArrayError: If ``mode`` is invalid, ``at`` is negative or given
            with ``mode="replace"``, ``present_mask`` length mismatches
            ``data``, the dtype has no default sentinel and no
            ``fill_value`` is given, or the appended row shape
            (everything beyond axis 0) does not match the existing array.

    Concurrency:
        ``mode="append"`` is read-modify-write and NOT cross-writer-safe.
        Callers must serialise concurrent appends to the same attribute.
        ``at`` makes a serialised writer *idempotent* — a retry lands on
        the same rows — it does not make concurrent writers safe.
    """
    if mode == "place":
        if at is None:
            raise ArrayError('mode="place" needs at=')
        rows = np.asarray(data)
        if present_mask is not None:
            node = level_group.zarr_group[f"{OBJECT_ATTRIBUTES}/{attr_name}"]
            mask = np.asarray(present_mask).astype(bool).reshape(-1)
            if mask.size != rows.shape[0]:
                raise ArrayError(
                    f"present_mask has {mask.size} rows; data has {rows.shape[0]}"
                )
            rows = rows.astype(node.dtype, copy=True)
            rows[~mask] = node.fill_value if fill_value is None else fill_value
        from zarr_vectors.core.object_rows import place_attribute_columns

        place_attribute_columns(level_group, {attr_name: rows}, at)
        return
    if mode not in ("replace", "append"):
        raise ArrayError(
            f"mode must be 'replace', 'append' or 'place', got {mode!r}"
        )
    if at is not None:
        if mode != "append":
            raise ArrayError("at= requires mode='append'")
        at = int(at)
        if at < 0:
            raise ArrayError(f"at must be >= 0, got {at}")

    data = np.asarray(data)
    full_name = f"{OBJECT_ATTRIBUTES}/{attr_name}"

    appending = (
        mode == "append"
        and level_group.standalone_array_exists(full_name)
    )
    if appending:
        # Shape and dtype come from the array METADATA, not from reading it.
        # Reading decompresses every existing row to check the tail dimensions
        # of the new ones — the check is O(1) information and the read is the
        # whole column, paid once per appending caller.
        meta = level_group.read_array_meta(full_name) or {}
        existing_shape = tuple(meta.get("shape") or ())
        existing_dtype = np.dtype(meta["dtype"]) if meta.get("dtype") else None
        if not existing_shape or existing_dtype is None:
            # Metadata too thin to trust — fall back to the read form, which
            # derives both from the data itself.
            existing = level_group.read_array(full_name)
            existing_shape = existing.shape
            existing_dtype = existing.dtype
        else:
            existing = None
        if tuple(existing_shape[1:]) != tuple(data.shape[1:]):
            raise ArrayError(
                f"append shape mismatch: existing {existing_shape} vs "
                f"new {data.shape} — tail dimensions must match"
            )
        # Existing dtype wins on conflict; new rows are cast.
        new_rows = data.astype(existing_dtype, copy=False)
        target_dtype = existing_dtype
    else:
        existing = None
        existing_shape = (0,) + tuple(data.shape[1:])
        new_rows = data
        target_dtype = data.dtype

    # Where the new rows land.  ``at`` is a claim about object ids, so it
    # wins over the array's current length in both directions: short pads,
    # long truncates.
    n0 = int(existing_shape[0]) if existing_shape else 0
    start = n0 if at is None else at

    if fill_value is None:
        fill_value = _default_fill_value_for_dtype(target_dtype)

    if present_mask is not None:
        mask_arr = np.asarray(present_mask, dtype=bool)
        if mask_arr.shape[0] != data.shape[0]:
            raise ArrayError(
                f"present_mask length {mask_arr.shape[0]} != data row "
                f"count {data.shape[0]}"
            )
        new_rows = new_rows.copy()
        new_rows[~mask_arr] = fill_value

    def _attrs(shape) -> dict:
        return {
            "zv_array": "object_attribute",
            "name": attr_name,
            "dtype": str(target_dtype),
            "shape": list(shape),
            "fill_sentinel_meaning": "absent",
        }

    def _gap(n: int) -> npt.NDArray:
        """``n`` absent rows — the sentinel, at the column's row shape."""
        return np.full((n, *new_rows.shape[1:]), fill_value, dtype=target_dtype)

    if appending and existing is None and start >= n0:
        # Grow in place: only the chunks the new rows land in are rewritten.
        # ``extend_array`` restamps ``shape`` from the resized array — taking
        # it from the metadata read above would propagate that metadata's own
        # drift, and it is exactly the number the O(1) length readers trust.
        # The other attrs keys do not change on an append.
        if start > n0:
            level_group.extend_array(full_name, _gap(start - n0))
        level_group.extend_array(full_name, new_rows)
        return

    if appending:
        # Either the metadata was too thin to grow in place, or ``at`` reaches
        # back into rows already written.  Both need the whole column: zarr
        # does not promise to drop chunks beyond a shrink, so the truncation
        # that realigns the ids has to be a rewrite.
        if existing is None:
            existing = level_group.read_array(full_name)
        head = np.asarray(existing)[:start]
        if head.shape[0] < start:
            head = np.concatenate([head, _gap(start - head.shape[0])], axis=0)
        write_data = np.concatenate([head, new_rows], axis=0)
    elif start > 0:
        # First write of a column that starts partway up the object table.
        write_data = np.concatenate([_gap(start), new_rows], axis=0)
    else:
        write_data = new_rows

    # A fixed row chunk, so a later append rewrites at most one chunk instead
    # of the whole column. NOT clamped to the current row count: the first
    # flush of a per-spatial-chunk build is small, and sizing the chunk to it
    # would leave a 27M-row column split into hundreds of thousands of them.
    # Zarr allows a chunk larger than the array.
    chunks = (OBJECT_ATTRIBUTE_ROW_BUCKET, *write_data.shape[1:])
    level_group.write_array(
        full_name, write_data,
        chunks=chunks,
        shards=_object_shards(level_group, chunks),
        fill_value=fill_value,
        attributes=_attrs(write_data.shape),
    )


def write_object_attribute_columns(
    level_group: Group,
    columns: Mapping[str, Any],
    *,
    mode: Literal["replace", "append", "place"] = "append",
    at: int | None = None,
    fill_values: Any = None,
) -> None:
    """Write several object attribute columns in one call.

    Leaves the store as one :func:`write_object_attributes` call per column
    would, but columns that grow in place are extended concurrently.

    Args:
        columns: ``{name: rows}``; device arrays are copied to the host once.
        mode: ``"append"`` (default), ``"replace"``, or ``"place"`` (rows
            ``[at, at + n)`` of columns sized by
            :func:`~zarr_vectors.core.object_rows.reserve_object_rows`, for
            processes writing disjoint ranges at once).
        at: Row the new rows start at, as for :func:`write_object_attributes`.
        fill_values: Absent-row sentinel: one value, or a mapping by name
            (missing names use the dtype default).
    """
    from concurrent.futures import ThreadPoolExecutor

    import zarr

    from zarr_vectors import _xp

    def _fill(name: str) -> Any:
        if isinstance(fill_values, Mapping):
            return fill_values.get(name)
        return fill_values

    host = {name: _xp.to_host(col) for name, col in columns.items()}
    if mode == "place":
        from zarr_vectors.core.object_rows import place_attribute_columns

        if at is None:
            raise ArrayError('mode="place" needs at=')
        place_attribute_columns(level_group, host, at)
        return
    if mode != "append":
        for name, data in host.items():
            write_object_attributes(
                level_group, name, data, mode=mode, at=at, fill_value=_fill(name),
            )
        return
    if at is not None and int(at) < 0:
        raise ArrayError(f"at must be >= 0, got {at}")

    grow: list[tuple[str, npt.NDArray, Any]] = []
    for name, data in host.items():
        full_name = f"{OBJECT_ATTRIBUTES}/{name}"
        node = level_group._lookup_node(full_name)
        meta = _zvc.unwrap_array_meta(node.attrs) if isinstance(node, zarr.Array) else {}
        shape = tuple(meta.get("shape") or ())
        n0 = int(shape[0]) if shape else 0
        start = n0 if at is None else int(at)
        if not shape or not meta.get("dtype") or start < n0:
            write_object_attributes(
                level_group, name, data, mode="append", at=at, fill_value=_fill(name),
            )
            continue
        if tuple(shape[1:]) != tuple(data.shape[1:]):
            raise ArrayError(
                f"append shape mismatch for {name!r}: existing {shape} vs "
                f"new {data.shape} — tail dimensions must match"
            )
        dtype = np.dtype(meta["dtype"])
        fill = _fill(name)
        if fill is None:
            fill = _default_fill_value_for_dtype(dtype)
        block = np.concatenate([
            np.full((start - n0, *data.shape[1:]), fill, dtype=dtype),
            data.astype(dtype, copy=False),
        ])
        if block.shape[0]:
            grow.append((full_name, block, node))

    if not grow:
        return
    with ThreadPoolExecutor(max_workers=min(8, len(grow))) as pool:
        for fut in [
            pool.submit(level_group.extend_array, path, rows, _node=node)
            for path, rows, node in grow
        ]:
            fut.result()


def read_object_attribute_present_mask(
    level_group: Group,
    attr_name: str,
) -> npt.NDArray[np.uint8] | None:
    """Reconstruct the ``(O,)`` byte present-mask for an object attribute.

    The 0.8.1 layout stores absence in-band via ``fill_value`` rather
    than as a sibling ``present_mask`` array, so this reader compares
    each row against the stored fill on the fly.  A row counts as
    "absent" only if every channel equals the sentinel.

    Returns:
        ``uint8`` mask (``1`` = present, ``0`` = absent), or ``None``
        when every row is present (so callers can skip allocating a
        full mask).  Also returns ``None`` when the attribute is
        missing.
    """
    full_name = f"{OBJECT_ATTRIBUTES}/{attr_name}"
    if not level_group.standalone_array_exists(full_name):
        return None

    data = level_group.read_array(full_name)
    fill = level_group.read_array_fill_value(full_name)

    # NaN ≠ NaN, so detect via isnan for any float-like fill (Python
    # float or numpy float scalar — zarr can return either).
    fill_is_nan = False
    if data.dtype.kind == "f":
        try:
            fill_is_nan = bool(np.isnan(fill))
        except (TypeError, ValueError):
            fill_is_nan = False
    if fill_is_nan:
        absent_per_elem = np.isnan(data)
    else:
        absent_per_elem = (data == fill)

    if data.ndim == 1:
        absent = absent_per_elem
    else:
        # Row "absent" iff every channel equals the sentinel.
        absent = absent_per_elem.reshape(data.shape[0], -1).all(axis=1)

    if not absent.any():
        return None
    return (~absent).astype(np.uint8)


def write_groupings(
    level_group: Group,
    groups: dict[int, list[int] | range],
) -> None:
    """Write group memberships as a single vlen-bytes Zarr v3 array.

    Each row of the array at ``groups/`` is the byte-serialised int64
    member list of one group, addressable by integer index.  This
    replaces the legacy ``groups/data`` + ``groups/offsets`` CSR pair
    with the same vlen layout already used by ``object_index/manifests``.

    A group whose members form a contiguous ``range(start, stop)`` may be
    passed as a ``range`` object.  It is stored implicitly as a
    ``[start, stop)`` descriptor in the array's ``group_ranges`` attribute
    (with an empty placeholder row), so a billion-member contiguous group
    costs O(1) on disk and in memory instead of an 8-byte-per-member int64
    list.  Explicit (non-range) groups keep their exact byte layout, so
    older stores remain readable.

    Args:
        level_group: Resolution level group.
        groups: ``{group_id: [object_id, ...] | range, ...}``.
            Group IDs must be contiguous starting from 0.  A ``range``
            value must have ``step == 1``.
    """
    if not groups:
        return

    max_gid = max(groups.keys())
    blobs: list[bytes] = []
    group_ranges: dict[str, list[int]] = {}
    for gid in range(max_gid + 1):
        members = groups.get(gid, [])
        if isinstance(members, range) and len(members) > 0:
            if members.step != 1:
                raise ArrayError(
                    f"range group {gid} must have step 1, got {members.step}"
                )
            group_ranges[str(gid)] = [members.start, members.stop]
            blobs.append(b"")  # implicit — members live in group_ranges
        else:
            arr = np.array(list(members), dtype=np.int64)
            blobs.append(arr.tobytes())

    attributes: dict[str, Any] = {
        "zv_array": "groups",
        "num_groups": max_gid + 1,
    }
    if group_ranges:
        attributes["group_ranges"] = group_ranges

    level_group.write_vlen_array(GROUPS, blobs, attributes=attributes)


def write_groupings_attributes(
    level_group: Group,
    attr_name: str,
    data: npt.NDArray,
) -> None:
    """Write dense G×C groupings attribute data as a single Zarr v3 array.

    Stored at ``group_attributes/<attr_name>`` as a standard chunked
    Zarr v3 array.  Unlike :func:`write_object_attributes`, no
    sentinel / present-mask handling — groupings attributes are always
    fully populated.

    Args:
        level_group: Resolution level group.
        attr_name: Attribute name.
        data: ``(G,)`` or ``(G, C)`` array.
    """
    data = np.asarray(data)
    full_name = f"{GROUP_ATTRIBUTES}/{attr_name}"
    level_group.write_array(
        full_name, data,
        attributes={
            "zv_array": "groupings_attribute",
            "name": attr_name,
            "dtype": str(data.dtype),
            "shape": list(data.shape),
        },
    )


@dataclass
class LinkPartition:
    """Per-input-record placement map returned by :func:`write_links`.

    Pass to :func:`write_link_attributes` to align per-record attribute
    data with the ``(offsets, cell)`` layout the link writer chose.

    Attributes:
        cell_indices: Maps ``(offsets_segment, source_chunk)`` → list of
            indices into the input ``links`` list.  Within each bucket
            indices preserve input ordering, so attribute data passed in
            input order partitions deterministically.  Under
            ``store="duplicate"`` one input index appears under several
            buckets — that is what makes the parallel attribute family
            replicate identically.
        num_links: **Logical** record count after the write — one per
            input record, regardless of how many physical copies
            ``store="duplicate"`` filed.  For ``append`` mode this
            includes pre-existing records.  This is the count
            :func:`write_link_attributes` validates ``attr_data``
            against, since ``attr_data`` is in input order.
        num_physical_records: On-disk row count after the write.  Equal
            to ``num_links`` for a ``canonical`` family; larger for a
            ``duplicate`` one.
        first_new: The input-order row index of the first newly-appended
            record.  ``0`` for ``replace`` mode, the pre-existing logical
            count for ``append`` mode.
    """

    cell_indices: dict[tuple[str, ChunkCoords], list[int]]
    num_links: int
    num_physical_records: int = 0
    first_new: int = 0

    def __int__(self) -> int:
        # Lets callers that did ``first_new = int(write_links(...))``
        # keep working.
        return self.first_new


def _normalise_link_records(
    links: list[list[tuple[ChunkCoords, int]]] | list[CrossChunkLink],
    link_width: int | None,
    sid_ndim: int,
    delta: int,
) -> tuple[list[list[tuple[ChunkCoords, int]]], int]:
    """Normalise record input to list-of-lists and resolve link_width.

    Accepts the legacy ``((chunk_a, vi_a), (chunk_b, vi_b))`` 2-tuple form
    or a list of ``(chunk_coords, vi)`` endpoint lists.  Validates record
    arity against ``link_width`` (inferred from the first record if omitted)
    and every chunk-coord arity against ``sid_ndim``.
    """
    normalised: list[list[tuple[ChunkCoords, int]]] = []
    for rec in links:
        if (
            isinstance(rec, tuple)
            and len(rec) == 2
            and isinstance(rec[0], tuple)
            and not isinstance(rec[0][0], tuple)
        ):
            # Legacy CrossChunkLink: ((chunk_a, vi_a), (chunk_b, vi_b))
            normalised.append([rec[0], rec[1]])
        else:
            normalised.append(list(rec))

    if link_width is None:
        link_width = len(normalised[0])
    for rec in normalised:
        if len(rec) != link_width:
            raise ArrayError(
                f"links/{format_delta(delta)}: record arity "
                f"{len(rec)} != link_width {link_width}"
            )
        for chunk, _vi in rec:
            if len(chunk) != sid_ndim:
                raise ArrayError(
                    f"chunk coords arity mismatch in links/"
                    f"{format_delta(delta)}: sid_ndim={sid_ndim}, "
                    f"got len(chunk)={len(chunk)}"
                )
    return normalised, link_width


def _pad_scale(scale: Sequence[int], sid_ndim: int) -> tuple[int, ...]:
    """Fit a per-axis chunk-scale factor to ``sid_ndim`` axes.

    :func:`_derive_level_scales` derives its rank from the root
    ``chunk_shape``, i.e. the *spatial* rank.  Writers that chunk by an
    attribute prepend a bin axis to every chunk key (see
    :func:`open_write_session`'s ``bin_count``), so their ``sid_ndim`` is
    one larger.  That axis indexes bins, not space, and therefore never
    rescales across pyramid levels — pad with 1s at the front, which
    makes :func:`~zarr_vectors.spatial.boundary.anchor_chunk` a no-op on
    it.  Without this the rank check in ``partition_records_by_offset``
    rejects every attribute-binned store.
    """
    scale = tuple(int(s) for s in scale)
    if len(scale) == sid_ndim:
        return scale
    if len(scale) < sid_ndim:
        return (1,) * (sid_ndim - len(scale)) + scale
    return scale[len(scale) - sid_ndim:]


def _link_scales(
    level_group: Group, delta: int, sid_ndim: int,
) -> tuple[tuple[int, ...], tuple[int, ...]]:
    """``(scale_src, scale_trg)`` fitted to ``sid_ndim`` — see
    :func:`_derive_level_scales` and :func:`_pad_scale`."""
    scale_src, scale_trg = _derive_level_scales(level_group, delta)
    return _pad_scale(scale_src, sid_ndim), _pad_scale(scale_trg, sid_ndim)


def _partition_links(
    level_group: Group,
    records: Sequence[Sequence[tuple[ChunkCoords, int]]],
    link_width: int,
    sid_ndim: int,
    *,
    delta: int,
    directed: bool,
    store: str,
) -> dict[tuple[str, ChunkCoords], list[tuple[list[int], int, int]]]:
    """Bucket records into ``(offsets_segment, source_chunk)`` cells.

    The single choke point deciding where a record lands.  ``delta != 0``
    forces ``cross_level``, which keeps the source at the owning level so
    the anchor's ``scale_src`` is that level's — see
    :func:`~zarr_vectors.spatial.boundary.partition_records_by_offset`.
    """
    from zarr_vectors.spatial.boundary import partition_records_by_offset

    scale_src, scale_trg = _link_scales(level_group, delta, sid_ndim)
    return partition_records_by_offset(
        records, link_width, sid_ndim,
        scale_src=scale_src, scale_trg=scale_trg,
        directed=directed, store=store, cross_level=(delta != 0),
    )


def _check_link_family_policy(
    fam_meta: dict[str, Any],
    *,
    delta: int,
    link_width: int,
    sid_ndim: int,
    directed: bool,
    store: str,
    action: str,
) -> None:
    """Reject a write whose policy contradicts the existing family.

    ``directed`` / ``store`` / ``link_width`` / ``sid_ndim`` live on the
    ``links/<delta>/`` **group** precisely because several offset arrays
    sit under it and must agree — a per-array override would let two
    arrays in one family decode differently.  Absent keys mean "no
    opinion yet" and pass.
    """
    fam = f"links/{format_delta(delta)}"
    checks = (
        ("link_width", int(fam_meta.get("link_width", link_width)), link_width),
        ("sid_ndim", int(fam_meta.get("sid_ndim", sid_ndim)), sid_ndim),
        ("directed", bool(fam_meta.get("directed", directed)), bool(directed)),
        ("store", str(fam_meta.get("store", store)), str(store)),
    )
    for field, existing, requested in checks:
        if existing != requested:
            raise ArrayError(
                f"{fam}: cannot {action} it with {field}={requested!r} onto an "
                f"existing family with {field}={existing!r} — this policy is "
                f"family-wide (every offsets array under the delta shares it). "
                f"Drop the family first to change it."
            )


def _pack_link_rows(
    entries: Sequence[tuple[list[int], int, int]],
    *,
    has_perm: bool,
    link_width: int,
    dtype: np.dtype,
) -> npt.NDArray[np.integer]:
    """Build the ``(M, W)`` row block for one cell.

    ``W`` is ``link_width`` normally and ``1 + link_width`` when
    ``has_perm`` — see :func:`links_has_perm`, the single definition
    writer and reader both consult.
    """
    width = link_width + (1 if has_perm else 0)
    if isinstance(entries, np.ndarray):
        # Already an (M, W) block from an array partitioner, with the
        # perm column in place wherever the segment carries one.
        if entries.ndim != 2 or entries.shape[1] != width:
            raise ArrayError(
                f"packed link rows are {entries.shape[1] if entries.ndim == 2 else '?'} "
                f"wide; this segment stores {width} columns"
            )
        return np.ascontiguousarray(entries, dtype=dtype)
    out = np.empty((len(entries), width), dtype=dtype)
    for r, (vi, perm_idx, _input_idx) in enumerate(entries):
        if has_perm:
            out[r, 0] = perm_idx
            out[r, 1:] = vi
        else:
            out[r, :] = vi
    return out


def write_cross_level_links(
    level_group: Group,
    src_chunks: npt.NDArray[np.int64],
    src_vi: npt.NDArray[np.int64],
    trg_chunks: npt.NDArray[np.int64],
    trg_vi: npt.NDArray[np.int64],
    sid_ndim: int,
    *,
    delta: int,
    dtype: np.dtype | str = np.int64,
    mode: Literal["replace", "append"] = "replace",
) -> LinkPartition:
    """:func:`write_links` for two-endpoint cross-level records, in array form.

    The pyramid emits one record per fine vertex -- twice, under the
    default explicit storage -- and the record-shaped path spends about
    ten Python objects on each of them before any of it reaches the
    store. The endpoints arrive as arrays and there is no reason to take
    them apart: partitioning them is floor-divide, subtract, group by.

    Only the family bookkeeping is shared, by re-entering
    :func:`write_links` with the partition already built, so segment
    policy, counts and family metadata keep exactly one implementation.

    Args:
        level_group: The level that owns the family.
        src_chunks: ``(M, sid_ndim)`` chunk coords of endpoint 0.
        src_vi: ``(M,)`` chunk-local vertex index of endpoint 0.
        trg_chunks: ``(M, sid_ndim)`` chunk coords of endpoint 1.
        trg_vi: ``(M,)`` chunk-local vertex index of endpoint 1.
        sid_ndim: Spatial index dimensionality.
        delta: Level delta; must be non-zero, since an intra-level record
            is not what this path is for and would need the permutation
            machinery it deliberately omits.
        dtype: Row dtype.
        mode: ``"replace"`` or ``"append"``, as :func:`write_links`.
    """
    from zarr_vectors.spatial.boundary import partition_arrays_by_offset

    if delta == 0:
        raise ArrayError(
            "write_cross_level_links is for cross-level records; delta=0 "
            "records need the placement and permutation handling in "
            "write_links"
        )
    n_records = int(np.asarray(src_vi).shape[0])
    if n_records == 0:
        return LinkPartition(
            cell_indices={}, num_links=0, num_physical_records=0, first_new=0,
        )
    scale_src, scale_trg = _link_scales(level_group, delta, sid_ndim)
    buckets = partition_arrays_by_offset(
        src_chunks, src_vi, trg_chunks, trg_vi,
        scale_src=scale_src, scale_trg=scale_trg, sid_ndim=sid_ndim,
    )
    return write_links(
        level_group,
        [],
        sid_ndim,
        delta=delta,
        link_width=2,
        dtype=dtype,
        mode=mode,
        directed=True,
        _prepartitioned=buckets,
        _link_width=2,
        _num_records=n_records,
    )


def write_links(
    level_group: Group,
    links: list[list[tuple[ChunkCoords, int]]] | list[CrossChunkLink],
    sid_ndim: int,
    *,
    delta: int = 0,
    link_width: int | None = None,
    dtype: np.dtype | str = np.int64,
    mode: Literal["replace", "append"] = "replace",
    directed: bool = False,
    store: Literal["canonical", "duplicate"] = "canonical",
    fragment_starts: Mapping[ChunkCoords, npt.NDArray[np.integer]] | None = None,
    _prepartitioned: dict[tuple[str, ChunkCoords], Any] | None = None,
    _link_width: int | None = None,
    _num_records: int | None = None,
    _arrays: tuple[npt.NDArray[np.integer], npt.NDArray[np.integer]] | None = None,
) -> LinkPartition:
    """Write whole link records into ``links/<delta>/<offsets>/``.

    ``_arrays`` is the same input as ``links`` in array form --
    ``(chunks, vi)`` of shapes ``(M, L, sid_ndim)`` and ``(M, L)`` -- for
    a writer that holds its records that way already (the mesh and graph
    writers do); it saves building and taking apart one Python list per
    record.  Pass ``links=[]`` with it.

    The whole-family counterpart to :func:`write_chunk_links`: it takes
    records in *global* ``(chunk_coords, vertex_idx)`` form, decides where
    each one belongs, and fans them out across the offset arrays.  There
    is no separate cross-chunk family — a record whose endpoints all
    share one chunk lands in the all-zero-offsets array, one whose
    endpoints straddle chunks lands in the array named by the offsets
    between them.

    Each record is ``link_width`` endpoints.  ``link_width=2`` (the
    default) encodes an edge, ``3`` a triangle face, ``1`` a parent→child
    reference used by pyramid metanode drill-down.  Records may be passed
    as legacy 2-tuples or as endpoint lists.

    For ``delta != 0``, endpoint 0 is at the owning resolution level and
    endpoints k>0 are at ``this_level + delta``; the source is always
    endpoint 0 so offsets anchor against the owning level's chunk grid
    (see :func:`~zarr_vectors.spatial.boundary.anchor_chunk`).

    Args:
        level_group: Resolution level group.
        links: List of records; each a list of ``(chunk_coords,
            vertex_idx)`` tuples of length ``link_width``.
        sid_ndim: Number of spatial index dimensions.
        delta: Level delta; see :mod:`zarr_vectors.core.paths`.
        link_width: Endpoints per record.  Defaults to the arity of the
            first record.
        dtype: Integer dtype for the stored rows.
        mode: ``"replace"`` (default) rewrites, from scratch, exactly the
            offset arrays this call's records land in — see the warning
            below.  ``"append"`` adds the records as a new group in each
            target cell, leaving existing rows in place.
        directed: When ``True`` endpoint order is data (streamline
            predecessor→successor, skeleton child→parent): records are
            NOT canonical-sorted, so ``A→B`` and ``B→A`` file under
            opposite offsets (``0.0.+1`` vs ``0.0.-1``) and carry no
            ``perm_idx``.
        store: ``"canonical"`` (default) files each record once, under
            the lexicographically-positive offset.  ``"duplicate"`` files
            it once per distinct incident chunk, so every record incident
            to a chunk can be found by scanning that chunk's cell alone.
            Duplicated records are returned once per copy by
            :func:`read_links`; the parallel attribute family replicates
            identically via the returned partition.
        fragment_starts: Per chunk, the first row of each of its vertex
            fragments, for a writer whose fragments are contiguous row
            ranges tiling the chunk.  Each intra-chunk cell is then
            written as one link fragment per vertex fragment -- fragment
            ``k`` holding the records whose first stored endpoint is a
            row of vertex fragment ``k``, empty ones included -- which
            is the partition spec §7.5 gives ``link_fragments``.  Rows
            keep their input order within a fragment, and the returned
            partition follows the reordering, so link attributes still
            align.  ``delta=0`` and ``mode="replace"`` only.  ``None``
            (default) writes each cell as a single fragment.

    Returns:
        :class:`LinkPartition` describing where each input record landed.

    Warning:
        ``mode="replace"`` scopes its delete to the offset arrays this
        call's records actually target.  It deliberately does **not**
        clear the whole ``links/<delta>/`` family: intra-chunk links live
        under it now, so a family-wide wipe would silently destroy
        everything :func:`write_chunk_links` wrote.  The corollary is
        that an offset array populated by an *earlier* call that this
        call's records do not reach survives untouched — enumerate with
        :func:`list_link_offsets` and delete explicitly if you need a
        broader wipe.

    Concurrency:
        ``mode="append"`` is read-modify-write per cell — safe across
        disjoint cells, unsafe within a single cell.
    """
    if mode not in ("replace", "append"):
        raise ArrayError(
            f"mode must be 'replace' or 'append', got {mode!r}"
        )
    if store not in ("canonical", "duplicate"):
        raise ArrayError(
            f"store must be 'canonical' or 'duplicate', got {store!r}"
        )
    if fragment_starts is not None and (delta != 0 or mode != "replace"):
        raise ArrayError(
            "fragment_starts= groups intra-chunk links by vertex fragment, "
            f"which applies to delta=0 replace writes only (got delta={delta}, "
            f"mode={mode!r})"
        )
    if _arrays is not None and int(np.asarray(_arrays[1]).shape[0]) == 0:
        _arrays = None
    if not links and not _prepartitioned and _arrays is None:
        # Honour the empty-input fast-exit; emit an empty partition so
        # callers don't crash on attribute reflection.  NOTE this means
        # an empty `links` does NOT clear anything — callers wanting that
        # must delete the offset arrays themselves (list_link_offsets).
        return LinkPartition(
            cell_indices={}, num_links=0, num_physical_records=0, first_new=0,
        )

    dtype = np.dtype(dtype)
    if _prepartitioned is not None:
        # Records already partitioned by the caller -- see
        # ``write_cross_level_links``. Everything past this point is
        # family bookkeeping that must not be duplicated, which is why
        # the array path re-enters here rather than reimplementing it.
        buckets = _prepartitioned
        link_width = int(_link_width or link_width or 2)
        n_records = int(_num_records or 0)
    else:
        chunks_arr: npt.NDArray[np.int64] | None = None
        vi_arr: npt.NDArray[np.int64] | None = None
        if _arrays is not None:
            chunks_arr = np.asarray(_arrays[0], dtype=np.int64)
            vi_arr = np.asarray(_arrays[1], dtype=np.int64)
            if chunks_arr.ndim != 3 or vi_arr.ndim != 2 or chunks_arr.shape[:2] != vi_arr.shape:
                raise ArrayError(
                    f"links/{format_delta(delta)}: array records must be "
                    f"(M, L, sid_ndim) chunks and (M, L) indices, got "
                    f"{chunks_arr.shape} and {vi_arr.shape}"
                )
            if chunks_arr.shape[2] != sid_ndim:
                raise ArrayError(
                    f"chunk coords arity mismatch in links/"
                    f"{format_delta(delta)}: sid_ndim={sid_ndim}, "
                    f"got {chunks_arr.shape[2]}"
                )
            if link_width is None:
                link_width = int(vi_arr.shape[1])
            elif int(vi_arr.shape[1]) != link_width:
                raise ArrayError(
                    f"links/{format_delta(delta)}: record arity "
                    f"{vi_arr.shape[1]} != link_width {link_width}"
                )
            n_records = int(vi_arr.shape[0])
            if store == "duplicate":
                # One record files under several cells there; that is the
                # record partitioner's business.
                normalised = [
                    list(zip(map(tuple, cs), vs))
                    for cs, vs in zip(chunks_arr.tolist(), vi_arr.tolist())
                ]
                chunks_arr = vi_arr = None
        else:
            from zarr_vectors.spatial.boundary import _MAX_ARRAY_LINK_WIDTH

            normalised, link_width = _normalise_link_records(
                links, link_width, sid_ndim, delta,
            )
            n_records = len(normalised)
            if store == "canonical" and link_width <= _MAX_ARRAY_LINK_WIDTH:
                # The record form is what callers hand over; the array
                # partitioner is what decides where each lands, since it
                # does the same arithmetic without a Python object per
                # endpoint.
                chunks_arr = np.array(
                    [[c for c, _ in rec] for rec in normalised], dtype=np.int64,
                ).reshape(n_records, link_width, sid_ndim)
                vi_arr = np.array(
                    [[v for _, v in rec] for rec in normalised], dtype=np.int64,
                ).reshape(n_records, link_width)
        if chunks_arr is not None and vi_arr is not None:
            from zarr_vectors.spatial.boundary import partition_link_arrays

            scale_src, scale_trg = _link_scales(level_group, delta, sid_ndim)
            buckets = partition_link_arrays(
                chunks_arr, vi_arr, link_width=link_width, sid_ndim=sid_ndim,
                scale_src=scale_src, scale_trg=scale_trg,
                directed=directed, cross_level=(delta != 0),
            )
        else:
            buckets = _partition_links(
                level_group, normalised, link_width, sid_ndim,
                delta=delta, directed=directed, store=store,
            )
    family = links_group_path(delta)
    fam_meta = level_group.read_array_meta(family) or {}

    # Intra-chunk cells regrouped one link fragment per vertex fragment;
    # ``intra_split`` holds each regrouped cell's fragment sizes.
    intra_split: dict[tuple[str, ChunkCoords], npt.NDArray[np.int64]] = {}
    if fragment_starts is not None:
        buckets, intra_split = _group_intra_by_fragment(
            buckets, fragment_starts,
            sid_ndim=sid_ndim, link_width=link_width,
        )

    # Grouped once. The write loop below used to rescan every bucket for
    # each targeted segment, which is quadratic in the number of distinct
    # offset segments.
    by_segment: dict[str, list[tuple[ChunkCoords, Any]]] = {}
    for (bucket_seg, src_chunk), entries in buckets.items():
        # The array partitioner yields (rows, input_indices); only the
        # rows are written, the indices ride out in the partition.
        block = entries[0] if isinstance(entries, tuple) else entries
        by_segment.setdefault(bucket_seg, []).append((src_chunk, block))
    targeted: list[str] = sorted(by_segment)
    surviving = [
        seg for seg in list_link_offsets(level_group, delta)
        if seg not in targeted
    ]

    # An append never wipes, so it must agree with the family it joins.
    # A replace only has to agree when it leaves siblings behind: those
    # arrays keep decoding against the family group's policy, so letting
    # this call flip it would silently corrupt them.
    if fam_meta and (mode == "append" or surviving):
        _check_link_family_policy(
            fam_meta, delta=delta, link_width=link_width, sid_ndim=sid_ndim,
            directed=directed, store=store,
            action="append to" if mode == "append" else "replace part of",
        )

    if mode == "replace":
        first_new = 0
        existing_total = 0
        existing_physical = 0
        for seg in targeted:
            path = f"{family}/{seg}"
            if level_group.array_exists(path):
                level_group.delete_subtree(path)
    else:
        # Existing counts come from family meta in O(1); a family written
        # only by the decentralized per-cell writers has none until
        # ``finalize_links`` runs, so fall back to a scan.
        if "num_links" in fam_meta:
            existing_total = int(fam_meta["num_links"])
            existing_physical = int(
                fam_meta.get("num_physical_records", existing_total)
            )
        elif level_group._native_sharded_config is not None:
            # An open write session is mid-build: the scan below reads the
            # store, which does not see cells this session has queued but
            # not flushed, so it would count 0 and stamp that as the
            # family's total — and a later ``write_link_attributes``
            # validating ``len(attr_data) == num_links`` would then reject
            # correct data against a fabricated 0.  A family with no counts
            # and a session open has nothing durable to count; leave the
            # reconciliation to ``finalize_links`` after the session
            # closes, which is when the cells are actually readable.
            existing_total = 0
            existing_physical = 0
        else:
            counted = finalize_links(level_group, delta=delta)
            existing_total = counted.num_links
            existing_physical = counted.num_physical_records
        first_new = existing_total

    new_physical = 0
    segment_offsets = {
        seg: parse_offsets(seg, sid_ndim=sid_ndim, link_width=link_width)
        for seg in targeted
    }
    # Every targeted array in one allocation.  A mesh with random
    # geometry fans out to hundreds of offsets segments, a graph to well
    # over a thousand, and creating each through its own ``sync()`` cost
    # tens of milliseconds a segment -- a third of a mesh write.
    _create_links_arrays(
        level_group, list(segment_offsets.values()),
        link_width=link_width, dtype=str(dtype), delta=delta,
        sid_ndim=sid_ndim, directed=directed, store=store,
    )
    for seg in targeted:
        offsets = segment_offsets[seg]
        has_perm = links_has_perm(
            offsets, delta=delta, directed=directed, store=store,
        )
        if mode == "replace" and not (delta == 0 and is_intra(offsets)):
            # A fresh cross-offset array: every cell is one inline ragged
            # blob of the rows it was handed, so the whole segment goes
            # to the store as one batch of cells.  The per-cell writer
            # below is the definition of that encoding
            # (``encode_ragged_blob``, no sidecar) and stays the path for
            # appends, which have to merge with what a cell already holds.
            cells: list[tuple[str, bytes]] = []
            for src_chunk, entries in by_segment[seg]:
                rows = _pack_link_rows(
                    entries, has_perm=has_perm, link_width=link_width, dtype=dtype,
                )
                new_physical += rows.shape[0]
                cells.append((_chunk_key(src_chunk), encode_ragged_blob([rows], dtype)))
            level_group.write_cells(links_path(delta, offsets), cells)
            continue
        # Appending: the segment's stamped element type wins (see
        # write_link_cells). A replace owns the segment and keeps ``dtype``.
        seg_dtype = (
            _stamped_link_dtype(level_group, links_path(delta, offsets), dtype)
            if mode == "append" else np.dtype(dtype)
        )
        for src_chunk, entries in by_segment[seg]:
            rows = _cast_checked(
                _pack_link_rows(
                    entries, has_perm=has_perm, link_width=link_width, dtype=np.int64,
                ),
                seg_dtype, links_path(delta, offsets),
            )
            new_physical += rows.shape[0]
            groups: list[npt.NDArray] = []
            if mode == "append":
                groups = list(_decode_link_cell(
                    level_group, src_chunk, delta=delta, offsets=offsets,
                    dtype=seg_dtype, width=rows.shape[1], default=[],
                    trust_presence=False,
                ))
            sizes = intra_split.get((seg, src_chunk))
            if sizes is not None:
                groups.extend(np.split(rows, np.cumsum(sizes)[:-1]))
            else:
                groups.append(rows)
            # Route through the per-cell writer so the flat+sidecar vs
            # inline-blob choice has exactly one definition.
            write_chunk_links(
                level_group, src_chunk, groups, seg_dtype,
                delta=delta, offsets=offsets, link_width=link_width,
            )

    if surviving:
        # This call did not own the whole family, so the totals it can
        # see are partial.  Recount from disk — the same scan finalize
        # does — rather than stamp a number that is wrong.
        counted = finalize_links(level_group, delta=delta)
        new_total = counted.num_links
        new_physical_total = counted.num_physical_records
    else:
        new_total = existing_total + n_records
        new_physical_total = existing_physical + new_physical

    _stamp_link_family_meta(
        level_group, delta=delta, link_width=link_width, sid_ndim=sid_ndim,
        directed=directed, store=store, num_links=new_total,
        num_physical_records=new_physical_total,
    )

    return LinkPartition(
        cell_indices={
            k: (v[1] if isinstance(v, tuple) else [idx for _, _, idx in v])
            for k, v in buckets.items()
        },
        num_links=new_total,
        num_physical_records=new_physical_total,
        first_new=first_new,
    )


def _group_intra_by_fragment(
    buckets: dict[tuple[str, ChunkCoords], Any],
    fragment_starts: Mapping[ChunkCoords, npt.NDArray[np.integer]],
    *,
    sid_ndim: int,
    link_width: int,
) -> tuple[
    dict[tuple[str, ChunkCoords], Any],
    dict[tuple[str, ChunkCoords], npt.NDArray[np.int64]],
]:
    """Reorder each intra-chunk bucket so its rows run vertex fragment by
    vertex fragment, for :func:`write_links` ``fragment_starts=``.

    Returns the reordered buckets -- input indices permuted with the rows,
    so the partition built from them still names the record each stored
    row came from -- and, per regrouped bucket, the row count of every
    fragment (one per vertex fragment, zeros included).
    """
    intra_seg = format_offsets(intra_offsets(sid_ndim, link_width))
    out = dict(buckets)
    sizes: dict[tuple[str, ChunkCoords], npt.NDArray[np.int64]] = {}
    for (seg, src), entries in buckets.items():
        if seg != intra_seg:
            continue
        starts = fragment_starts.get(tuple(src))
        if starts is None:
            continue
        starts = np.asarray(starts, dtype=np.int64)
        if isinstance(entries, tuple):
            rows, idx = np.asarray(entries[0]), np.asarray(entries[1])
            first = rows[:, 0]
        else:
            first = np.fromiter(
                (vi[0] for vi, _, _ in entries), dtype=np.int64, count=len(entries),
            )
        # Intra-chunk rows carry no perm_idx (links_has_perm), so column
        # 0 is the first stored endpoint.
        owner = np.searchsorted(starts, first, side="right") - 1
        if owner.size and int(owner.min()) < 0:
            raise ArrayError(
                f"links in chunk {src} reference rows before the chunk's "
                f"first vertex fragment (starts at {int(starts[0])})"
            )
        order = np.argsort(owner, kind="stable")
        if isinstance(entries, tuple):
            out[(seg, src)] = (rows[order], idx[order])
        else:
            out[(seg, src)] = [entries[i] for i in order.tolist()]
        sizes[(seg, src)] = np.bincount(owner, minlength=len(starts)).astype(np.int64)
    return out, sizes


def _stamp_link_family_meta(
    level_group: Group,
    *,
    delta: int,
    link_width: int,
    sid_ndim: int,
    directed: bool,
    store: str,
    num_links: int | None = None,
    num_physical_records: int | None = None,
) -> None:
    """Write the ``links/<delta>/`` group's family-wide attributes.

    Policy (``link_width`` / ``sid_ndim`` / ``directed`` / ``store``)
    lives here rather than on the arrays because every offsets array
    under the delta must agree on it.  The counts are family-wide totals
    across all of them; the decentralized per-cell writers leave them
    absent for :func:`finalize_links` to fill in.
    """
    meta: dict[str, Any] = {
        "zv_array": "links_family",
        "level_delta": int(delta),
        "link_width": int(link_width),
        "sid_ndim": int(sid_ndim),
        "directed": bool(directed),
        "store": str(store),
    }
    if num_links is not None:
        meta["num_links"] = int(num_links)
    if num_physical_records is not None:
        meta["num_physical_records"] = int(num_physical_records)
    _ensure_array_dir(level_group, links_group_path(delta))
    level_group.write_array_meta(links_group_path(delta), meta)


def write_link_attributes(
    level_group: Group,
    attr_name: str,
    attr_data: npt.NDArray,
    *,
    num_links: int,
    delta: int = 0,
    mode: Literal["replace", "append"] = "replace",
    partition: LinkPartition | None = None,
) -> None:
    """Write per-link attribute data parallel to ``links/<delta>/``.

    The whole-family counterpart to :func:`write_chunk_link_attributes`.
    Attribute rows are stored per ``(offsets, cell)``, one row per link
    record, in the same order the link writer used — that positional
    alignment is the whole contract.

    ``attr_data`` is in **input order** — the same ordering passed to the
    matching :func:`write_links` call, whose returned ``partition``
    supplies the mapping.  Without a ``partition`` the writer re-derives
    one by reading the link records back, which only recovers *on-disk*
    order, so ``attr_data`` must then already be in the enumeration order
    :func:`read_links` returns (each offsets segment sorted, then each
    cell sorted).

    Args:
        level_group: Resolution level group.
        attr_name: Attribute name.
        attr_data: ``(num_links,)`` or ``(num_links, C)`` array in
            **input order**.  In ``mode="append"`` this is the NEW rows;
            the post-append total must equal ``num_links``.
        num_links: Expected post-write logical record count (matches
            :attr:`LinkPartition.num_links`).
        delta: Level delta.
        mode: ``"replace"`` (default) rewrites exactly the offset arrays
            the partition targets — same scoping rule, and same caveat,
            as :func:`write_links`.  ``"append"`` per-cell RMW.
        partition: :class:`LinkPartition` from the matching
            :func:`write_links` call.  Required for ``append`` and for
            any ``store="duplicate"`` family.

    Raises:
        ArrayError: If ``mode`` is invalid, if the row count of
            ``attr_data`` does not match ``num_links`` (replace) or the
            new-row count derived from ``partition`` (append), or if the
            appended row shape does not match an existing array.

    Concurrency:
        ``mode="append"`` is read-modify-write per cell — safe across
        disjoint cells, unsafe within a single cell.
    """
    if mode not in ("replace", "append"):
        raise ArrayError(
            f"mode must be 'replace' or 'append', got {mode!r}"
        )

    arr = np.ascontiguousarray(np.asarray(attr_data))
    fam_meta = level_group.read_array_meta(links_group_path(delta)) or {}

    # Resolve the partition.  Append mode requires it explicitly — only
    # the matching write_links call knows which cell each new attribute
    # row belongs to.  Replace mode can fall back to re-deriving from
    # disk (assumes ``attr_data`` is in on-disk enumeration order).
    if partition is None:
        if mode == "append":
            raise ArrayError(
                f"link_attributes[{attr_name}] append mode requires "
                f"partition=... from the matching write_links(mode='append') "
                f"call so the writer knows which cell each new row belongs to"
            )
        # A duplicate family fans one input record across several cells;
        # only the link writer's partition records that fan-out, so the
        # re-derived (physical, positional) partition would misalign
        # attribute rows.  Require the partition explicitly.
        if str(fam_meta.get("store", "canonical")) == "duplicate":
            raise ArrayError(
                f"link_attributes[{attr_name}]: store='duplicate' requires "
                f"partition=... from the matching write_links call so "
                f"replicated rows align"
            )
        partition = _derive_partition_from_links(level_group, delta)

    link_width = int(fam_meta.get("link_width", 2))
    targeted = sorted({seg for seg, _chunk in partition.cell_indices})

    if mode == "replace":
        if arr.shape[0] != num_links:
            raise ArrayError(
                f"link_attributes[{attr_name}] row count {arr.shape[0]} != "
                f"num_links {num_links} (delta={format_delta(delta)})"
            )
        if arr.shape[0] != partition.num_links:
            raise ArrayError(
                f"link_attributes[{attr_name}] attr rows {arr.shape[0]} != "
                f"link records {partition.num_links} derived from "
                f"links/{format_delta(delta)}"
            )
        # Scoped exactly like write_links: only the offset arrays this
        # partition targets, never the whole family.
        for seg in targeted:
            path = f"{link_attributes_group_path(attr_name, delta)}/{seg}"
            if level_group.array_exists(path):
                level_group.delete_subtree(path)
    else:
        # Append mode.  The post-append total record count must equal
        # num_links; arr.shape[0] is the new-row count.
        new_count = sum(len(v) for v in partition.cell_indices.values())
        if arr.shape[0] != new_count:
            raise ArrayError(
                f"link_attributes[{attr_name}] append: attr_data row count "
                f"{arr.shape[0]} != new link record count {new_count} "
                f"(delta={format_delta(delta)})"
            )
        if partition.num_links != num_links:
            raise ArrayError(
                f"link_attributes[{attr_name}] row count "
                f"{partition.num_links} != num_links {num_links} "
                f"(delta={format_delta(delta)})"
            )

    sid_ndim = int(fam_meta.get("sid_ndim", 0)) or None
    for seg in targeted:
        offsets = _parse_offsets_for_family(
            seg, sid_ndim=sid_ndim, link_width=link_width, partition=partition,
        )
        create_link_attributes_array(
            level_group, attr_name, dtype=str(arr.dtype), delta=delta,
            sid_ndim=sid_ndim, link_width=link_width, offsets=offsets,
            exist_ok=True, row_shape=arr.shape[1:],
        )
        full_name = link_attributes_path(attr_name, delta, offsets)
        cells = [
            (_chunk_key(src_chunk), input_idxs)
            for (bucket_seg, src_chunk), input_idxs in partition.cell_indices.items()
            if bucket_seg == seg
        ]
        if mode == "append":
            target, blobs = _link_attr_target_dtype(
                level_group, full_name, [k for k, _ in cells], arr.dtype,
            )
        else:
            target, blobs = arr.dtype, {}
        for key, input_idxs in cells:
            new_rows = _cast_checked(
                arr[np.asarray(input_idxs, dtype=np.int64)], target, full_name,
            )
            blob = blobs.get(key)
            if blob:
                existing = _read_attr_cell(level_group, full_name, key, new_rows, blob=blob)
                combined = np.concatenate([existing, new_rows], axis=0)
            else:
                combined = new_rows
            level_group.write_bytes(
                full_name, key, np.ascontiguousarray(combined).tobytes(),
            )
        # ``row_shape`` (the tail dims per row, ``()`` for 1-D) lets the
        # reader reconstruct shape from a bare byte blob.  Stamped only
        # when it differs: the values settle on the first batch, and a
        # pre-created segment may lack ``row_shape`` or carry a dtype the
        # data does not have.
        _write_array_meta_if_changed(level_group, full_name, {
            "zv_array": "link_attribute",
            "name": attr_name,
            "dtype": str(target),
            "row_shape": list(arr.shape[1:]),
            "offsets": [list(int(c) for c in o) for o in offsets],
            "level_delta": int(delta),
        })

    _ensure_array_dir(level_group, link_attributes_group_path(attr_name, delta))
    level_group.write_array_meta(link_attributes_group_path(attr_name, delta), {
        "zv_array": "link_attribute_family",
        "name": attr_name,
        "level_delta": int(delta),
        "num_links": int(num_links),
    })


def _read_attr_cell(
    level_group: Group, full_name: str, key: str, like: npt.NDArray,
    *,
    blob: bytes | None = None,
) -> npt.NDArray:
    """Decode one attribute cell as ``(M, *row_shape)``, matching ``like``.

    Row shape comes from the array's own meta and must agree with the
    incoming rows — an append that changes the tail dims would make the
    blob undecodable, so it raises instead.  ``blob`` is the cell's bytes
    when the caller has already read them.
    """
    meta = level_group.read_array_meta(full_name) or {}
    dtype = np.dtype(meta["dtype"]) if "dtype" in meta else like.dtype
    tail = tuple(meta.get("row_shape", like.shape[1:]))
    if tail != like.shape[1:]:
        raise ArrayError(
            f"{full_name}: append shape mismatch — existing row shape "
            f"{tail} vs new {like.shape[1:]}"
        )
    if blob is None:
        blob = level_group.read_bytes(full_name, key)
    return np.frombuffer(blob, dtype=dtype).reshape((-1, *tail)).astype(
        like.dtype, copy=False,
    )


def _parse_offsets_for_family(
    seg: str,
    *,
    sid_ndim: int | None,
    link_width: int,
    partition: LinkPartition,
) -> tuple[ChunkCoords, ...]:
    """Parse an offsets segment, recovering ``sid_ndim`` if the family
    group meta didn't carry it.

    The source chunks in the partition have the family's true arity, so
    they are an exact fallback for a family whose group attributes lack
    ``sid_ndim`` (or that was written by the per-cell writers alone).
    """
    if sid_ndim is None:
        for _seg, src_chunk in partition.cell_indices:
            sid_ndim = len(src_chunk)
            break
    if sid_ndim is None:
        raise ArrayError(
            f"cannot parse offsets segment {seg!r}: no sid_ndim on the "
            f"links family meta and no cells in the partition"
        )
    return parse_offsets(seg, sid_ndim=sid_ndim, link_width=link_width)


def list_link_offsets(level_group: Group, delta: int = 0) -> list[str]:
    """Sorted offsets segments present under ``links/<delta>/``.

    ``links/<delta>`` is a group whose children are one array per
    distinct relative-offset segment, so this enumerates the whole
    family — the all-zero (intra-chunk) array included, since it is not
    a separate family any more.

    Uses :meth:`FsGroup.child_names`, not iteration: ``__iter__`` yields
    sub-*groups* only and these children are arrays -- and not
    :meth:`FsGroup.children`, which reads every segment array's metadata
    to return names a store listing already has.
    """
    group_path = links_group_path(delta)
    if not level_group.array_exists(group_path):
        return []
    try:
        return sorted(level_group[group_path].child_names())
    except Exception:
        return []


def list_link_attribute_offsets(
    level_group: Group, name: str, delta: int = 0,
) -> list[str]:
    """Sorted offsets segments under ``link_attributes/<name>/<delta>/``.

    Mirrors :func:`list_link_offsets`; the attribute family is required
    to carry the same segments as the link family it parallels.
    """
    group_path = link_attributes_group_path(name, delta)
    if not level_group.array_exists(group_path):
        return []
    try:
        return sorted(level_group[group_path].child_names())
    except Exception:
        return []


def _cast_checked(values: npt.NDArray, dtype: Any, what: str) -> npt.NDArray:
    """``values`` as ``dtype``, raising :class:`ArrayError` if an integer value would
    change or a finite float become infinite.
    """
    dtype = np.dtype(dtype)
    if values.dtype == dtype:
        return values
    cast = values.astype(dtype)
    if dtype.kind in "iub":
        ok = np.array_equal(cast.astype(values.dtype), values)
    else:
        ok = bool(np.all(np.isfinite(cast) | ~np.isfinite(values)))
    if not ok:
        raise ArrayError(
            f"{what} is stored as {dtype}; these values do not fit it"
        )
    return cast


def _stamped_link_dtype(level_group: Group, name: str, fallback: Any) -> np.dtype:
    """The element type a links segment is stored in, else ``fallback``."""
    meta = level_group.read_array_meta(name) or {}
    return np.dtype(meta.get("dtype", fallback))


def _stamp_is(stamped: Any, dtype: Any) -> bool:
    """Whether a stamped dtype equals ``dtype`` (an unparseable stamp is not a
    match; both go through ``np.dtype`` since ``np.dtype('f8') == None``).
    """
    try:
        return np.dtype(stamped) == np.dtype(dtype)
    except TypeError:
        return False


def _link_attr_target_dtype(
    level_group: Group, full_name: str, keys: Sequence[str], new_dtype: Any,
) -> tuple[np.dtype, dict[str, bytes]]:
    """The dtype an attribute segment's cells are written in, and their current bytes.

    The stamped dtype wins once the segment holds data (asked of the cells as
    well as the lagging presence manifest); an empty segment takes ``new_dtype``.
    """
    meta = level_group.read_array_meta(full_name) or {}
    blobs = {k: level_group.read_bytes(full_name, k) for k in keys}
    stamped = meta.get("dtype")
    holds = bool(stamped) and (
        _stamp_is(stamped, new_dtype)
        or any(blobs.values())
        or bool(level_group.list_chunks(full_name))
    )
    return (np.dtype(stamped) if holds else np.dtype(new_dtype)), blobs


def _decode_link_cell(
    level_group: Group,
    chunk_coords: ChunkCoords,
    *,
    delta: int,
    offsets: Sequence[ChunkCoords],
    dtype: np.dtype | str,
    width: int,
    default: Any = _UNSET,
    trust_presence: bool = True,
) -> list[npt.NDArray[np.integer]] | Any:
    """Decode one ``links/<delta>/<offsets>/`` cell into its row groups.

    ``width`` is the **physical** row width — ``link_width``, or
    ``1 + link_width`` when the array carries a ``perm_idx`` column.
    :func:`links_has_perm` is the single definition of which; this
    decoder is told, it never guesses.

    The encoding branch mirrors :func:`write_chunk_links` exactly and
    must stay in lockstep with it: a cell written under one branch is
    undecodable under the other.

    ``trust_presence=False`` reads the cell itself instead of asking the
    presence manifest first, and is what every read-modify-write must
    pass.  The manifest lags the cells by design -- :func:`write_link_cells`
    writes with ``record_presence=False`` -- so a writer appending to a
    cell it filled one batch earlier was told the cell was absent, and
    replaced the first batch with the second.  A reader keeps the default:
    for it the manifest saves a request per absent cell.
    """
    dtype = np.dtype(dtype)
    full_name = links_path(delta, offsets)
    key = _chunk_key(chunk_coords)
    try:
        if trust_presence and not level_group.chunk_exists(full_name, key):
            raise ArrayError(f"{full_name}: no cell {key}")
        raw = level_group.read_bytes(full_name, key)
    except (ArrayError, StoreError):
        if default is _UNSET:
            raise
        return default
    if not raw and not trust_presence:
        return []

    if delta == 0 and is_intra(offsets):
        # Flat blob + link_fragments/<chunk> sidecar.  An empty cell is
        # the vlen fill value under the single-array layout, which is not
        # the same as "no sidecar" — short-circuit before reading it.
        if not raw:
            return []
        fi = read_link_fragment_index(level_group, chunk_coords)
        if fi.num_fragments == 0:
            return []
        full = _reshape_link_buffer(raw, dtype, width)
        groups: list[npt.NDArray[np.integer]] = []
        for f in range(fi.num_fragments):
            if fi.is_range(f):
                start, count = fi.range(f)
                groups.append(full[start : start + count])
            else:
                groups.append(full[fi.indices(f)])
        return groups

    # Inline self-describing blob; no sidecar.
    return decode_ragged_blob(raw, dtype, ncols=width)


def link_family_policy(
    level_group: Group, delta: int,
) -> tuple[int, int | None, bool, str] | None:
    """``(link_width, sid_ndim, directed, store)`` from the family group.

    Returns ``None`` when the family carries no policy — an absent
    family, or one whose group attributes were never stamped — which
    callers treat as "nothing to read".
    """
    family = links_group_path(delta)
    if not level_group.array_exists(family):
        return None
    fam_meta = level_group.read_array_meta(family) or {}
    if "link_width" not in fam_meta:
        return None
    return (
        int(fam_meta["link_width"]),
        int(fam_meta["sid_ndim"]) if "sid_ndim" in fam_meta else None,
        bool(fam_meta.get("directed", False)),
        str(fam_meta.get("store", "canonical")),
    )


def iter_link_cells(
    level_group: Group, delta: int,
) -> Iterator[tuple[str, tuple[ChunkCoords, ...], ChunkCoords, list[npt.NDArray[np.integer]]]]:
    """Yield ``(segment, offsets, source_chunk, groups)`` for every cell.

    Enumeration order is the canonical one every reader shares: offsets
    segments sorted, then cells sorted within each.  ``groups`` are the
    decoded **physical** row blocks — still carrying any ``perm_idx``
    column, since callers differ on whether they want it.

    Offsets come from each array's own ``offsets`` meta when present,
    falling back to parsing the path segment; the two agree, but the
    meta needs no ``sid_ndim`` to decode.  ``has_perm`` likewise comes
    from the array's stamp, with :func:`links_has_perm` as the fallback.
    """
    policy = link_family_policy(level_group, delta)
    if policy is None:
        return
    link_width, sid_ndim, directed, store = policy
    family = links_group_path(delta)
    for seg in list_link_offsets(level_group, delta):
        full_name = f"{family}/{seg}"
        meta = level_group.read_array_meta(full_name) or {}
        raw_offsets = meta.get("offsets")
        if raw_offsets is not None:
            offsets = tuple(tuple(int(c) for c in o) for o in raw_offsets)
        elif sid_ndim is not None:
            offsets = parse_offsets(
                seg, sid_ndim=sid_ndim, link_width=link_width,
            )
        else:
            continue
        dtype = np.dtype(meta.get("dtype", "int64"))
        has_perm = bool(meta.get(
            "has_perm",
            links_has_perm(
                offsets, delta=delta, directed=directed, store=store,
            ),
        ))
        width = link_width + (1 if has_perm else 0)
        for key in sorted(level_group.list_chunks(full_name)):
            try:
                chunk = _parse_chunk_key(key)
            except ValueError:
                continue  # skip non-chunk entries
            groups = _decode_link_cell(
                level_group, chunk, delta=delta, offsets=offsets,
                dtype=dtype, width=width, default=[],
            )
            if not groups:
                continue
            yield seg, offsets, chunk, groups


def _derive_partition_from_links(
    level_group: Group,
    delta: int,
) -> LinkPartition:
    """Re-derive a :class:`LinkPartition` from the on-disk link records.

    ``cell_indices`` is keyed in :func:`read_links` enumeration order —
    each offsets segment sorted, then each cell sorted — with indices
    ``0..num_links-1`` assigned in that read order.  Callers passing
    ``attr_data`` to :func:`write_link_attributes` without an explicit
    partition must supply rows in that same order.

    Only meaningful for a ``canonical`` family: under ``duplicate`` the
    on-disk rows are physical copies, so positional indices cannot
    express the fan-out that maps them back to input records.
    """
    cell_indices: dict[tuple[str, ChunkCoords], list[int]] = {}
    next_idx = 0
    for seg, offsets, chunk, rows in iter_link_cells(level_group, delta):
        del offsets
        n = sum(int(np.asarray(g).shape[0]) for g in rows)
        cell_indices[(seg, chunk)] = list(range(next_idx, next_idx + n))
        next_idx += n
    return LinkPartition(
        cell_indices=cell_indices,
        num_links=next_idx,
        num_physical_records=next_idx,
        first_new=0,
    )


# ===================================================================
# Decentralized (per-cell) link writers
# ===================================================================
#
# ``write_links`` is a whole-family replace/append that also maintains the
# family-wide ``num_links`` / ``num_physical_records`` meta.  The functions
# below instead let many independent workers each write a batch of records
# into ONLY the cells those records touch, deferring the global bookkeeping
# to a single ``finalize_links`` pass.
#
# Race-freedom rests on the flat layout: each cell is its own object
# (sharding is a later, coordinator-run pass), so workers writing DISJOINT
# cells never touch the same file.  A cell IS a source chunk, so giving
# each worker ownership of a disjoint set of source chunks makes every
# cell the property of exactly one worker.  Per-cell RMW is NOT safe for
# two workers hitting the SAME cell.


def write_link_cells(
    level_group: Group,
    links: list[list[tuple[ChunkCoords, int]]] | list[CrossChunkLink] | None = None,
    sid_ndim: int | None = None,
    *,
    chunks: Any = None,
    vids: Any = None,
    attributes: Mapping[str, Any] | None = None,
    delta: int = 0,
    link_width: int | None = None,
    dtype: np.dtype | str = np.int64,
    directed: bool = False,
    store: Literal["canonical", "duplicate"] = "canonical",
    allocate: bool = True,
    record_presence: bool = False,
) -> LinkPartition:
    """Write a batch of records into only the cells they touch.

    Records come one of two ways: ``links``, a list with a Python object
    per endpoint, or as arrays -- ``chunks`` ``(R, L, sid_ndim)`` and
    ``vids`` ``(R, L)`` -- optionally with per-record ``attributes``
    ``{name: (R, *row_shape)}``. The array form places records with
    array arithmetic and reads every cell it touches (links, their
    fragment sidecar, and each attribute) in one prefetch, then writes
    each array's cells in one call: one read-modify-write per cell for
    the links and all their attributes together, where the list form
    plus :func:`write_link_attribute_cells` makes one per attribute. The
    store it leaves is the one those two calls leave. Device arrays are
    copied to the host once each.

    The decentralized counterpart to :func:`write_links`: it leaves every
    other cell untouched and does **not** maintain the family-wide
    ``num_links`` / ``num_physical_records`` counts — call
    :func:`finalize_links` once, after all workers finish, to reconcile
    them (and shard separately if desired).

    Placement routes through :func:`_partition_links`, the same choke
    point :func:`write_links` uses, so a batch lands in exactly the cells
    the whole-family writer would have chosen.  That is what makes
    disjoint per-cell writes plus one ``finalize_links`` equivalent to a
    single ``write_links`` over the union of the batches.

    A coordinator **must** pre-create the family with matching
    ``directed`` / ``store`` / ``sid_ndim`` via :func:`create_links_array`
    when workers run concurrently, and pass ``allocate=False`` to assert
    it did.  With ``allocate=True`` (the default, and the historical
    behaviour) this creates the segment array idempotently from inside the
    per-bucket loop — so two workers whose records land in the same
    ``<offsets>`` segment race on the same ``zarr.json``.  Serial callers
    are unaffected and need change nothing.

    Args:
        allocate: When True (default) create each segment array on demand.
            When False, require it to exist already and raise
            :class:`ArrayError` naming the missing segment instead — the
            spelling for a worker whose coordinator pre-created the family.

    Returns the :class:`LinkPartition` for THIS batch — its ``num_links``
    is the batch's logical record count, not the family's — for use with
    :func:`write_link_attribute_cells`.

    Concurrency:
        Per-cell read-modify-write.  Safe only while workers own disjoint
        source chunks; two workers appending to one cell lose rows.
    """
    if store not in ("canonical", "duplicate"):
        raise ArrayError(
            f"store must be 'canonical' or 'duplicate', got {store!r}"
        )
    if chunks is not None or vids is not None:
        if links is not None or chunks is None or vids is None:
            raise ArrayError("give links, or chunks= and vids=, not both")
        return _write_link_cells_arrays(
            level_group, chunks, vids, attributes or {},
            sid_ndim=sid_ndim, delta=delta, dtype=dtype, directed=directed,
            store=store, allocate=allocate, record_presence=record_presence,
        )
    if attributes:
        raise ArrayError("attributes= goes with the array form (chunks=, vids=)")
    if links is None or sid_ndim is None:
        raise ArrayError("the list form needs links and sid_ndim")
    if not links:
        return LinkPartition(
            cell_indices={}, num_links=0, num_physical_records=0, first_new=0,
        )

    dtype = np.dtype(dtype)
    normalised, link_width = _normalise_link_records(
        links, link_width, sid_ndim, delta,
    )

    # Guard before any write: a worker joining a family stamped with other
    # flags would file rows the family-wide reader decodes at the wrong
    # width.  Absent meta means the family is this call's to create.
    fam_meta = level_group.read_array_meta(links_group_path(delta)) or {}
    if fam_meta:
        _check_link_family_policy(
            fam_meta, delta=delta, link_width=link_width, sid_ndim=sid_ndim,
            directed=directed, store=store, action="append to",
        )

    buckets = _partition_links(
        level_group, normalised, link_width, sid_ndim,
        delta=delta, directed=directed, store=store,
    )

    physical = 0
    for (seg, src_chunk), entries in buckets.items():
        offsets = parse_offsets(seg, sid_ndim=sid_ndim, link_width=link_width)
        if allocate:
            create_links_array(
                level_group, link_width, dtype=str(dtype), delta=delta,
                sid_ndim=sid_ndim, offsets=offsets, directed=directed,
                store=store, exist_ok=True,
            )
        elif not level_group.array_exists(links_path(delta, offsets)):
            raise ArrayError(
                f"write_link_cells(allocate=False) requires "
                f"{links_path(delta, offsets)!r} to exist already; a "
                f"coordinator must pre-create every offsets segment its "
                f"workers will touch (create_links_family / "
                f"create_links_array)."
            )
        has_perm = links_has_perm(
            offsets, delta=delta, directed=directed, store=store,
        )
        # The segment's stamped element type wins over this call's: an
        # int32 segment appended with the default int64 used to decode its
        # old rows at the wrong width and write the new ones in another.
        cell_dtype = _stamped_link_dtype(level_group, links_path(delta, offsets), dtype)
        rows = _cast_checked(
            _pack_link_rows(
                entries, has_perm=has_perm, link_width=link_width, dtype=np.int64,
            ),
            cell_dtype, links_path(delta, offsets),
        )
        physical += rows.shape[0]
        # RMW: this batch is a new group appended after whatever the cell
        # already holds, so a worker may call this repeatedly.
        groups = list(_decode_link_cell(
            level_group, src_chunk, delta=delta, offsets=offsets,
            dtype=cell_dtype, width=rows.shape[1], default=[],
            trust_presence=False,
        ))
        groups.append(rows)
        # Route through the per-cell writer so the flat+sidecar vs
        # inline-blob choice has exactly one definition.
        #
        # record_presence=False: this is the worker half of the
        # decentralized protocol.  Workers own disjoint source chunks, so
        # their *cells* never collide — but ``nonempty_chunks`` is
        # array-wide, and stamping it is a read-modify-write that two
        # workers writing disjoint cells still race on, silently dropping
        # the loser's key while its payload sits on disk.  The manifest is
        # rebuilt from the store listing by :func:`finalize_links`, which
        # the coordinator must run before any ``shard_store``.
        write_chunk_links(
            level_group, src_chunk, groups, cell_dtype,
            delta=delta, offsets=offsets, link_width=link_width,
            record_presence=record_presence,
        )

    return LinkPartition(
        cell_indices={k: [idx for _, _, idx in v] for k, v in buckets.items()},
        num_links=len(normalised),
        num_physical_records=physical,
        first_new=0,
    )


def _write_link_cells_arrays(
    level_group: Group,
    chunks: Any,
    vids: Any,
    attributes: Mapping[str, Any],
    *,
    sid_ndim: int | None,
    delta: int,
    dtype: Any,
    directed: bool,
    store: str,
    allocate: bool,
    record_presence: bool,
) -> LinkPartition:
    """:func:`write_link_cells` for records and attributes held as arrays."""
    from zarr_vectors import _xp
    from zarr_vectors.core._batch_reader import flush_prefetch
    from zarr_vectors.spatial.boundary import (
        _MAX_ARRAY_LINK_WIDTH,
        partition_link_arrays,
    )

    if _xp.encode_on_device(chunks, vids):
        cc, vi = chunks, vids
    else:
        cc = _xp.to_host(chunks, dtype=np.int64)
        vi = _xp.to_host(vids, dtype=np.int64)
    attrs = {name: _xp.to_host(a) for name, a in attributes.items()}
    if cc.ndim != 3 or vi.shape != cc.shape[:2]:
        raise ArrayError(
            f"chunks must be (R, L, sid_ndim) and vids (R, L); got "
            f"{cc.shape} and {vi.shape}"
        )
    num, link_width = int(cc.shape[0]), int(cc.shape[1])
    if sid_ndim is None:
        sid_ndim = int(cc.shape[2])
    elif cc.shape[2] != sid_ndim:
        raise ArrayError(f"chunks have rank {cc.shape[2]}, expected sid_ndim={sid_ndim}")
    for name, a in attrs.items():
        if a.shape[:1] != (num,):
            raise ArrayError(f"attribute {name!r} has {a.shape[0]} rows for {num} records")
    if num == 0:
        return LinkPartition(cell_indices={}, num_links=0, num_physical_records=0, first_new=0)

    fam_meta = level_group.read_array_meta(links_group_path(delta)) or {}
    if fam_meta:
        _check_link_family_policy(
            fam_meta, delta=delta, link_width=link_width, sid_ndim=sid_ndim,
            directed=directed, store=store, action="append to",
        )

    buckets: dict[tuple[str, ChunkCoords], tuple[npt.NDArray, npt.NDArray]]
    if store == "canonical" and link_width <= _MAX_ARRAY_LINK_WIDTH:
        scale_src, scale_trg = _link_scales(level_group, delta, sid_ndim)
        buckets = partition_link_arrays(
            cc, vi, link_width=link_width, sid_ndim=sid_ndim,
            scale_src=scale_src, scale_trg=scale_trg,
            directed=directed, cross_level=delta != 0,
        )
    else:
        cc = _xp.to_host(cc, dtype=np.int64)
        vi = _xp.to_host(vi, dtype=np.int64)
        records = [
            [(tuple(cc[r, k].tolist()), int(vi[r, k])) for k in range(link_width)]
            for r in range(num)
        ]
        normalised, _ = _normalise_link_records(records, link_width, sid_ndim, delta)
        buckets = {}
        for key, entries in _partition_links(
            level_group, normalised, link_width, sid_ndim,
            delta=delta, directed=directed, store=store,
        ).items():
            offsets = parse_offsets(key[0], sid_ndim=sid_ndim, link_width=link_width)
            has_perm = links_has_perm(offsets, delta=delta, directed=directed, store=store)
            buckets[key] = (
                _pack_link_rows(entries, has_perm=has_perm, link_width=link_width, dtype=np.int64),
                np.asarray([idx for _, _, idx in entries], dtype=np.int64),
            )

    by_seg: dict[str, list[tuple[ChunkCoords, npt.NDArray, npt.NDArray]]] = {}
    for (seg, src), (rows, idx) in sorted(buckets.items()):
        by_seg.setdefault(seg, []).append((src, rows, idx))

    seg_info: dict[str, tuple[Any, np.dtype, bool]] = {}
    for seg in by_seg:
        offsets = parse_offsets(seg, sid_ndim=sid_ndim, link_width=link_width)
        name = links_path(delta, offsets)
        if allocate:
            create_links_array(
                level_group, link_width, dtype=str(np.dtype(dtype)), delta=delta,
                sid_ndim=sid_ndim, offsets=offsets, directed=directed,
                store=store, exist_ok=True,
            )
        elif not level_group.array_exists(name):
            raise ArrayError(
                f"write_link_cells(allocate=False) requires {name!r} to exist "
                f"already; a coordinator must pre-create every offsets segment "
                f"its workers will touch (create_links_family / create_links_array)."
            )
        for attr_name, a in attrs.items():
            attr_path = link_attributes_path(attr_name, delta, offsets)
            if allocate:
                create_link_attributes_array(
                    level_group, attr_name, dtype=str(a.dtype), delta=delta,
                    sid_ndim=sid_ndim, link_width=link_width, offsets=offsets,
                    exist_ok=True, row_shape=a.shape[1:],
                )
            elif not level_group.array_exists(attr_path):
                raise ArrayError(
                    f"write_link_cells(allocate=False) requires {attr_path!r} "
                    f"to exist already (create_link_attributes_array)."
                )
        seg_info[seg] = (
            offsets,
            _stamped_link_dtype(level_group, name, dtype),
            delta == 0 and is_intra(offsets),
        )

    # One prefetch of every cell this batch touches -- except those an open
    # shard transaction answers itself (staged, or prefetched with its shard).
    txn = level_group._shard_txn
    plan: list[tuple[str, list[str]]] = []
    intra_keys: list[str] = []

    def unserved(name: str, keys: list[str]) -> tuple[str, list[str]]:
        if txn is None:
            return name, keys
        return name, [k for k in keys if not txn.serves(name, k)]

    for seg, cells in by_seg.items():
        offsets, _, flat = seg_info[seg]
        keys = [_chunk_key(src) for src, _, _ in cells]
        plan.append(unserved(links_path(delta, offsets), keys))
        plan += [unserved(link_attributes_path(n, delta, offsets), keys) for n in attrs]
        if flat:
            intra_keys += keys
    if intra_keys:
        plan.append(unserved(LINK_FRAGMENTS, sorted(set(intra_keys))))
    plan = [(name, keys) for name, keys in plan if keys]
    cache = flush_prefetch(level_group._zarr, plan) if plan else {}
    # Cells staged in a shard transaction win over the store prefetch.

    def raw(name: str, key: str) -> bytes:
        if txn is not None:
            staged = txn.lookup(name, key)
            if staged is not None:
                return staged
        return cache.get((name, key)) or b""

    physical = 0
    writes: dict[str, list[tuple[str, bytes]]] = {}
    attr_stamps: list[tuple[str, str, npt.NDArray, np.dtype, Any]] = []
    for seg, cells in by_seg.items():
        offsets, cell_dtype, flat = seg_info[seg]
        name = links_path(delta, offsets)
        for src, rows, _idx in cells:
            key = _chunk_key(src)
            new = _cast_checked(rows, cell_dtype, name)
            physical += new.shape[0]
            old = raw(name, key)
            if flat:
                data, sidecar = _append_flat_link_cell(
                    old, raw(LINK_FRAGMENTS, key), new, cell_dtype,
                )
                writes.setdefault(name, []).append((key, data))
                writes.setdefault(LINK_FRAGMENTS, []).append((key, sidecar))
            else:
                groups = decode_ragged_blob(old, cell_dtype, ncols=new.shape[1]) if old else []
                writes.setdefault(name, []).append(
                    (key, encode_ragged_blob([*groups, new], cell_dtype)),
                )
        for attr_name, a in attrs.items():
            attr_path = link_attributes_path(attr_name, delta, offsets)
            meta = level_group.read_array_meta(attr_path) or {}
            tail = tuple(meta.get("row_shape", a.shape[1:]))
            if tail != a.shape[1:]:
                raise ArrayError(
                    f"{attr_path}: append shape mismatch — existing row shape "
                    f"{tail} vs new {a.shape[1:]}"
                )
            olds = {_chunk_key(src): raw(attr_path, _chunk_key(src)) for src, _, _ in cells}
            stamped = meta.get("dtype")
            holds = bool(stamped) and (
                _stamp_is(stamped, a.dtype)
                or any(olds.values())
                or bool(level_group.list_chunks(attr_path))
            )
            target = np.dtype(stamped) if holds else a.dtype
            for src, _rows, idx in cells:
                key = _chunk_key(src)
                new_rows = _cast_checked(a[idx], target, attr_path)
                writes.setdefault(attr_path, []).append(
                    (key, olds[key] + np.ascontiguousarray(new_rows).tobytes()),
                )
            attr_stamps.append((attr_name, attr_path, a, target, offsets))

    for name, cells in writes.items():
        level_group.write_cells(name, cells, record_presence=record_presence)
    for attr_name, attr_path, a, target, offsets in attr_stamps:
        _write_array_meta_if_changed(level_group, attr_path, {
            "zv_array": "link_attribute",
            "name": attr_name,
            "dtype": str(target),
            "row_shape": list(a.shape[1:]),
            "offsets": [list(int(c) for c in o) for o in offsets],
            "level_delta": int(delta),
        })

    return LinkPartition(
        cell_indices={
            (seg, src): idx for seg, cells in by_seg.items() for src, _, idx in cells
        },
        num_links=num,
        num_physical_records=physical,
        first_new=0,
    )


def _append_flat_link_cell(
    raw: bytes, raw_sidecar: bytes, rows: npt.NDArray, dtype: np.dtype,
) -> tuple[bytes, bytes]:
    """An intra cell and its fragment sidecar with ``rows`` added as a group, as
    :func:`write_chunk_links` would write them (fast path when the sidecar tiles the cell).
    """
    width = rows.shape[1]
    new_bytes = np.ascontiguousarray(rows, dtype=dtype).tobytes()
    if not raw:
        sections = range_fragment_sections([0], [rows.shape[0]])
        return new_bytes, pack_fragment_sections(sections)
    fi = decode_fragments(raw_sidecar)
    full = np.frombuffer(raw, dtype=dtype).reshape(-1, width)
    if fi.tiles(full.shape[0]):
        sections = concat_fragment_sections(
            fragment_sections_from_index(fi),
            range_fragment_sections([full.shape[0]], [rows.shape[0]]),
        )
        return raw + new_bytes, pack_fragment_sections(sections)
    groups = [
        full[fi.range(f)[0]:fi.range(f)[0] + fi.range(f)[1]] if fi.is_range(f)
        else full[fi.indices(f)]
        for f in range(fi.num_fragments)
    ] + [np.asarray(rows, dtype=dtype)]
    counts = np.array([g.shape[0] for g in groups], dtype=np.int64)
    data = b"".join(np.ascontiguousarray(g, dtype=dtype).tobytes() for g in groups)
    return data, pack_fragment_sections(
        range_fragment_sections(np.cumsum(counts) - counts, counts),
    )


def write_link_attribute_cells(
    level_group: Group,
    attr_name: str,
    attr_data: npt.NDArray,
    *,
    partition: LinkPartition,
    delta: int = 0,
    allocate: bool = True,
    record_presence: bool = True,
) -> None:
    """Append attribute rows for the cells one batch wrote.

    ``record_presence=False`` skips stamping each cell into the segment's
    presence manifest, as the link writers do; :func:`finalize_links`
    rebuilds it.

    ``attr_data`` holds one row per logical record in the SAME batch, in
    the input order used for the matching :func:`write_link_cells` call;
    ``partition`` is that call's return value.  Rows are appended per
    ``(offsets, cell)``, replicating automatically in ``duplicate`` mode
    where one input index appears under several cells.

    Only ``dtype`` / ``row_shape`` are stamped here (idempotent across
    workers).  The attribute family's ``num_links`` is deliberately left
    unstamped: a worker sees only its own batch, and :func:`read_link_attributes`
    derives the row count from the cells themselves.

    Args:
        allocate: As on :func:`write_link_cells` — True (default) creates
            each segment array from inside the loop, which two concurrent
            workers hitting the same segment race on; False requires the
            coordinator to have pre-created it and raises otherwise.
            Note a pre-create loop written for the ``links/`` family does
            **not** cover this one: ``link_attributes/<name>/<delta>/…``
            is a separate family and needs its own pass.
    """
    arr = np.ascontiguousarray(np.asarray(attr_data))
    fam_meta = level_group.read_array_meta(links_group_path(delta)) or {}
    link_width = int(fam_meta.get("link_width", 2))
    sid_ndim = int(fam_meta.get("sid_ndim", 0)) or None

    for seg in sorted({seg for seg, _chunk in partition.cell_indices}):
        offsets = _parse_offsets_for_family(
            seg, sid_ndim=sid_ndim, link_width=link_width, partition=partition,
        )
        full_name = link_attributes_path(attr_name, delta, offsets)
        if allocate:
            create_link_attributes_array(
                level_group, attr_name, dtype=str(arr.dtype), delta=delta,
                sid_ndim=sid_ndim, link_width=link_width, offsets=offsets,
                exist_ok=True, row_shape=arr.shape[1:],
            )
        elif not level_group.array_exists(full_name):
            raise ArrayError(
                f"write_link_attribute_cells(allocate=False) requires "
                f"{full_name!r} to exist already; a coordinator must "
                f"pre-create every link-attribute segment its workers will "
                f"touch (create_link_attributes_array). Pre-creating the "
                f"links/ family alone does not cover link_attributes/."
            )
        cells = [
            (_chunk_key(src_chunk), input_idxs)
            for (bucket_seg, src_chunk), input_idxs in partition.cell_indices.items()
            if bucket_seg == seg
        ]
        target, blobs = _link_attr_target_dtype(
            level_group, full_name, [k for k, _ in cells], arr.dtype,
        )
        for key, input_idxs in cells:
            new_rows = _cast_checked(
                arr[np.asarray(input_idxs, dtype=np.int64)], target, full_name,
            )
            blob = blobs[key]
            if blob:
                existing = _read_attr_cell(level_group, full_name, key, new_rows, blob=blob)
                combined = np.concatenate([existing, new_rows], axis=0)
            else:
                combined = new_rows
            level_group.write_bytes(
                full_name, key, np.ascontiguousarray(combined).tobytes(),
                record_presence=record_presence,
            )
        # ``row_shape`` (the tail dims per row, ``()`` for 1-D) lets the
        # reader reconstruct shape from a bare byte blob.  Stamped only
        # when it differs.  ``dtype`` is the data's only while the segment
        # holds none -- a pre-created segment may carry a placeholder --
        # and the stored one after that, which the rows were cast to.
        _write_array_meta_if_changed(level_group, full_name, {
            "zv_array": "link_attribute",
            "name": attr_name,
            "dtype": str(target),
            "row_shape": list(arr.shape[1:]),
            "offsets": [list(int(c) for c in o) for o in offsets],
            "level_delta": int(delta),
        })


def finalize_links(
    level_group: Group,
    *,
    delta: int = 0,
    attributes: bool = True,
) -> LinkPartition:
    """Reconcile a ``links/<delta>/`` family's counts after decentralized
    per-cell writes.

    Scans every offsets array and every cell under the family to recompute
    ``num_physical_records`` (total on-disk rows) and ``num_links`` (the
    logical record count).  For a ``canonical`` family the two are equal;
    for a ``duplicate`` one the logical count is recovered by deduplicating
    decoded records, since every physical copy of a record decodes to the
    same input-order endpoints.

    Sharding is a separate coordinator step — run
    :func:`zarr_vectors.sharding.shard_store` after finalizing, once all
    cells are on disk.

    Returns the re-derived :class:`LinkPartition` in :func:`read_links`
    enumeration order (each offsets segment sorted, then each cell
    sorted).  ``num_links`` is the **logical** count and
    ``num_physical_records`` the **physical** one — the same two numbers
    stamped on the family group, which the returned partition must agree
    with.  ``cell_indices`` is positional over the physical rows, so under
    ``store="duplicate"`` its indices are row positions, not input
    indices, and must not be fed to :func:`write_link_attributes`.
    """
    policy = link_family_policy(level_group, delta)
    if policy is None:
        return LinkPartition(
            cell_indices={}, num_links=0, num_physical_records=0, first_new=0,
        )
    store = policy[3]  # (link_width, sid_ndim, directed, store)

    # Rebuild each offset array's ``nonempty_chunks`` manifest from the
    # store listing BEFORE enumerating.  This is the coordinator half of
    # the decentralized-write protocol: workers pass
    # ``record_presence=False`` to skip the manifest, because stamping it
    # is a read-modify-write of state shared by every cell in the array —
    # two workers writing *disjoint* cells still race on it, and the
    # loser's key vanishes even though its payload landed.  Without this
    # rebuild, ``iter_link_cells`` (→ ``list_chunks`` → the manifest)
    # would enumerate nothing and this pass would count 0.
    #
    # ``list_link_offsets`` discovers segments via ``children()`` — a
    # store listing — so segment discovery is already race-free.
    #
    # Valid sharded or not: ``derive_nonempty_chunks`` reads a sharded
    # array's cells out of its shard objects.  This used to pass
    # ``on_sharded="skip"`` on the premise that sharding ran after
    # finalize by contract, so a sharded segment's manifest was already
    # correct.  A store can now be born sharded, which makes that premise
    # false and "skip" a silent no-op over exactly the cells this rebuild
    # exists to recover.
    family_group = links_group_path(delta)
    rebuild = [f"{family_group}/{seg}" for seg in list_link_offsets(level_group, delta)]
    if attributes:
        # The same holds for what rides alongside the links: every link
        # attribute segment of this delta, and at delta 0 the intra cells'
        # fragment sidecar. Workers skip their stamps too, and a reader of
        # those arrays asks the same manifest.
        attr_root = LINK_ATTRIBUTES
        if level_group.array_exists(attr_root):
            for name in level_group[attr_root].children():
                rebuild += [
                    f"{link_attributes_group_path(name, delta)}/{seg}"
                    for seg in list_link_attribute_offsets(level_group, name, delta)
                ]
        if delta == 0:
            rebuild.append(LINK_FRAGMENTS)
    if level_group.presence_deferred():
        # A deferred level has no manifests to rebuild, and this is not
        # the place to write them: tasks may still be writing, and a
        # manifest written here would put their stamps back to racing.
        # Its listings ask the store instead, so the enumeration below
        # still finds every cell; the level's own rebuild_presence (or
        # set_presence) records presence once, at the end.
        rebuild = []
    for name in rebuild:
        if level_group._sharded_chunk_array(name) is None:
            # Not a chunk array: an already-stamped segment from the
            # whole-family writer path needs no rebuild.  This is exactly
            # what ``derive_nonempty_chunks`` raises StoreError on, tested
            # up front rather than caught, so a genuine failure inside the
            # rebuild surfaces instead of being swallowed into a count of
            # zero.
            continue
        level_group.derive_nonempty_chunks(name)

    physical = 0
    cell_indices: dict[tuple[str, ChunkCoords], list[int]] = {}
    for seg, offsets, chunk, groups in iter_link_cells(level_group, delta):
        del offsets
        n = sum(int(np.asarray(g).shape[0]) for g in groups)
        cell_indices[(seg, chunk)] = list(range(physical, physical + n))
        physical += n

    if store == "duplicate":
        # Every physical copy of a logical record decodes to the same
        # input-order endpoints, so distinct decoded records == logical.
        records = read_links(level_group, delta=delta)
        logical = len({tuple(r) for r in records})
    else:
        logical = physical

    # Merge into the existing family meta rather than restamping policy:
    # this pass counts rows, it has no opinion on directed/store, and a
    # family group written without ``sid_ndim`` must not gain a made-up one.
    family = links_group_path(delta)
    meta = level_group.read_array_meta(family) or {}
    meta["num_links"] = int(logical)
    meta["num_physical_records"] = int(physical)
    _ensure_array_dir(level_group, family)
    level_group.write_array_meta(family, meta)

    return LinkPartition(
        cell_indices=cell_indices,
        num_links=logical,
        num_physical_records=physical,
        first_new=0,
    )


# ===================================================================
# Reading data
# ===================================================================

def vertices_dtype(level_group: Group) -> np.dtype:
    """The element dtype ``vertices/`` declares.

    A cell is a flat buffer with no inline header, so the Zarr
    ``data_type`` (``variable_length_bytes``) describes the *container*
    and says nothing about the payload.  The element type lives in the
    array's ``dtype`` **attribute**, which :func:`create_vertices_array`
    stamps — this is the only place it is recorded.

    Falls back to ``float32`` when the attribute is unreadable, matching
    the writer's own default.
    """
    try:
        vmeta = level_group.read_array_meta(VERTICES) or {}
        return np.dtype(vmeta.get("dtype", "float32"))
    except Exception:
        return np.dtype(np.float32)


def read_chunk_vertices(
    level_group: Group,
    chunk_coords: ChunkCoords,
    dtype: np.dtype | str | None = None,
    ndim: int = 3,
    *,
    _leaf: bool = False,
) -> list[npt.NDArray[np.floating]]:
    """Read all fragments from a spatial chunk.

    Handles both range and explicit fragments: the full chunk buffer is read
    once and dispatched per fragment based on the ``vertex_fragments/<chunk>``
    index — range fragments are returned as contiguous slices, explicit
    fragments via ``fi.indices(f)`` gather.

    Args:
        level_group: Resolution level group.
        chunk_coords: Spatial chunk coordinates.
        dtype: Numpy dtype.  ``None`` (the default) reads the dtype the
            store declares — see :func:`vertices_dtype`.  Pass one only to
            override, and only knowing that a wrong value does not raise:
            a ``float64`` cell read as ``float32`` decodes to garbage at
            twice the row count, silently.
        ndim: Number of coordinate dimensions (D).

    Returns:
        List of arrays, each ``(N_k, D)``.

    Raises:
        ArrayError: If the chunk does not exist or data is malformed.
    """
    from zarr_vectors.octree_chunks.guard import refuse_octree_read

    # A leaf is no uniform cell: only the octree readers (``_leaf``) read one.
    if not _leaf:
        refuse_octree_read(level_group, "read_chunk_vertices")
    full, fi = _read_chunk_buffer(level_group, chunk_coords, dtype, ndim)
    return [] if full is None else _partition_rows(full, fi)


def _read_chunk_fragments(
    level_group: Group,
    chunk_coords: ChunkCoords,
    dtype: np.dtype | str | None = None,
    ndim: int = 3,
) -> Sequence[npt.NDArray[np.floating]]:
    """:func:`read_chunk_vertices`, cutting range fragments only when
    accessed (a box query wants a few of a neighbour chunk's fragments)."""
    full, fi = _read_chunk_buffer(level_group, chunk_coords, dtype, ndim)
    if full is None:
        return []
    table = fi.ranges()
    if table is None:
        return _partition_rows(full, fi)
    return _RangeFragments(full, table)


class _RangeFragments(Sequence):
    """``full`` as a sequence of row ranges, each a view cut when indexed."""

    __slots__ = ("_full", "_starts", "_stops")

    def __init__(self, full: npt.NDArray, table: npt.NDArray[np.int64]) -> None:
        self._full = full
        self._starts = table[:, 0].tolist()
        self._stops = (table[:, 0] + table[:, 1]).tolist()

    def __len__(self) -> int:
        return len(self._starts)

    def __getitem__(self, f: Any) -> Any:
        if isinstance(f, slice):
            return [self[i] for i in range(*f.indices(len(self)))]
        return self._full[self._starts[f] : self._stops[f]]


def _read_chunk_buffer(
    level_group: Group,
    chunk_coords: ChunkCoords,
    dtype: np.dtype | str | None,
    ndim: int,
) -> tuple[npt.NDArray | None, ChunkFragmentIndex]:
    """A chunk's ``(N, D)`` vertex buffer and fragment index; the buffer
    is ``None`` when the chunk holds no fragments."""
    key = _chunk_key(chunk_coords)
    # Default to the declared dtype rather than float32.  Nothing in the
    # blob records the element type, so an assumed dtype is not checkable
    # — it just produces wrong numbers.  The store already knows; ask it.
    dtype = vertices_dtype(level_group) if dtype is None else np.dtype(dtype)

    with _maybe_batched_reads(level_group, [
        (VERTICES, [key]),
        (VERTEX_FRAGMENTS, [key]),
    ]):
        try:
            raw = level_group.read_bytes(VERTICES, key)
        except Exception as e:
            raise ArrayError(f"Cannot read vertices chunk {key}: {e}") from e

        fi = read_vertex_fragment_index(level_group, chunk_coords)

    if fi.num_fragments == 0:
        return None, fi
    return _reshape_vertex_buffer(raw, dtype, ndim), fi


def _partition_rows(
    full: npt.NDArray, fi: ChunkFragmentIndex,
) -> list[npt.NDArray]:
    """``full`` cut into one array per fragment, in fragment order.

    Range fragments are views; explicit ones are gathers.  When every
    fragment is a range the two lists come off the range table whole
    rather than through a per-fragment accessor -- see
    :meth:`ChunkFragmentIndex.ranges`.
    """
    table = fi.ranges()
    if table is not None:
        return [
            full[start : start + count]
            for start, count in zip(table[:, 0].tolist(), table[:, 1].tolist())
        ]
    return [fragment_rows(full, fi, f) for f in range(fi.num_fragments)]


def fragment_rows(
    full: npt.NDArray, fi: ChunkFragmentIndex, f: int,
) -> npt.NDArray:
    """The rows of fragment ``f`` from a per-vertex buffer ``full``.

    ``full`` is any array whose leading axis is the chunk's vertex rows
    -- the ``(N, D)`` positions, or an attribute's ``(N, width)`` -- and
    this is the one place the fragment-to-rows rule lives: a range
    fragment is a contiguous slice, an explicit one a gather.
    """
    if fi.is_range(f):
        start, count = fi.range(f)
        return full[start : start + count]
    return full[fi.indices(f)]


def attribute_buffer(
    raw: bytes,
    fi: ChunkFragmentIndex,
    dtype: np.dtype,
    *,
    what: str = "attribute",
) -> npt.NDArray | None:
    """One per-vertex attribute cell as its ``(n_vertices, width)`` buffer.

    Per-vertex attributes are one row per underlying vertex, aligned 1:1
    with the ``vertices`` buffer, so the row count is the fragment
    index's vertex extent and the width falls out of the byte length.
    ``None`` for a cell with no rows.

    Raises:
        ArrayError: If the bytes do not divide into that many rows.
    """
    itemsize = dtype.itemsize
    total_elements = len(raw) // itemsize if itemsize else 0
    n_vertices = _fragment_vertex_extent(fi)
    if n_vertices <= 0 or total_elements == 0:
        return None
    if total_elements % n_vertices != 0:
        raise ArrayError(
            f"{what} has {total_elements} elements, not a multiple of its "
            f"{n_vertices} vertices; per-vertex attributes must align 1:1 "
            "with the vertices array."
        )
    return np.frombuffer(raw, dtype=dtype).reshape(n_vertices, total_elements // n_vertices)


def shape_attribute_rows(rows: npt.NDArray, ncols: int) -> npt.NDArray:
    """Rows from :func:`attribute_buffer`, in the shape a caller asked
    for: flat for ``ncols == 1``, ``(N, ncols)`` otherwise -- the
    historical ``decode_ragged_floats`` contract."""
    flat = np.ascontiguousarray(rows).reshape(-1)
    return flat if ncols == 1 else flat.reshape(-1, ncols)


@_device_result
def read_chunk_attribute_rows(
    level_group: Group,
    attr_name: str,
    chunk_coords: ChunkCoords,
    dtype: np.dtype | str | None = None,
    ncols: int | None = None,
) -> npt.NDArray:
    """Every fragment's attribute rows from one chunk, concatenated in
    fragment order.

    The attribute twin of :func:`read_chunk_vertex_rows`, and for the
    same reason: a bulk reader that concatenates
    :func:`read_chunk_attributes` pays for a 64-way partition it then
    undoes, on every chunk, for every attribute.  When the fragments
    tile the buffer -- the layout every bulk writer produces -- the
    concatenation *is* the buffer and it is returned whole.  Anything
    else falls back to partition-and-concatenate, so the rows are
    exactly those the per-fragment reader would have returned, in the
    same order.

    Returns an empty array for a chunk with no fragments or no rows.
    """
    key = _chunk_key(chunk_coords)
    full_name = f"{VERTEX_ATTRIBUTES}/{attr_name}"
    dtype, ncols = _resolve_attribute_layout(level_group, full_name, dtype, ncols)

    with _maybe_batched_reads(level_group, [
        (full_name, [key]),
        (VERTEX_FRAGMENTS, [key]),
    ]):
        try:
            raw = level_group.read_bytes(full_name, key)
        except Exception as e:
            raise ArrayError(
                f"Cannot read attribute '{attr_name}' chunk {key}: {e}"
            ) from e
        fi = read_vertex_fragment_index(level_group, chunk_coords)

    empty = np.empty((0,) if ncols == 1 else (0, ncols), dtype=dtype)
    if fi.num_fragments == 0:
        return empty
    full = attribute_buffer(
        raw, fi, dtype, what=f"Attribute '{attr_name}' chunk {key}",
    )
    if full is None:
        return empty
    if fi.tiles(full.shape[0]):
        return shape_attribute_rows(full, ncols)
    parts = _partition_rows(full, fi)
    return shape_attribute_rows(
        np.concatenate(parts, axis=0) if parts else full[:0], ncols,
    )


def chunk_fragments_tile(
    level_group: Group,
    chunk_coords: ChunkCoords,
    n_rows: int,
) -> bool:
    """Does this one chunk's fragment index tile a buffer of ``n_rows``?

    The read-time half of the ``fragments_tile`` claim.  A reader taking
    the fast path checks its first chunk, so a claim that has gone stale
    — a hand-edited store, a migration, a writer bug — costs one index
    read rather than a wrong answer.

    It cannot catch a claim broken only in a later chunk; that case
    belongs to :meth:`Group._clear_fragments_tile`, which drops the claim
    the moment anything writes to the level.  This is the belt to that
    chokepoint's braces.
    """
    try:
        return read_vertex_fragment_index(level_group, chunk_coords).tiles(
            n_rows,
        )
    except (ArrayError, StoreError):
        return False


def stamp_fragments_tile(level_group: Group, ndim: int) -> bool:
    """Record whether every chunk in this level tiles its vertex buffer.

    Called by a bulk writer once its chunk writes are done.  Returns what
    it stamped.

    **Verified, not asserted.**  It would be cheaper to let each writer
    declare "my layout tiles" — they all emit one contiguous range per
    bin via :func:`write_chunk_vertices`, so structurally they do — but
    the cost of a wrong declaration is a silent wrong answer on every
    later read, and the cost of checking is one index read per chunk on a
    path that has just written far more than that.  So it checks.

    Must run AFTER the chunk writes, never as part of the
    :class:`LevelMetadata` a writer builds up front: creating the level
    first and then writing to ``vertices`` trips
    :meth:`Group._clear_fragments_tile`, which would wipe a claim stamped
    early.  That clearing is the same mechanism that stops an edit
    leaving a stale claim behind, so it is not something to work around.

    A level with no chunks stamps nothing: there is no layout to claim.

    Args:
        level_group: The level just written.
        ndim: Coordinate columns per vertex, so a buffer's row count
            can be derived from its byte length.
    """
    keys = list_chunk_keys(level_group)
    if not keys:
        return False

    dtype = vertices_dtype(level_group)
    key_strs = [_chunk_key(cc) for cc in keys]
    # Row counts the writer recorded as it encoded each cell. Where one
    # is present the buffer need not be fetched to be measured, which is
    # the difference between a bulk write that reads its own output back
    # in full (measured: 1.00x the bytes written) and one that reads only
    # the fragment indices -- 16 bytes per fragment. The check itself is
    # unchanged: the index still comes from the store and is still
    # verified against the row count rather than trusted.
    recorded = level_group.take_vertex_rows()
    unrecorded = [k for k in key_strs if k not in recorded]
    with _maybe_batched_reads(level_group, [
        (VERTICES, unrecorded),
        (VERTEX_FRAGMENTS, key_strs),
    ]):
        for cc in keys:
            key = _chunk_key(cc)
            try:
                fi = read_vertex_fragment_index(level_group, cc)
                n_rows = recorded.get(key)
                if n_rows is None:
                    raw = level_group.read_bytes(VERTICES, key)
                    row_bytes = dtype.itemsize * max(1, int(ndim))
                    if row_bytes == 0 or len(raw) % row_bytes:
                        return False
                    n_rows = len(raw) // row_bytes
            except (ArrayError, StoreError):
                return False
            if not fi.tiles(n_rows):
                return False

    level = level_group.attrs.get(_LEVEL_META_KEY)
    if not isinstance(level, dict):
        return False
    level_group.attrs.update({
        _LEVEL_META_KEY: {**level, "fragments_tile": True},
    })
    # The stamp is this handle's last word; a later chunk write must be
    # able to clear it again.
    level_group._tiling_claim_settled = False
    return True


def stamp_link_fragments_aligned(level_group: Group) -> bool:
    """Record that every intra-chunk link cell is grouped by vertex fragment.

    Called by a bulk writer that passed ``fragment_starts=`` to
    :func:`write_links`, once its chunk writes are done -- after, for the
    reason :func:`stamp_fragments_tile` gives.  Returns what it stamped.

    Checked as far as the indices allow: every chunk holding an
    intra-chunk link cell must have exactly as many link fragments as
    vertex fragments.  That is two small index reads per chunk and
    catches a writer that did not group at all.  Which record went to
    which fragment is the writer's construction and is not re-derived
    here; ``validate_consistency`` does that, at the cost of decoding
    every cell.
    """
    policy = link_family_policy(level_group, 0)
    if policy is None:
        return False
    link_width, sid_ndim, _directed, _store = policy
    if sid_ndim is None:
        return False
    intra_path = links_path(0, intra_offsets(sid_ndim, link_width))
    if not level_group.array_exists(intra_path):
        return False
    keys = level_group.list_chunks(intra_path)
    if not keys:
        return False
    with _maybe_batched_reads(level_group, [
        (VERTEX_FRAGMENTS, keys),
        (LINK_FRAGMENTS, keys),
    ]):
        for key in keys:
            cc = _parse_chunk_key(key)
            try:
                n_vertex = read_vertex_fragment_index(level_group, cc).num_fragments
                n_link = read_link_fragment_index(level_group, cc).num_fragments
            except (ArrayError, StoreError):
                return False
            if n_vertex != n_link:
                return False

    level = level_group.attrs.get(_LEVEL_META_KEY)
    if not isinstance(level, dict):
        return False
    level_group.attrs.update({
        _LEVEL_META_KEY: {**level, "link_fragments_aligned": True},
    })
    level_group._alignment_claim_settled = False
    return True


def chunk_link_fragments_aligned(
    level_group: Group,
    chunk_coords: ChunkCoords,
) -> bool:
    """Does this chunk bear out the ``link_fragments_aligned`` claim?

    The full check :func:`stamp_link_fragments_aligned` leaves to the
    validator: the intra-chunk cell has one link fragment per vertex
    fragment, and every record in link fragment ``k`` has its first
    stored endpoint among vertex fragment ``k``'s rows.  Decodes the
    cell.  A chunk with no intra-chunk records holds trivially.
    """
    try:
        fi = read_vertex_fragment_index(level_group, chunk_coords)
        groups = read_chunk_links(level_group, chunk_coords)
    except (ArrayError, StoreError):
        return False
    if not groups:
        return True
    if len(groups) != fi.num_fragments:
        return False
    for k, rows in enumerate(groups):
        rows = np.asarray(rows)
        if rows.size == 0:
            continue
        first = rows[:, 0] if rows.ndim == 2 else rows
        if fi.is_range(k):
            start, count = fi.range(k)
            if not np.all((first >= start) & (first < start + count)):
                return False
        elif not np.all(np.isin(first, fi.indices(k))):
            return False
    return True


@_device_result(on_device=True)
def read_chunk_vertex_rows(
    level_group: Group,
    chunk_coords: ChunkCoords,
    dtype: np.dtype | str | None = None,
    ndim: int = 3,
) -> npt.NDArray[np.floating]:
    """Every fragment's rows from one chunk, concatenated in fragment order.

    What a bulk reader actually wants.  :func:`read_chunk_vertices`
    answers the per-fragment question — which rows belong to which
    object — and a caller that immediately concatenates the answer pays
    for a partition it then throws away.  On a point cloud binned 4x4x4
    that is 64 slices per chunk, 8000 array objects and an 8000-way
    ``np.concatenate`` for a level whose rows were already contiguous:
    ~14 ms of a 10^6-point read-everything, for nothing.

    So this checks first.  When the fragments are all ranges that tile
    ``[0, N)`` in order — the layout every bulk writer produces, because
    it assigns rows bin by bin — their concatenation *is* the chunk
    buffer, and the buffer is returned whole with no slicing at all.
    Anything else (explicit fragments, gaps left by deletions, ranges out
    of order) falls back to the general partition-and-concatenate.

    Not interchangeable with :func:`read_chunk_vertex_buffer`, which
    returns the buffer unconditionally.  The difference is exactly the
    rows no fragment references: this function drops them, that one
    keeps them.  On a level written per object with rows retired by a
    later edit, those are different arrays.

    Args:
        level_group: Resolution level group.
        chunk_coords: Spatial chunk coordinates.
        dtype: Element dtype.  ``None`` (the default) reads the dtype the
            store declares — see :func:`vertices_dtype`.
        ndim: Number of coordinate dimensions (D).

    Returns:
        ``(M, D)`` array (``(M,)`` when ``ndim == 1``), where ``M`` is the
        total row count across every fragment.  Empty when the chunk has
        no fragments.

    Raises:
        ArrayError: If the chunk does not exist or data is malformed.
    """
    key = _chunk_key(chunk_coords)
    dtype = vertices_dtype(level_group) if dtype is None else np.dtype(dtype)

    with _maybe_batched_reads(level_group, [
        (VERTICES, [key]),
        (VERTEX_FRAGMENTS, [key]),
    ]):
        try:
            raw = level_group.read_bytes(VERTICES, key)
        except Exception as e:
            raise ArrayError(f"Cannot read vertices chunk {key}: {e}") from e

        fi = read_vertex_fragment_index(level_group, chunk_coords)

    full = _reshape_vertex_buffer(raw, dtype, ndim)
    if fi.num_fragments == 0:
        return full[:0]
    if fi.tiles(len(full)):
        return full

    groups: list[npt.NDArray[np.floating]] = []
    for f in range(fi.num_fragments):
        if fi.is_range(f):
            start, count = fi.range(f)
            groups.append(full[start : start + count])
        else:
            groups.append(full[fi.indices(f)])
    return np.concatenate(groups, axis=0) if groups else full[:0]


@_device_result(on_device=True)
def read_chunk_vertex_buffer(
    level_group: Group,
    chunk_coords: ChunkCoords,
    dtype: np.dtype | str | None = None,
    ndim: int = 3,
    *,
    default: Any = _UNSET,
) -> npt.NDArray[np.floating] | Any:
    """A chunk's whole ``(N, D)`` vertex buffer, in stored row order.

    The array every other per-chunk index is expressed against: fragments
    are row ranges or row gathers into it, links name row numbers in it,
    and per-vertex attributes align to it 1:1.  Reading it is what a
    caller wants whenever the unit of work is the chunk rather than one
    object — a metric over every vertex, a position lookup by row number,
    a repack of the row order.

    Not ``read_fragment(level_group, chunk_coords, 0)``.  That happens to
    be the same array whenever fragment 0 is a range covering the chunk,
    which is how a bulk vertex writer lays a level out — so the
    substitution works until it meets a level written per object, where
    fragment 0 is one object's rows and the rest of the buffer is
    invisible through it.  The failure is silent: short positions, short
    attribute cells, and a level that reads back as though it were never
    written.

    Args:
        level_group: Resolution level group.
        chunk_coords: Spatial chunk coordinates.
        dtype: Element dtype.  ``None`` (the default) reads the dtype the
            store declares — see :func:`vertices_dtype`.
        ndim: Number of coordinate dimensions (D).
        default: When supplied, returned instead of raising when the
            ``vertices`` array cannot be read at all.  Pass ``None`` for
            the common "soft-fail with None" pattern.  A chunk nobody
            wrote is NOT a failure — it reads back as ``(0, D)``.

    Returns:
        ``(N, D)`` array (``(N,)`` when ``ndim == 1``), or ``default``.

    Raises:
        ArrayError: If the array cannot be read and no ``default`` is given.
    """
    key = _chunk_key(chunk_coords)
    dtype = vertices_dtype(level_group) if dtype is None else np.dtype(dtype)
    try:
        raw = level_group.read_bytes(VERTICES, key)
    except (ArrayError, StoreError):
        if default is _UNSET:
            raise
        return default
    except Exception as e:
        if default is _UNSET:
            raise ArrayError(f"Cannot read vertices chunk {key}: {e}") from e
        return default
    return _reshape_vertex_buffer(raw, dtype, ndim)


def chunk_vertex_count(
    level_group: Group,
    chunk_coords: ChunkCoords,
    *,
    default: int = 0,
) -> int:
    """How many vertex rows a chunk spans, without decoding any of them.

    ``max(referenced row) + 1`` over the chunk's fragment index — the
    length per-vertex attribute cells must be written at, and the row
    count :func:`read_chunk_vertex_buffer` returns for a buffer every row
    of which some fragment references.

    Reads only the fragment index, which is kilobytes; the alternative
    every consumer reaches for first — decode the vertices and call
    ``len`` — decompresses the whole chunk for a number the index already
    carries, and via the plural readers it decodes each fragment's rows
    again on top.

    Returns ``default`` (0) when the chunk has no fragment index.
    """
    try:
        fi = read_vertex_fragment_index(level_group, chunk_coords)
    except (ArrayError, StoreError):
        return int(default)
    return int(_fragment_vertex_extent(fi))


def read_fragment(
    level_group: Group,
    chunk_coords: ChunkCoords,
    fragment_index: int,
    dtype: np.dtype | str = np.float32,
    ndim: int = 3,
    *,
    default: Any = _UNSET,
) -> npt.NDArray[np.floating] | Any:
    """Read a single vertex fragment from a chunk.

    Dispatches on the ``vertex_fragments/<chunk>`` index: range fragments
    use a byte-slice fast path -- on an uncompressed array a byte-range
    read of just the fragment's rows (:meth:`Group.read_cell_range`),
    otherwise a slice of the whole chunk buffer; explicit fragments
    reshape the full chunk buffer and gather rows via
    ``fi.indices(fragment_index)``.

    Args:
        level_group: Resolution level group.
        chunk_coords: Spatial chunk coordinates.
        fragment_index: Index of the fragment within the chunk.
        dtype: Numpy dtype.
        ndim: Number of coordinate dimensions.
        default: When supplied, returned on read failure (missing chunk
            or out-of-range ``fragment_index``) instead of raising.  Pass
            ``None`` for the common "soft-fail with None" pattern.  Only
            :class:`ArrayError` and :class:`StoreError` are caught;
            programming errors propagate.

    Returns:
        Array of shape ``(N, D)`` (or ``(N,)`` when ``ndim == 1``), or
        ``default`` when supplied and the read fails.
    """
    key = _chunk_key(chunk_coords)
    dtype = np.dtype(dtype)

    try:
        if level_group.range_readable(VERTICES):
            # Uncompressed: the index says where the rows are, and only
            # those bytes are read -- the rest of the chunk never is.
            fi = read_vertex_fragment_index(level_group, chunk_coords)
            if 0 <= fragment_index < fi.num_fragments:
                span = fragment_byte_range(
                    fi, fragment_index, dtype.itemsize * int(ndim),
                )
                if span is not None:
                    raw = level_group.read_cell_range(VERTICES, key, *span)
                    _, count = fi.range(fragment_index)
                    return _slice_vertex_range(raw, 0, count, dtype, ndim)
        with _maybe_batched_reads(level_group, [
            (VERTICES, [key]),
            (VERTEX_FRAGMENTS, [key]),
        ]):
            raw = level_group.read_bytes(VERTICES, key)
            fi = read_vertex_fragment_index(level_group, chunk_coords)

        if fragment_index < 0 or fragment_index >= fi.num_fragments:
            raise ArrayError(
                f"Fragment index {fragment_index} out of range "
                f"(chunk {key} has {fi.num_fragments} groups)"
            )

        if fi.is_range(fragment_index):
            start, count = fi.range(fragment_index)
            return _slice_vertex_range(raw, start, count, dtype, ndim)

        full = _reshape_vertex_buffer(raw, dtype, ndim)
        return full[fi.indices(fragment_index)]
    except (ArrayError, StoreError):
        if default is _UNSET:
            raise
        return default


def read_chunk_links(
    level_group: Group,
    chunk_coords: ChunkCoords,
    dtype: np.dtype | str = np.int64,
    link_width: int | None = None,
    *,
    delta: int = 0,
    offsets: Sequence[ChunkCoords] | None = None,
) -> list[npt.NDArray[np.integer]]:
    """Read link groups from one cell of ``links/<delta>/<offsets>/``.

    The per-cell counterpart to :func:`write_chunk_links`, and it mirrors
    its encoding rule exactly: ``chunk_coords`` is the **source** chunk
    (the cell) and ``offsets`` names the array.  Defaults to the all-zero
    (intra-chunk) offsets — the array holding records whose endpoints all
    share the source chunk.

    Rows come back **as stored**, in placement order: this reader does not
    reverse a canonical sort.  Where the array carries a ``perm_idx``
    column (see :func:`links_has_perm`) the returned rows are ``1 + L``
    wide, with ``perm_idx`` in column 0 and the ``L`` vertex indices after
    it — and those indices are in the placement's endpoint order, not the
    order they were written in.  Use :func:`read_links` or
    :func:`read_links_for_tuple` for whole records in input order.

    Args:
        level_group: Resolution level group.
        chunk_coords: **Source** chunk coordinates (the array cell).
        dtype: Integer dtype.
        link_width: The **logical** width L. If None, read from the family
            group's metadata.  Note the *stored* width may be ``1 + L``;
            this argument never changes how the bytes are decoded, which
            is governed by the array's own ``has_perm`` stamp.
        delta: Level delta; ``0`` is the intra-level family.
        offsets: Relative offsets naming the array.  ``None`` (default)
            means the all-zero intra-chunk offsets.

    Returns:
        List of arrays, each ``(M_k, L)`` — or ``(M_k, 1 + L)`` when the
        array carries ``perm_idx``.
    """
    from zarr_vectors.octree_chunks.guard import refuse_octree_read

    # A leaf is no uniform cell (the octree readers go through read_octree).
    refuse_octree_read(level_group, "read_chunk_links")
    key = _chunk_key(chunk_coords)
    dtype = np.dtype(dtype)

    # Read L from the <delta> family group, not from the array: the
    # offsets segment naming the array is itself a function of L, so
    # reading it from the array would be circular.
    fam_meta = level_group.read_array_meta(links_group_path(delta)) or {}
    if link_width is None:
        link_width = int(fam_meta.get("link_width", 2))
    if offsets is None:
        offsets = intra_offsets(len(chunk_coords), link_width)
    full_name = links_path(delta, offsets)

    # Decode at the PHYSICAL row width.  ``link_width`` is the logical
    # width; a links_has_perm array stores 1 + L per row.  Decoding
    # physical bytes at the logical width does not reliably raise: with N
    # records the cell holds (1 + L)*N elements, and (1 + L)*N ≡ N (mod L),
    # so it silently yields (1 + L)*N/L fabricated rows whenever
    # N % L == 0 — every even N at L=2.  Take the width from the array's
    # own stamp; never infer it from L.
    arr_meta = level_group.read_array_meta(full_name) or {}
    has_perm = bool(arr_meta.get(
        "has_perm",
        links_has_perm(
            offsets,
            delta=delta,
            directed=bool(fam_meta.get("directed", False)),
            store=str(fam_meta.get("store", "canonical")),
        ),
    ))
    ncols = (1 + link_width) if has_perm else link_width

    # Only the intra array at delta 0 is flat-with-sidecar; every other
    # offset array is an inline self-describing blob.  Same condition as
    # write_chunk_links — keep them in lockstep.
    flat = delta == 0 and is_intra(offsets)
    plan: list[tuple[str, list[str]]] = [(full_name, [key])]
    if flat:
        plan.append((LINK_FRAGMENTS, [key]))

    with _maybe_batched_reads(level_group, plan):
        try:
            raw = level_group.read_bytes(full_name, key)
        except Exception as e:
            raise ArrayError(
                f"Cannot read links chunk {key} (delta={format_delta(delta)}, "
                f"offsets={format_offsets(offsets)}): {e}"
            ) from e

        if flat:
            # v0.6 intra-level layout: raw is the flat concatenated link
            # data; per-group row counts live in link_fragments/<chunk>.
            # In the native-sharded layout, ``links/0`` is a single
            # multidim Zarr array; cells for chunks with no intra-edges
            # return ``b""`` (the vlen fill value) instead of "chunk not
            # found".  Short-circuit that case before trying to read
            # the (likely absent) ``link_fragments`` array.
            if not raw:
                return []
            fi = read_link_fragment_index(level_group, chunk_coords)
            if fi.num_fragments == 0:
                return []
            full = _reshape_link_buffer(raw, dtype, ncols)
            groups: list[npt.NDArray[np.integer]] = []
            for f in range(fi.num_fragments):
                if fi.is_range(f):
                    start, count = fi.range(f)
                    groups.append(full[start : start + count])
                else:
                    groups.append(full[fi.indices(f)])
            return groups

        # Cross-offset and/or cross-level: inline self-describing blob.
        return decode_ragged_blob(raw, dtype, ncols=ncols)


def read_chunk_link_fragment(
    level_group: Group,
    chunk_coords: ChunkCoords,
    fragment_index: int,
    dtype: np.dtype | str = np.int64,
    link_width: int | None = None,
    *,
    default: Any = _UNSET,
) -> npt.NDArray[np.integer] | Any:
    """Read a single link fragment from a chunk's ``links/0/<chunk>`` array.

    Intra-level only (``delta == 0``). Dispatches on the
    ``link_fragments/<chunk>`` index: range fragments use a byte-slice
    fast path; explicit fragments reshape the full chunk buffer and gather
    rows via ``fi.indices(fragment_index)``.

    Args:
        level_group: Resolution level group.
        chunk_coords: Spatial chunk coordinates.
        fragment_index: Index of the fragment within the chunk.
        dtype: Integer dtype.
        link_width: Number of columns per link (L). If None, read from
            array metadata.
        default: When supplied, returned on read failure (missing chunk
            or out-of-range ``fragment_index``) instead of raising.  Pass
            ``None`` for the common "soft-fail with None" pattern.  Only
            :class:`ArrayError` and :class:`StoreError` are caught;
            programming errors propagate.

    Returns:
        Array of shape ``(M, L)`` (or ``(M,)`` when ``link_width == 1``),
        or ``default`` when supplied and the read fails.

    Raises:
        ArrayError: If the chunk does not exist or ``fragment_index`` is
            out of range, AND ``default`` was not supplied.
    """
    key = _chunk_key(chunk_coords)
    dtype = np.dtype(dtype)

    try:
        if link_width is None:
            # From the family group — the offsets segment naming the
            # array depends on L, so reading L from the array is circular.
            fam_meta = level_group.read_array_meta(links_group_path(0)) or {}
            link_width = int(fam_meta.get("link_width", 2))
        # link_fragments/ only ever partitions the intra array at delta 0
        # (it is keyed by chunk alone, with no delta or offsets segment),
        # so this reader is intra-only by construction.
        full_name = links_path(0, intra_offsets(len(chunk_coords), link_width))

        with _maybe_batched_reads(level_group, [
            (full_name, [key]),
            (LINK_FRAGMENTS, [key]),
        ]):
            try:
                raw = level_group.read_bytes(full_name, key)
            except Exception as e:
                raise ArrayError(
                    f"Cannot read links chunk {key} (delta=0): {e}"
                ) from e
            fi = read_link_fragment_index(level_group, chunk_coords)

        if fragment_index < 0 or fragment_index >= fi.num_fragments:
            raise ArrayError(
                f"Fragment index {fragment_index} out of range "
                f"(chunk {key} has {fi.num_fragments} groups)"
            )

        if fi.is_range(fragment_index):
            start, count = fi.range(fragment_index)
            return _slice_link_range(raw, start, count, dtype, link_width)

        full = _reshape_link_buffer(raw, dtype, link_width)
        return full[fi.indices(fragment_index)]
    except (ArrayError, StoreError):
        if default is _UNSET:
            raise
        return default


def attribute_layout(
    level_group: Group,
    name: str,
    *,
    scope: str = "vertex",
) -> tuple[np.dtype, int]:
    """The ``(dtype, ncols)`` an attribute array was written with.

    Resolution order, most authoritative first: the stamped
    ``row_shape``; then ``len(channel_names)``; then 1.  ``dtype`` comes
    from the stamped field, defaulting to float32.

    Offered because the column count was previously recoverable only by
    counting ``channel_names``, so every consumer carried its own
    ``ncols = len(channel_names) if channel_names else 1`` — and any
    consumer that forgot read a C-column attribute as C times as many
    scalar rows, silently.

    Args:
        scope: ``"vertex"`` or ``"fragment"``.
    """
    group = {
        "vertex": VERTEX_ATTRIBUTES,
        "fragment": FRAGMENT_ATTRIBUTES,
    }.get(scope)
    if group is None:
        raise ArrayError(
            f"unknown attribute scope {scope!r}; expected 'vertex' or 'fragment'"
        )
    return _resolve_attribute_layout(level_group, f"{group}/{name}", None, None)


def _resolve_attribute_layout(
    level_group: Group,
    full_name: str,
    dtype: np.dtype | str | None,
    ncols: int | None,
) -> tuple[np.dtype, int]:
    """Resolve ``(dtype, ncols)`` for one attribute array.

    ``None`` for either means "ask the store".  An explicit value that
    CONTRADICTS a stamped one raises rather than being honoured: reading
    at the wrong stride does not fail, it returns a differently-shaped
    array of the same bytes, so the mismatch has to be caught here or not
    at all.
    """
    try:
        meta = level_group.read_array_meta(full_name) or {}
    except Exception:
        meta = {}

    stamped_dtype = meta.get("dtype")
    if dtype is None:
        resolved_dtype = np.dtype(stamped_dtype or np.float32)
    else:
        resolved_dtype = np.dtype(dtype)
        if stamped_dtype and np.dtype(stamped_dtype) != resolved_dtype:
            raise ArrayError(
                f"{full_name!r} is stored as {stamped_dtype!r} but was read "
                f"as {resolved_dtype!r}. Reading at the wrong element size "
                f"does not raise on its own -- it silently reinterprets the "
                f"bytes. Pass dtype=None to use the stored one."
            )

    row_shape = meta.get("row_shape")
    if row_shape is not None:
        stamped_ncols: int | None = int(row_shape[0]) if list(row_shape) else 1
    else:
        channel_names = meta.get("channel_names")
        stamped_ncols = len(channel_names) if channel_names else None

    if ncols is None:
        resolved_ncols = stamped_ncols if stamped_ncols is not None else 1
    else:
        resolved_ncols = int(ncols)
        if stamped_ncols is not None and stamped_ncols != resolved_ncols:
            raise ArrayError(
                f"{full_name!r} holds {stamped_ncols}-column rows but was "
                f"read as {resolved_ncols}-column. Pass ncols=None to use "
                f"the stored width."
            )
    return resolved_dtype, resolved_ncols


def read_chunk_attributes(
    level_group: Group,
    attr_name: str,
    chunk_coords: ChunkCoords,
    dtype: np.dtype | str | None = None,
    ncols: int | None = None,
    *,
    vert_dtype: np.dtype | str | None = None,
    vert_ndim: int | None = None,
) -> list[npt.NDArray]:
    """Read vertex attribute data for a chunk.

    Per-vertex attributes are stored one row per vertex, aligned 1:1
    with the ``vertices`` buffer (Core-1's fragment 0).  Each fragment
    is gathered by vertex index from the shared attribute buffer via the
    ``vertex_fragments/<chunk>`` index — range fragments as contiguous
    slices, explicit fragments via ``fi.indices(f)`` — exactly as
    :func:`read_chunk_vertices` does.  There is no contiguity
    requirement, so explicit path-fragment vertex-fragments (e.g.
    a downstream pipeline's polyline twins appended on top of Core-1's range) read
    correctly.

    Args:
        level_group: Resolution level group.
        attr_name: Attribute name.
        chunk_coords: Spatial chunk coordinates.
        dtype: Numpy dtype of the attribute.
        ncols: Number of columns (channels). Use 1 for scalars.
        vert_dtype: Retained for backward compatibility; ignored.
            Per-fragment sizes now come from the fragment index directly.
        vert_ndim: Retained for backward compatibility; ignored.

    Returns:
        List of arrays aligned with fragments, each ``(N_k, ncols)`` (or
        ``(N_k,)`` when ``ncols == 1``).  ``groups[0]`` is Core-1's
        fragment 0 — the full per-vertex buffer for the chunk.
    """
    del vert_dtype, vert_ndim  # retained for signature compat; unused
    key = _chunk_key(chunk_coords)
    full_name = f"{VERTEX_ATTRIBUTES}/{attr_name}"
    dtype, ncols = _resolve_attribute_layout(level_group, full_name, dtype, ncols)

    with _maybe_batched_reads(level_group, [
        (full_name, [key]),
        (VERTEX_FRAGMENTS, [key]),
    ]):
        try:
            raw = level_group.read_bytes(full_name, key)
        except Exception as e:
            raise ArrayError(
                f"Cannot read attribute '{attr_name}' chunk {key}: {e}"
            ) from e
        fi = read_vertex_fragment_index(level_group, chunk_coords)

    if fi.num_fragments == 0:
        return []
    # Per-vertex attributes are one row per underlying vertex, aligned 1:1
    # with the ``vertices`` buffer (Core-1's fragment 0).  Reshape the flat
    # buffer to ``(N_vertices, width)`` where ``width`` is the attribute's
    # true per-vertex column count (derived from the buffer size and the
    # vertex extent — independent of the requested ``ncols``), then gather
    # each fragment by vertex index exactly as read_chunk_vertices does:
    # range fragments as contiguous slices, explicit fragments (e.g.
    # a downstream pipeline's appended path-fragment twins) via ``fi.indices(f)``.  Each
    # gathered group is finally flattened and re-shaped to honour the
    # caller's ``ncols`` (ncols=1 yields a flat 1-D array), matching the
    # historical decode_ragged_floats contract.
    full = attribute_buffer(
        raw, fi, dtype, what=f"Attribute '{attr_name}' chunk {key}",
    )
    if full is None:
        empty = np.empty((0,) if ncols == 1 else (0, ncols), dtype=dtype)
        return [empty for _ in range(fi.num_fragments)]
    return [
        shape_attribute_rows(rows, ncols) for rows in _partition_rows(full, fi)
    ]


def read_attribute_fragment(
    level_group: Group,
    attr_name: str,
    chunk_coords: ChunkCoords,
    fragment_index: int,
    dtype: np.dtype | str | None = None,
    ncols: int | None = None,
    *,
    default: Any = _UNSET,
) -> npt.NDArray | Any:
    """Read a single fragment's per-vertex attribute rows from a chunk.

    The attribute counterpart to :func:`read_fragment`, and the same
    reason to prefer it: ``read_chunk_attributes(...)[k]`` decodes and
    copies **every** fragment in the chunk to hand back one of them, so a
    caller that wants only Core-1's fragment 0 pays for every
    path-fragment twin appended after it.  That cost grows as the store
    is written, which turns a fixed-size read into one that scales with
    how much of the surrounding volume has already been built.

    Semantics are identical to indexing :func:`read_chunk_attributes` at
    ``fragment_index``: rows are gathered by vertex index from the shared
    per-vertex buffer (range fragments as a contiguous slice, explicit
    fragments via ``fi.indices``), flattened, then reshaped to honour
    ``ncols``.

    Args:
        level_group: Resolution level group.
        attr_name: Attribute name.
        chunk_coords: Spatial chunk coordinates.
        fragment_index: Index of the fragment within the chunk.
        dtype: Numpy dtype of the attribute.
        ncols: Number of columns (channels). Use 1 for scalars.
        default: When supplied, returned on read failure (missing chunk
            or out-of-range ``fragment_index``) instead of raising.  Only
            :class:`ArrayError` and :class:`StoreError` are caught;
            programming errors propagate.

    Returns:
        Array of shape ``(N, ncols)`` (or ``(N,)`` when ``ncols == 1``),
        or ``default`` when supplied and the read fails.
    """
    key = _chunk_key(chunk_coords)
    full_name = f"{VERTEX_ATTRIBUTES}/{attr_name}"

    try:
        dtype, ncols = _resolve_attribute_layout(
            level_group, full_name, dtype, ncols,
        )

        with _maybe_batched_reads(level_group, [
            (full_name, [key]),
            (VERTEX_FRAGMENTS, [key]),
        ]):
            try:
                raw = level_group.read_bytes(full_name, key)
            except Exception as e:
                raise ArrayError(
                    f"Cannot read attribute '{attr_name}' chunk {key}: {e}"
                ) from e
            fi = read_vertex_fragment_index(level_group, chunk_coords)

        if fragment_index < 0 or fragment_index >= fi.num_fragments:
            raise ArrayError(
                f"Fragment index {fragment_index} out of range "
                f"(chunk {key} has {fi.num_fragments} groups)"
            )

        itemsize = dtype.itemsize
        total_elements = len(raw) // itemsize if itemsize else 0
        n_vertices = _fragment_vertex_extent(fi)
        if n_vertices <= 0 or total_elements == 0:
            return np.empty((0,) if ncols == 1 else (0, ncols), dtype=dtype)
        if total_elements % n_vertices != 0:
            raise ArrayError(
                f"Attribute '{attr_name}' chunk {key} has {total_elements} "
                f"elements, not a multiple of its {n_vertices} vertices; "
                "per-vertex attributes must align 1:1 with the vertices array."
            )
        width = total_elements // n_vertices
        full = np.frombuffer(raw, dtype=dtype).reshape(n_vertices, width)

        if fi.is_range(fragment_index):
            start, count = fi.range(fragment_index)
            rows = full[start : start + count]
        else:
            rows = full[fi.indices(fragment_index)]
        flat = np.ascontiguousarray(rows).reshape(-1)
        return flat if ncols == 1 else flat.reshape(-1, ncols)
    except (ArrayError, StoreError):
        if default is _UNSET:
            raise
        return default


@_device_result(on_device=True)
def read_chunk_fragment_attributes(
    level_group: Group,
    attr_name: str,
    chunk_coords: ChunkCoords,
    dtype: np.dtype | str | None = None,
    ncols: int | None = None,
    *,
    default: Any = _UNSET,
) -> npt.NDArray | Any:
    """Read per-fragment attribute data for a spatial chunk.

    The on-disk layout is a dense per-chunk byte blob; ``F`` (number of
    fragments) is derived from the byte length and the row stride
    (``dtype.itemsize * ncols``).  No round-trip to ``vertex_fragments``
    is needed.

    Args:
        level_group: Resolution level group.
        attr_name: Attribute name.
        chunk_coords: Spatial chunk coordinates.
        dtype: Numpy dtype of the attribute.  ``None`` (the default)
            reads the dtype the array was written with.
        ncols: Number of columns (channels).  ``None`` (the default)
            reads the stored width -- ``row_shape``, else
            ``len(channel_names)``, else 1.  An explicit value that
            contradicts the stored one raises.
        default: When supplied, returned on read failure (missing chunk,
            byte-length mismatch) instead of raising.  Pass ``None`` for
            the common "soft-fail with None" pattern.  Only
            :class:`ArrayError` and :class:`StoreError` are caught;
            programming errors propagate.

    Returns:
        Array of shape ``(F,)`` (when ``ncols == 1``) or ``(F, ncols)``
        (when ``ncols > 1``).  Empty 1-D array when the blob is empty.
    """
    key = _chunk_key(chunk_coords)
    full_name = f"{FRAGMENT_ATTRIBUTES}/{attr_name}"
    dtype, ncols = _resolve_attribute_layout(level_group, full_name, dtype, ncols)
    row_bytes = dtype.itemsize * ncols

    try:
        # An unwritten cell of a vlen array reads back b"" rather than
        # raising, and b"" passes the stride check below — so without this
        # guard a missing chunk would quietly decode to an empty array and
        # ``default`` would never be honoured.  ``chunk_exists`` consults
        # the presence manifest, which is what distinguishes "absent" from
        # "empty" now that the two are byte-identical.
        if not level_group.chunk_exists(full_name, key):
            raise ArrayError(
                f"fragment_attribute '{attr_name}' chunk {key} not present"
            )
        try:
            raw = level_group.read_bytes(full_name, key)
        except Exception as e:
            raise ArrayError(
                f"Cannot read fragment_attribute '{attr_name}' chunk {key}: {e}"
            ) from e

        if row_bytes <= 0 or len(raw) % row_bytes != 0:
            raise ArrayError(
                f"fragment_attribute '{attr_name}' chunk {key}: byte length "
                f"{len(raw)} is not a multiple of row stride "
                f"{row_bytes} (dtype={dtype}, ncols={ncols})"
            )

        flat = np.frombuffer(raw, dtype=dtype)
        if ncols == 1:
            return flat.copy()
        return flat.reshape(-1, ncols).copy()
    except (ArrayError, StoreError):
        if default is _UNSET:
            raise
        return default


def read_chunk_link_attributes(
    level_group: Group,
    attr_name: str,
    chunk_coords: ChunkCoords,
    dtype: np.dtype | str | None = None,
    ncols: int | None = None,
    *,
    delta: int = 0,
) -> list[npt.NDArray]:
    """Read per-link attribute data for a chunk's intra-chunk links.

    Mirrors :func:`read_chunk_attributes` for the per-link case: the
    ragged bytes live under
    ``link_attributes/<name>/<delta>/<all-zero offsets>/<chunk>`` and
    align 1:1 with the link fragments under ``link_fragments/<chunk>``.

    Intra-chunk at ``delta == 0`` only, and not by omission: the fragment
    sidecar is keyed by chunk alone, so the all-zero-offsets array is the
    only one it partitions.  Attributes on any other offsets array have no
    fragment structure to align to — read those with
    :func:`read_link_attributes`.  Per-link group ``k`` has the
    same row count as link group ``k`` in ``links/<delta>/<chunk>``.

    Args:
        level_group: Resolution level group.
        attr_name: Attribute name (e.g. ``"weight"``).
        chunk_coords: Spatial chunk coordinates.
        dtype: Numpy dtype of the attribute.  ``None`` (the default)
            reads the dtype the array was written with.
        ncols: Number of columns (channels).  ``None`` (the default)
            reads the stored width -- ``row_shape``, else
            ``len(channel_names)``, else 1.  An explicit value that
            contradicts the stored one raises.
        delta: Level delta; cross-level link attributes are stored
            differently and must be read via the whole-family
            :func:`read_link_attributes` — this helper handles only the
            per-chunk ``delta == 0`` case.

    Returns:
        List of arrays aligned with the link fragments in the chunk.
    """
    if delta != 0:
        raise ArrayError(
            f"read_chunk_link_attributes only supports delta=0 "
            f"(per-chunk intra-level); got delta={delta}.  Use "
            f"read_link_attributes for cross-level link attributes.",
        )
    key = _chunk_key(chunk_coords)
    # Fragment-aligned attributes exist only for the intra array: it is
    # the one link_fragments/<chunk> partitions.
    fam_meta = level_group.read_array_meta(links_group_path(delta)) or {}
    link_width = int(fam_meta.get("link_width", 2))
    full_name = link_attributes_path(
        attr_name, delta, intra_offsets(len(chunk_coords), link_width),
    )
    # This family already stamps row_shape (write_link_attribute_cells and
    # write_link_attributes both do), so the resolver has something
    # authoritative to read here.
    dtype, ncols = _resolve_attribute_layout(level_group, full_name, dtype, ncols)

    try:
        raw = level_group.read_bytes(full_name, key)
    except Exception as e:
        raise ArrayError(
            f"Cannot read link attribute '{attr_name}' chunk {key} "
            f"(delta={format_delta(delta)}): {e}"
        ) from e

    # Per-link group `k` has N_k rows where N_k = link_fragments[k].count.
    # Derive byte offsets from the link-fragment sidecar.
    fi = read_link_fragment_index(level_group, chunk_coords)
    if fi.num_fragments == 0:
        return []
    row_bytes = int(dtype.itemsize) * int(ncols)
    cursor = 0
    out: list[npt.NDArray] = []
    for f in range(fi.num_fragments):
        if not fi.is_range(f):
            raise ArrayError(
                f"link_fragments/{key} fragment {f} is non-contiguous; "
                "read_chunk_link_attributes requires every fragment to be "
                "a contiguous range of link rows.",
            )
        _start, count = fi.range(f)
        seg = raw[cursor : cursor + int(count) * row_bytes]
        cursor += int(count) * row_bytes
        arr = np.frombuffer(seg, dtype=dtype)
        if ncols > 1:
            arr = arr.reshape(-1, ncols)
        out.append(arr.copy())
    return out


def _infer_vert_ndim(level_group: Group) -> int:
    """Best-effort lookup of the spatial-index dimensionality.

    Reads the length of the root's ``zarr_vectors.axes``.  Falls back to
    3 when unavailable.
    """
    try:
        # Level groups don't carry root attrs; walk up to root via the
        # backend.  Most levels have an ``_backend`` handle that owns
        # the root path.
        from zarr_vectors.core.group import Group
        root_handle = Group._from_backend(level_group._backend, "")
        zv = root_handle.attrs.to_dict().get("zarr_vectors") or {}
        axes = zv.get("axes") or []
        if axes:
            return len(axes)
    except Exception:
        pass
    return 3


def read_object_manifest(
    level_group: Group,
    object_id: int,
) -> ObjectManifest:
    """Read the ordered fragment reference list for one object.

    Args:
        level_group: Resolution level group.
        object_id: Object ID.

    Returns:
        List of ``(chunk_coords, fragment_index)`` tuples.
    """
    meta = level_group.read_array_meta(OBJECT_INDEX)
    sid_ndim = meta["sid_ndim"]
    num_objects = meta["num_objects"]

    _require_object_index_layout(meta)
    found, rows = object_rows_for_ids(level_group, [object_id])
    if found.size == 0:
        raise ArrayError(
            f"Object ID {object_id} is not in this level "
            f"({num_objects} object(s))"
        )
    from zarr_vectors.core import dense_manifests as dense

    if dense.is_dense(level_group, meta):
        return dense.manifests_from_csr(*dense.read_csr(level_group, rows[:1]))[0]
    # Via the Group rather than the raw zarr node, so the read passes a
    # chokepoint the offline snapshot can serve (see Group.offline_reads).
    # Slice-then-extract, never scalar-index: see zarr_vectors.core._vlen.
    # This 1-D manifests array shares that rule with the N-D cell readers.
    blob = level_group.read_vlen_element(
        f"{OBJECT_INDEX}/manifests", int(rows[0]),
    )
    blocks = decode_object_manifest_blocks(blob, sid_ndim=sid_ndim)
    return expand_manifest_blocks(blocks)


def read_all_object_manifests(
    level_group: Group,
) -> list[ObjectManifest]:
    """Read all object manifests at once.

    Returns:
        List indexed by object_id, each a list of ``(chunk_coords, fragment_index)``.
    """
    meta = level_group.read_array_meta(OBJECT_INDEX)
    sid_ndim = meta["sid_ndim"]
    num_objects = int(meta.get("num_objects", 0))

    _require_object_index_layout(meta)
    if num_objects == 0:
        return []
    from zarr_vectors.core import dense_manifests as dense

    if dense.is_dense(level_group, meta):
        return dense.manifests_from_csr(*dense.read_csr(level_group))
    # Via the Group rather than the raw zarr node, so the read passes a
    # chokepoint the offline snapshot can serve (see Group.offline_reads).
    blobs = level_group.read_vlen_array(f"{OBJECT_INDEX}/manifests")
    return _decode_manifests(blobs, sid_ndim)


@dataclass(frozen=True)
class ManifestCSR:
    """Every object's manifest as flat arrays.

    Object row ``o`` owns rows ``offsets[o]:offsets[o + 1]`` of
    ``chunk_coords`` and ``fragment_idx``. ``object_ids[o]`` is its id,
    or ``object_ids`` is ``None`` when rows are the ids. Unpacks as
    ``offsets, chunk_coords, fragment_idx = read_all_object_manifests_csr(lg)``.
    """

    offsets: Any
    chunk_coords: Any
    fragment_idx: Any
    object_ids: Any = None

    def __iter__(self) -> Iterator[Any]:
        return iter((self.offsets, self.chunk_coords, self.fragment_idx))


@_device_result
def _manifest_csr_arrays(level_group: Group) -> tuple[npt.NDArray, ...]:
    meta = level_group.read_array_meta(OBJECT_INDEX)
    _require_object_index_layout(meta)
    sid_ndim = int(meta["sid_ndim"])
    num_objects = int(meta.get("num_objects", 0))
    from zarr_vectors.core import dense_manifests as dense

    if dense.is_dense(level_group, meta):
        offsets, coords, frags = (
            dense.read_csr(level_group, stop=num_objects) if num_objects
            else (np.zeros(1, np.int64), np.empty((0, sid_ndim), np.int64), np.empty(0, np.int64))
        )
    else:
        blobs = (
            level_group.read_vlen_array_raw(f"{OBJECT_INDEX}/manifests", stop=num_objects)
            if num_objects else np.empty(0, dtype=object)
        )
        offsets, coords, frags = decode_object_manifests_csr(blobs, sid_ndim)
    if len(offsets) - 1 < num_objects:
        # A committed count past the stored rows: the missing rows are
        # objects with no fragments, as a read by id would find them.
        offsets = np.concatenate([
            offsets, np.full(num_objects - len(offsets) + 1, offsets[-1]),
        ])
    return offsets, coords, frags


def read_all_object_manifests_csr(
    level_group: Group, *, device: str | None = None,
) -> ManifestCSR:
    """Every committed manifest as CSR arrays, decoded without per-object Python.

    Reads rows ``[0, num_objects)``: the committed prefix, where
    :func:`read_all_object_manifests` also decodes any rows a torn flush
    left past it. Range and explicit-list blocks are expanded to one row
    per fragment, in manifest order. ``device="cuda"`` returns the three
    arrays on the device (ids stay on the host).
    """
    offsets, coords, frags = _manifest_csr_arrays(level_group, device=device)
    table = read_object_id_table(level_group)
    if table is not None:
        table = table[: int(offsets.shape[0]) - 1]
    return ManifestCSR(offsets, coords, frags, table)


def _decode_manifests(blobs: Sequence[bytes], sid_ndim: int) -> list[ObjectManifest]:
    """Every blob's expanded manifest, decoded as one batch.

    The uniform case -- every block a single fragment, which is what
    every bulk writer produces -- comes back from the batch decoder
    already in the expanded ``(chunk_coords, fragment_index)`` shape;
    anything else is expanded blob by blob.
    """
    decoded, uniform = decode_object_manifests_many(blobs, sid_ndim=sid_ndim)
    if uniform:
        return decoded
    return [expand_manifest_blocks(blocks) for blocks in decoded]



#: Fragment-attribute column naming the object that owns each fragment.
#:
#: ``constants.FRAGMENT_ATTRIBUTES`` already reserves this: "including
#: parent-IDs (e.g. an ``object_id`` fragment attribute carrying the OID
#: that owns each fragment)".  Writing it makes "which objects reference
#: this fragment" a single cell read rather than a decode of every
#: manifest in the level.
FRAGMENT_OWNER_ATTR = "object_id"

#: Owner value meaning "more than one object references this fragment".
#:
#: Shared fragments are a declared capability (``CAP_SHARED_FRAGMENTS``),
#: so one int64 cannot always name the owner.  It is deliberately not
#: ``-1``, which already means "no parent" in the cross-level tables --
#: reusing it would make an unowned fragment and a jointly-owned one
#: indistinguishable.
FRAGMENT_OWNER_SHARED = -2

#: Owner value for a fragment no object references.
FRAGMENT_OWNER_NONE = -1


def build_fragment_owner_column(
    level_group: Group,
) -> dict[ChunkCoords, npt.NDArray[np.int64]]:
    """The owning object id of every fragment, per chunk.

    Derived from the manifests, which is the only place the relation is
    recorded today.  Writing the result as a
    ``fragment_attributes/object_id`` column is what turns the reverse
    question into a read: without it, every caller that asks "which
    objects reference this fragment" rebuilds this whole inversion in
    memory, and four separate places in this package do exactly that.

    A fragment named by more than one object is marked
    :data:`FRAGMENT_OWNER_SHARED` rather than given one of its owners,
    so a reader knows to consult the manifests instead of trusting a
    half-truth.
    """
    ids, manifests = read_object_manifest_rows(level_group)
    counts: dict[ChunkCoords, int] = {}
    for manifest in manifests:
        for cc, fi in manifest:
            key = tuple(int(c) for c in cc)
            counts[key] = max(counts.get(key, 0), int(fi) + 1)
    owners = {
        cc: np.full(n, FRAGMENT_OWNER_NONE, dtype=np.int64)
        for cc, n in counts.items()
    }
    for oid, manifest in zip(ids.tolist(), manifests):
        for cc, fi in manifest:
            col = owners[tuple(int(c) for c in cc)]
            current = int(col[int(fi)])
            if current == FRAGMENT_OWNER_NONE:
                col[int(fi)] = int(oid)
            elif current != int(oid):
                col[int(fi)] = FRAGMENT_OWNER_SHARED
    return owners


def write_fragment_owner_column(level_group: Group) -> int:
    """Materialise :func:`build_fragment_owner_column` on the level.

    Returns the number of fragments recorded.  Safe to re-run; it
    rewrites whatever it finds.
    """
    owners = build_fragment_owner_column(level_group)
    if not owners:
        return 0
    total = 0
    create_fragment_attribute_array(
        level_group, FRAGMENT_OWNER_ATTR, dtype="int64", exist_ok=True,
    )
    with level_group.batched_writes():
        for cc, column in sorted(owners.items()):
            write_chunk_fragment_attributes(
                level_group, FRAGMENT_OWNER_ATTR, cc, column, dtype=np.int64,
            )
            total += int(column.size)
    return total


def read_fragment_owners(
    level_group: Group,
    chunk_coords: ChunkCoords,
    fragment_index: int,
) -> list[int] | None:
    """Object ids referencing one fragment, or ``None`` if not recorded.

    ``None`` means the level carries no owner column, or the fragment is
    marked shared -- in both cases the caller must fall back to scanning
    the manifests, which is what it did before this column existed.
    """
    try:
        column = read_chunk_fragment_attributes(
            level_group, FRAGMENT_OWNER_ATTR, chunk_coords, dtype=np.int64,
        )
    except Exception:
        return None
    if column is None or int(fragment_index) >= len(column):
        return None
    owner = int(np.asarray(column).reshape(-1)[int(fragment_index)])
    if owner == FRAGMENT_OWNER_SHARED:
        return None
    return [] if owner == FRAGMENT_OWNER_NONE else [owner]


def read_object_manifest_rows(
    level_group: Group,
) -> tuple[npt.NDArray[np.int64], list[ObjectManifest]]:
    """Every manifest in row order, paired with the id that owns it.

    The honest replacement for enumerating
    :func:`read_all_object_manifests`. That returns a list indexed by
    *row*, and a caller writing ``for oid, manifest in enumerate(...)``
    is reading the row as an id -- true only while the level stores its
    objects densely from zero, and silently wrong otherwise.
    """
    manifests = read_all_object_manifests(level_group)
    ids = object_ids_for_rows(level_group)
    if ids.size != len(manifests):
        # A table that disagrees with the rows it describes cannot be
        # used to name them; fall back to positional, which is what the
        # store meant before the table existed.
        ids = np.arange(len(manifests), dtype=np.int64)
    return ids, manifests


def read_object_manifests(
    level_group: Group,
    *,
    ids: Sequence[int] | None = None,
) -> dict[int, ObjectManifest]:
    """Read the manifests of specific objects.

    ``read_all_object_manifests`` decodes every manifest in the store,
    which is the step that hangs on a large one: at twenty-one million
    objects it materialises and decodes twenty-one million Python
    manifests even when the caller needs a hundred.  Naming the ids turns
    that into one coordinate selection.

    Downstream had to reach for the private ``_expand_blocks``, the
    ``OBJECT_INDEX_LAYOUT_V1`` sentinel and a raw
    ``zarr_group[...].get_coordinate_selection`` to do this, which means
    a consumer pinned to three internals purely to avoid an O(N) decode.

    Args:
        level_group: Resolution level group.
        ids: Object ids to read.  ``None`` reads them all, which is the
            same work as ``read_all_object_manifests`` and is offered so
            a caller need not branch.

    Returns:
        ``{object_id: [(chunk_coords, fragment_index), ...]}``.  Ids that
        do not exist are simply absent, so a caller can pass a superset
        without pre-filtering.
    """
    meta = level_group.read_array_meta(OBJECT_INDEX)
    sid_ndim = meta["sid_ndim"]
    num_objects = int(meta.get("num_objects", 0))
    _require_object_index_layout(meta)
    if num_objects == 0:
        return {}

    from zarr_vectors.core import dense_manifests as dense

    if dense.is_dense(level_group, meta):
        if ids is None:
            rows = None
            wanted = object_ids_for_rows(level_group).tolist()
        else:
            found, rows = object_rows_for_ids(level_group, list(ids))
            if found.size == 0:
                return {}
            wanted = found.tolist()
        manifests = dense.manifests_from_csr(*dense.read_csr(level_group, rows))
        return dict(zip(wanted, manifests))
    path = f"{OBJECT_INDEX}/manifests"
    if ids is None:
        blobs = level_group.read_vlen_array(path)
        wanted = object_ids_for_rows(level_group).tolist()
    else:
        found, rows = object_rows_for_ids(level_group, list(ids))
        if found.size == 0:
            return {}
        # Ascending rows so the coordinate selection touches each zarr
        # chunk once; the result is keyed by id, so the order it was
        # asked in does not matter.
        order = np.argsort(rows, kind="stable")
        wanted = found[order].tolist()
        # One coordinate selection, not one request per id: the plural
        # read is the whole point, and it goes through the Group so it
        # stays serveable from an offline snapshot like every other read.
        blobs = level_group.read_vlen_elements(path, rows[order].tolist())

    return dict(zip(wanted, _decode_manifests(blobs, sid_ndim)))


def read_object_manifests_csr(
    level_group: Group, ids: Sequence[int],
) -> ManifestCSR:
    """The manifests of the objects ``ids``, as a :class:`ManifestCSR`.

    Row ``o`` is the ``o``-th id found, in the order asked; unknown ids are
    left out, as in :func:`read_object_manifests`.
    """
    meta = level_group.read_array_meta(OBJECT_INDEX)
    _require_object_index_layout(meta)
    sid_ndim = int(meta["sid_ndim"])
    found, rows = object_rows_for_ids(level_group, ids)
    if found.size == 0:
        return ManifestCSR(
            np.zeros(1, np.int64), np.empty((0, sid_ndim), np.int64),
            np.empty(0, np.int64), found,
        )

    from zarr_vectors.core import dense_manifests as dense

    if dense.is_dense(level_group, meta):
        offsets, coords, frags = dense.read_csr(level_group, rows)
        return ManifestCSR(offsets, coords, frags, found)
    # Ascending rows, so the coordinate selection touches each zarr chunk
    # once; then back to the order asked.
    order = np.argsort(rows, kind="stable")
    blobs = level_group.read_vlen_elements(
        f"{OBJECT_INDEX}/manifests", rows[order].tolist(),
    )
    asked = np.empty(len(blobs), dtype=object)
    asked[order] = blobs
    offsets, coords, frags = decode_object_manifests_csr(list(asked), sid_ndim)
    return ManifestCSR(offsets, coords, frags, found)


def read_object_id_table(level_group: Group) -> npt.NDArray[np.int64] | None:
    """Row → object id, or ``None`` when rows *are* ids.

    ``None`` is the V1 answer and means the identity mapping.  Callers
    should branch on it rather than materialising ``arange(n)``, which
    on a large level is the allocation the table exists to avoid.
    """
    try:
        meta = level_group.read_array_meta(OBJECT_INDEX)
    except Exception:
        return None
    if meta.get("layout") not in (OBJECT_INDEX_LAYOUT_V2, _LAYOUT_DENSE):
        return None
    try:
        table = level_group.read_array(f"{OBJECT_INDEX}/{OBJECT_IDS_ARRAY}")
    except Exception:
        return None
    return np.asarray(table, dtype=np.int64)


#: Id-table rows read per piece when a lookup proves the table is the
#: identity, or a commit checks the ids it commits.
_ID_SCAN_ROWS = 1 << 20


def _id_table_pieces(node: Any, lo: int, hi: int) -> Any:
    """``node[lo:hi]`` as int64 pieces of at most :data:`_ID_SCAN_ROWS`."""
    for a in range(lo, hi, _ID_SCAN_ROWS):
        b = min(a + _ID_SCAN_ROWS, hi)
        yield a, np.asarray(node[a:b], dtype=np.int64)


def _id_table_is_identity(level_group: Group, meta: dict[str, Any], node: Any) -> bool:
    """Whether the id table holds exactly ``0 .. len - 1``, row for row.

    With the sorted stamp, two ids prove it for the stamped rows --
    strictly increasing integers from 0 to ``m - 1`` in ``m`` rows can
    only be ``0 .. m - 1`` -- and only the rows past the committed count,
    which a commit's stamp does not speak for, are read. Without it, the
    table is read in pieces, stopping at the first that is not the
    identity, so a table that is never needs more than one piece of
    memory.
    """
    n = int(node.shape[0])
    if n == 0:
        return True
    if meta.get(OBJECT_IDS_SORTED_ATTR):
        committed = meta.get("num_objects")
        m = n if committed is None else max(0, min(int(committed), n))
        if m:
            from zarr_vectors.core._batch_reader import direct_elements

            ends = direct_elements(node, [0, m - 1])
            if ends is None:
                ends = (node[0], node[m - 1])
            if int(ends[0]) != 0 or int(ends[1]) != m - 1:
                return False
        lo = m
    else:
        lo = 0
    for a, piece in _id_table_pieces(node, lo, n):
        if not np.array_equal(piece, np.arange(a, a + piece.size, dtype=np.int64)):
            return False
    return True


def _object_id_lookup(level_group: Group) -> tuple[Any, ...] | None:
    """How ids resolve to rows: ``None`` (V1 identity), ``("identity", n)`` (proved
    without loading the table), ``("sorted", table)`` or ``("permuted", sorted_ids, rows)``.
    """
    cache = level_group._object_id_lookup_cache
    key = level_group._full_path(OBJECT_INDEX)
    if cache is not None and key in cache:
        return cache[key]
    result: tuple[Any, ...] | None = None
    try:
        meta = level_group.read_array_meta(OBJECT_INDEX)
    except Exception:
        meta = {}
    node = None
    if level_group._offline is None and (meta or {}).get("layout") in (
        OBJECT_INDEX_LAYOUT_V2, _LAYOUT_DENSE,
    ):
        try:
            node = level_group._require_array_node(f"{OBJECT_INDEX}/{OBJECT_IDS_ARRAY}")
        except Exception:
            node = None
    if node is not None and _id_table_is_identity(level_group, meta, node):
        result = ("identity", int(node.shape[0]))
    else:
        table = read_object_id_table(level_group)
        if table is not None:
            if meta.get(OBJECT_IDS_SORTED_ATTR):
                result = ("sorted", table)
            else:
                order = np.argsort(table, kind="stable")
                result = ("permuted", table[order], order)
    if cache is None:
        cache = level_group._object_id_lookup_cache = {}
    cache[key] = result
    return result


def object_rows_for_ids(
    level_group: Group, ids: Sequence[int],
) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]:
    """Resolve object ids to rows, dropping ids the level does not hold.

    Returns ``(found_ids, rows)`` in the order given.  An id that is
    absent is simply not returned, which is the same contract
    :func:`read_object_manifests` already offers for an out-of-range id,
    so a caller may pass a superset without pre-filtering.
    """
    # An array stays an array: list() of 1.45M numpy ints is 1.45M
    # Python objects, built only to be converted straight back.
    wanted = (
        ids.astype(np.int64, copy=False).reshape(-1) if isinstance(ids, np.ndarray)
        else np.asarray(list(ids), dtype=np.int64)
    )
    if wanted.size == 0:
        return wanted, wanted
    lookup = _object_id_lookup(level_group)
    if lookup is None or lookup[0] == "identity":
        # Identity: the id is the row, bounded by the row count (V1) or
        # by the table's length (a stored identity table).
        n_rows = object_row_count(level_group) if lookup is None else int(lookup[1])
        keep = (wanted >= 0) & (wanted < n_rows)
        return wanted[keep], wanted[keep]
    if lookup[0] == "sorted":
        sorted_ids, rows = lookup[1], None
    else:
        sorted_ids, rows = lookup[1], lookup[2]
    pos = np.searchsorted(sorted_ids, wanted)
    np.clip(pos, 0, max(sorted_ids.size - 1, 0), out=pos)
    hit = sorted_ids.size > 0
    found = (sorted_ids[pos] == wanted) if hit else np.zeros_like(wanted, bool)
    return wanted[found], (pos[found] if rows is None else rows[pos[found]])


def object_ids_for_rows(
    level_group: Group, rows: Sequence[int] | npt.NDArray[np.int64] | None = None,
) -> npt.NDArray[np.int64]:
    """The object ids at ``rows``, or every id in row order.

    The inverse of :func:`object_rows_for_ids`, and what a caller
    scanning manifests positionally needs in order to say which object
    each row belongs to.
    """
    if rows is not None:
        lookup = _object_id_lookup(level_group)
        if lookup is not None and lookup[0] == "identity":
            # The table is its rows: index it without reading it, as
            # numpy would index it (negative from the end, past it raises).
            n = int(lookup[1])
            r = np.asarray(list(rows), dtype=np.int64)
            bad = (r >= n) | (r < -n)
            if bad.any():
                raise IndexError(
                    f"index {int(r[bad][0])} is out of bounds for axis 0 with size {n}"
                )
            return np.where(r < 0, r + n, r)
    table = read_object_id_table(level_group)
    if table is None:
        n_rows = object_row_count(level_group)
        return (
            np.arange(n_rows, dtype=np.int64) if rows is None
            else np.asarray(list(rows), dtype=np.int64)
        )
    return table if rows is None else table[np.asarray(list(rows), dtype=np.int64)]


def object_row_count(level_group: Group) -> int:
    """How many manifest rows this level holds."""
    try:
        meta = level_group.read_array_meta(OBJECT_INDEX)
    except Exception:
        return 0
    return int(meta.get("num_objects", 0) or 0)


def object_count(level_group: Group) -> int:
    """How many objects this level declares, without decoding any of them."""
    try:
        meta = level_group.read_array_meta(OBJECT_INDEX)
    except Exception:
        return 0
    return int(meta.get("num_objects", 0) or 0)


def object_present_mask(level_group: Group) -> npt.NDArray[np.bool_]:
    """Per-slot mask of which objects this level actually holds.

    ``True`` where the slot has a non-empty manifest.

    Answered from the stored bytes rather than from decoded manifests.
    A manifest encodes as a block count followed by its blocks, so an
    empty one is exactly the four zero bytes of a zero count and the
    question "is this slot occupied" is a byte comparison.  Decoding
    first -- building every chunk-coordinate tuple of every object in
    the level -- answered the same question and then threw the answer
    away: on a 400,000-object store the decode was about 80% of the
    time this function took.
    """
    meta = level_group.read_array_meta(OBJECT_INDEX)
    _require_object_index_layout(meta)
    if int(meta.get("num_objects", 0)) == 0:
        return np.zeros((0,), dtype=bool)
    from zarr_vectors.core import dense_manifests as dense

    if dense.is_dense(level_group, meta):
        return dense.present_mask(level_group)
    blobs = level_group.read_vlen_array(f"{OBJECT_INDEX}/manifests")
    # A never-written row reads back empty, which is absent too.
    return np.array(
        [bool(b) and bytes(b) != _EMPTY_MANIFEST_BLOB for b in blobs],
        dtype=bool,
    )


def object_present_count(level_group: Group) -> int:
    """How many objects this level actually holds, not how many slots.

    Prefers the stamped ``num_present``; falls back to decoding the
    manifests for a store written before it existed, so the answer is
    correct either way and only the cost differs.
    """
    try:
        meta = level_group.read_array_meta(OBJECT_INDEX)
    except Exception:
        return 0
    stamped = meta.get("num_present")
    if stamped is not None:
        return int(stamped)
    return int(object_present_mask(level_group).sum())


def _require_object_index_layout(meta: dict[str, Any]) -> None:
    """Raise unless ``object_index`` is a layout this build can read.

    Both V1 and V2 are readable, and they share one code path: a V1
    store is one whose id table is the identity.  Anything else is older
    than this build supports.
    """
    layout = meta.get("layout")
    if layout in (OBJECT_INDEX_LAYOUT_V1, OBJECT_INDEX_LAYOUT_V2, _LAYOUT_DENSE):
        return
    _require_object_index_v1(meta)


def _require_object_index_v1(meta: dict[str, Any]) -> None:
    """Raise if ``object_index`` is in none of the readable layouts (V1, V2,
    dense; see :func:`_require_object_index_layout`)."""
    layout = meta.get("layout")
    if layout != OBJECT_INDEX_LAYOUT_V1:
        raise ArrayError(
            f"object_index layout {layout!r} is not readable by this build "
            f"(readable: {OBJECT_INDEX_LAYOUT_V1!r}, "
            f"{OBJECT_INDEX_LAYOUT_V2!r}, {_LAYOUT_DENSE!r}) — rewrite the "
            f"store from source."
        )


def expand_manifest_blocks(
    blocks: list[tuple[ChunkCoords, Any]],
) -> ObjectManifest:
    """Expand v0.6 manifest blocks to the legacy
    ``[(chunk_coords, fragment_index), ...]`` tuple list.

    Mode-1 (range) and mode-2 (explicit list) blocks expand to one
    tuple per fragment so existing call sites that iterate
    ``(chunk_coords, fragment_index)`` keep working unchanged.  Callers that
    want the raw block representation can use
    :func:`zarr_vectors.encoding.fragments.decode_object_manifest_blocks`
    directly.
    """
    out: ObjectManifest = []
    for chunk_coords, frag_ref in blocks:
        if isinstance(frag_ref, int):
            out.append((chunk_coords, int(frag_ref)))
        elif isinstance(frag_ref, tuple):
            r_start, r_count = frag_ref
            for k in range(int(r_count)):
                out.append((chunk_coords, int(r_start) + k))
        else:
            # np.ndarray of explicit indices
            for idx in frag_ref:
                out.append((chunk_coords, int(idx)))
    return out


def read_object_vertices(
    level_group: Group,
    object_id: int,
    dtype: np.dtype | str = np.float32,
    ndim: int = 3,
) -> list[npt.NDArray[np.floating]]:
    """Read all vertex data for an object by following its manifest.

    Args:
        level_group: Resolution level group.
        object_id: Object ID.
        dtype: Numpy dtype.
        ndim: Number of coordinate dimensions.

    Returns:
        List of fragment arrays in reconstruction order.
    """
    manifest = read_object_manifest(level_group, object_id)
    if not manifest:
        return []

    # Prefetch every chunk this object touches in one async gather, so
    # the per-fragment read_fragment calls below hit the cache
    # instead of paying one round-trip per fragment.  Distinct chunks
    # appear once in the plan; multiple fragments inside the same chunk
    # share the same cache entry.
    chunk_keys = sorted({_chunk_key(cc) for cc, _ in manifest})
    with _maybe_batched_reads(level_group, [
        (VERTICES, chunk_keys),
        (VERTEX_FRAGMENTS, chunk_keys),
    ]):
        groups: list[npt.NDArray] = []
        for chunk_coords, fragment_index in manifest:
            fragment = read_fragment(
                level_group, chunk_coords, fragment_index,
                dtype=dtype, ndim=ndim,
            )
            groups.append(fragment)
    return groups


def read_object_attributes(
    level_group: Group,
    attr_name: str,
    dtype: np.dtype | str | None = None,
) -> npt.NDArray:
    """Read dense O×C object attribute data.

    Returns the raw array values, including any sentinel positions for
    absent rows.  Use :func:`read_object_attribute_present_mask` to
    reconstruct a 0/1 mask, or compare directly against
    ``level_group.read_array_fill_value(...)``.

    Args:
        level_group: Resolution level group.
        attr_name: Attribute name.
        dtype: Optional override applied via ``astype`` after read.

    Returns:
        Array of shape ``(O,)`` or ``(O, C)``.
    """
    full_name = f"{OBJECT_ATTRIBUTES}/{attr_name}"
    out = level_group.read_array(full_name)
    if dtype is not None:
        out = out.astype(np.dtype(dtype), copy=False)
    return out


def read_group_object_ids(
    level_group: Group,
    group_id: int,
) -> Sequence[int]:
    """Read the object IDs belonging to a group.

    Args:
        level_group: Resolution level group.
        group_id: Group ID.

    Returns:
        The member object IDs.  A group written from a ``range`` (see
        :func:`write_groupings`) is returned as a ``range`` — O(1) rather
        than materialising up to a billion ints.  Explicit groups are
        returned as a ``list[int]``.  Both support ``len()``, indexing
        and iteration.
    """
    blobs = level_group.read_vlen_array(GROUPS)
    if group_id < 0 or group_id >= len(blobs):
        raise ArrayError(
            f"Group ID {group_id} out of range [0, {len(blobs)})"
        )
    group_ranges = level_group.read_array_meta(GROUPS).get("group_ranges", {})
    rng = group_ranges.get(str(group_id))
    if rng is not None:
        return range(int(rng[0]), int(rng[1]))
    return np.frombuffer(blobs[group_id], dtype=np.int64).tolist()


def read_all_groupings(
    level_group: Group,
) -> list[Sequence[int]]:
    """Read all group memberships.

    Returns:
        List indexed by group_id.  Each entry is a ``list[int]`` for an
        explicit group, or a ``range`` for an implicitly-stored contiguous
        group (see :func:`write_groupings`).
    """
    blobs = level_group.read_vlen_array(GROUPS)
    group_ranges = level_group.read_array_meta(GROUPS).get("group_ranges", {})
    out: list[Sequence[int]] = []
    for gid, b in enumerate(blobs):
        rng = group_ranges.get(str(gid))
        if rng is not None:
            out.append(range(int(rng[0]), int(rng[1])))
        else:
            out.append(np.frombuffer(b, dtype=np.int64).tolist())
    return out




def read_groupings_attributes(
    level_group: Group,
    attr_name: str,
    dtype: np.dtype | str | None = None,
) -> npt.NDArray:
    """Read dense G×C groupings attribute data."""
    full_name = f"{GROUP_ATTRIBUTES}/{attr_name}"
    out = level_group.read_array(full_name)
    if dtype is not None:
        out = out.astype(np.dtype(dtype), copy=False)
    return out


def cell_endpoint_chunks(
    src: ChunkCoords,
    offsets: Sequence[ChunkCoords],
    scale_src: Sequence[int],
    scale_trg: Sequence[int],
) -> tuple[ChunkCoords, ...]:
    """Reconstruct a cell's L endpoint chunks from its source and offsets.

    The inverse of the placement arithmetic in
    :func:`~zarr_vectors.spatial.boundary.partition_records_by_offset`:
    endpoint 0 *is* the source (its offset is the implicit zero and is
    never encoded), and endpoint k>0 is ``anchor(src) + o_k``.  The
    anchor makes this exact across levels whose chunk grids differ; it
    is the identity when they do not.
    """
    from zarr_vectors.spatial.boundary import anchor_chunk

    anchor = anchor_chunk(src, scale_src, scale_trg)
    return (tuple(src),) + tuple(
        tuple(int(a) + int(o) for a, o in zip(anchor, off)) for off in offsets
    )


def _link_cell_rows(
    blob: bytes, *, ncols: int, flat: bool, dtype: np.dtype | str = np.int64,
) -> npt.NDArray[np.int64]:
    """Decode one link cell's bytes into its ``(M, ncols)`` physical rows.

    The single decode :func:`read_links` and :func:`read_links_for_tuple`
    share, so a whole-family read and a single-cell read of the same bytes
    cannot disagree.  ``flat`` selects the branch
    :func:`write_chunk_links` wrote under (``delta == 0 and
    is_intra(offsets)``) — the two encodings are not interchangeable.

    ``dtype`` is the *cell's own* declared element type, which
    :func:`write_chunk_links` stamped onto the array and which a caller
    reads back off ``read_array_meta``.  It is not always int64: an
    int32-declared array (a downstream pipeline stamps its per-chunk node graph int32 via
    ``create_node_graph_array``) holds half as many bytes per element, so
    decoding it at a fixed int64 yields a quarter of the rows on an even
    element count and raises ``cannot reshape array of size N`` on an odd
    one.  :func:`iter_link_cells` already honours the stamp; this is the
    same rule, so the two readers agree on the same bytes.  The fallback
    stays int64 for arrays written before the dtype was stamped.

    Rows come back in write order: groups in append order, rows in order
    within each group.  That matches the enumeration
    :func:`iter_link_cells` counts against.  Values are widened to int64 on
    return regardless of the on-disk width, so callers see one row type.

    NOTE :func:`~zarr_vectors.encoding.ragged.decode_ragged_blob` yields
    one entry per *group* — an ``(M_k, ncols)`` block — not one per row.
    A whole-family write files a cell's rows as a single group and each
    append adds another, so the groups must be concatenated; treating the
    group count as a row count mis-parses every multi-record cell.
    """
    cell_dtype = np.dtype(dtype)
    if flat:
        # Intra-chunk at delta 0: flat concatenation, group bounds in the
        # link_fragments sidecar.  A cell-wide read wants every row, so
        # the sidecar is not consulted.
        return (
            np.frombuffer(blob, dtype=cell_dtype)
            .reshape(-1, ncols)
            .astype(np.int64, copy=False)
        )
    groups = decode_ragged_blob(blob, cell_dtype, ncols=ncols)
    if not groups:
        return np.empty((0, ncols), dtype=np.int64)
    return np.concatenate(
        [np.asarray(g, dtype=np.int64).reshape(-1, ncols) for g in groups],
        axis=0,
    )


def read_links(
    level_group: Group,
    *,
    delta: int = 0,
    include_intra: bool = True,
    select: Sequence[int] | npt.NDArray[np.integer] | None = None,
) -> list[tuple[tuple[ChunkCoords, int], ...]]:
    """Read every link record under ``links/<delta>/``.

    The whole-family counterpart to :func:`write_links`, and the inverse
    of its placement: each cell's source chunk plus the array's offsets
    segment reconstruct the record's endpoint chunks, and ``perm_idx``
    (where present) reverses the canonical sort — so callers see the same
    record shape they wrote.  Intra-chunk links are included by default;
    they are the all-zero-offsets array, not a separate family.

    Records are returned in **(offsets segment, cell) sorted order**, and
    within a cell in write order.  :func:`read_link_attributes`
    enumerates identically — that shared order is the only thing aligning
    attribute rows to link records, so the two must not drift.

    For a ``store="duplicate"`` family each logical record was filed in
    several cells, so it is returned **once per copy** — dedupe, or query
    a single location with :func:`read_links_for_tuple`.

    Args:
        level_group: Resolution level group.
        delta: Level delta.
        include_intra: When False, skip the all-zero-offsets array — the
            per-chunk intra links — and return only records that cross
            chunks.  A producer that keeps two populations in the one
            merged family (a per-chunk graph plus boundary crossings)
            wants only the second, and writes its attributes from that
            path alone: the attribute family then holds exactly the
            non-intra segments, so ``include_intra=False`` is what
            restores row-for-row alignment with
            :func:`read_link_attributes`.
        select: Sorted row indices to materialise, numbered over the rows
            this call *returns* — so ``select=[i]`` names the same record
            as ``read_links(...)[i]`` under the same ``include_intra``.
            The arrays are decoded either way; what this skips is the
            per-record Python tuple construction, which is the whole cost
            of a large family (tens of millions of records take minutes
            to build, and a caller sampling a handful of them was paying
            all of it).  ``None`` returns every record.

    Returns ``[]`` when the ``<delta>`` family is absent or empty.

    Raises:
        ArrayError: If ``select`` is not sorted ascending.
    """
    sel: npt.NDArray[np.int64] | None = None
    if select is not None:
        sel = np.asarray(select, dtype=np.int64).ravel()
        if sel.size > 1 and bool(np.any(np.diff(sel) < 0)):
            raise ArrayError(
                "select must be sorted ascending: row indices are matched "
                "against a running count, so an unsorted list silently "
                "returns the wrong records"
            )
    family = links_group_path(delta)
    if not level_group.array_exists(family):
        return []
    fam_meta = level_group.read_array_meta(family) or {}
    if "link_width" not in fam_meta or "sid_ndim" not in fam_meta:
        return []
    link_width = int(fam_meta["link_width"])
    sid_ndim = int(fam_meta["sid_ndim"])
    directed = bool(fam_meta.get("directed", False))
    store = str(fam_meta.get("store", "canonical"))

    from zarr_vectors.spatial.boundary import apply_perm_inverse

    # Must be _link_scales, not _derive_level_scales: the latter derives
    # its rank from the root chunk_shape, but an attribute-binned store
    # prepends a bin axis to every chunk key, so the scales need padding
    # to sid_ndim.  The write path anchors through _link_scales — reading
    # with a differently-ranked scale would silently anchor elsewhere.
    scale_src, scale_trg = _link_scales(level_group, delta, sid_ndim)

    # Two passes, as read_link_arrays does: every segment's layout and
    # cells first, then one batched prefetch of all of them rather than a
    # read per cell -- on an object store, one round trip instead of one
    # per cell.
    segments: list[tuple[Any, ...]] = []
    for seg in list_link_offsets(level_group, delta):
        arr_name = f"{family}/{seg}"
        try:
            offsets = parse_offsets(
                seg, sid_ndim=sid_ndim, link_width=link_width,
            )
        except ValueError as e:
            raise ArrayError(
                f"{arr_name}: offsets segment {seg!r} does not match the "
                f"family's sid_ndim={sid_ndim} link_width={link_width}: {e}"
            ) from e
        if not include_intra and is_intra(offsets):
            # Skipped before the rows are counted, so ``select`` numbers the
            # returned population and not the one on disk.
            continue
        arr_meta = level_group.read_array_meta(arr_name) or {}
        # Trust the stored width; fall back to recomputing it from the
        # family policy for an array written before it was stamped.
        # Guessing here would silently mis-parse every row in the cell.
        has_perm = bool(arr_meta.get(
            "has_perm",
            links_has_perm(
                offsets, delta=delta, directed=directed, store=store,
            ),
        ))
        ncols = (1 + link_width) if has_perm else link_width
        flat = delta == 0 and is_intra(offsets)
        # Per-ARRAY, not per-family: each offsets segment carries its own
        # element width (a downstream pipeline's intra node graph is int32 while its seam
        # segments are int64), so this must be read inside the segment loop.
        cell_dtype = np.dtype(arr_meta.get("dtype", "int64"))
        segments.append((
            arr_name, offsets, has_perm, ncols, flat, cell_dtype,
            sorted(level_group.list_chunks(arr_name)),
        ))

    with _maybe_batched_reads(level_group, [
        (seg_info[0], seg_info[6]) for seg_info in segments if seg_info[6]
    ]):
        segment_blobs = [
            [level_group.read_bytes(seg_info[0], k) for k in seg_info[6]]
            for seg_info in segments
        ]

    out: list[tuple[tuple[ChunkCoords, int], ...]] = []
    base = 0  # index of the next row this call returns, for ``select``
    for (arr_name, offsets, has_perm, ncols, flat, cell_dtype, cell_keys), blobs in zip(
        segments, segment_blobs,
    ):
        chunks_cache: dict[ChunkCoords, tuple[ChunkCoords, ...]] = {}
        for cell_key, blob in zip(cell_keys, blobs):
            if not blob:
                continue
            src = _parse_chunk_key(cell_key)
            rows_arr = _link_cell_rows(
                blob, ncols=ncols, flat=flat, dtype=cell_dtype,
            )
            if rows_arr.size == 0:
                continue

            if sel is not None:
                # Subset before the .tolist() below: the numpy gather is
                # what makes ``select`` cheap, so it has to happen while
                # the rows are still an array.
                row_base, base = base, base + rows_arr.shape[0]
                lo = int(np.searchsorted(sel, row_base, side="left"))
                hi = int(np.searchsorted(sel, base, side="left"))
                if hi <= lo:
                    continue
                rows_arr = rows_arr[sel[lo:hi] - row_base]

            if src not in chunks_cache:
                chunks_cache[src] = cell_endpoint_chunks(
                    src, offsets, scale_src, scale_trg,
                )
            chunks = chunks_cache[src]

            if has_perm:
                perm_list = rows_arr[:, 0].tolist()
                vi_list = rows_arr[:, 1:1 + link_width].tolist()
            else:
                # Identity placement only: rows are already input order.
                perm_list = None
                vi_list = rows_arr[:, :link_width].tolist()

            if perm_list is None:
                for vis in vi_list:
                    out.append(tuple(zip(chunks, vis)))
            elif link_width == 2:
                # The only 2-endpoint perms are identity (0) and swap (1);
                # avoid the per-row Lehmer decode in apply_perm_inverse.
                cc0, cc1 = chunks[0], chunks[1]
                for perm_idx, (v0, v1) in zip(perm_list, vi_list):
                    ep0 = (cc0, v0)
                    ep1 = (cc1, v1)
                    out.append((ep0, ep1) if perm_idx == 0 else (ep1, ep0))
            else:
                for perm_idx, vi_placed in zip(perm_list, vi_list):
                    placed_endpoints = list(zip(chunks, vi_placed))
                    out.append(tuple(apply_perm_inverse(
                        placed_endpoints, perm_idx, link_width,
                    )))
    return out


def link_cells_within(
    level_group: Group,
    within: Iterable[ChunkCoords],
    *,
    delta: int = 0,
    touching: bool = False,
) -> dict[str, list[str]]:
    """The cells of ``links/<delta>/`` whose records lie wholly in ``within``.

    A reader scoped to some chunks -- a bbox, a ``chunks=`` whitelist,
    the chunks one object's manifest names -- keeps a record only if
    every endpoint is in a chunk it read, so a cell is worth fetching
    only when *all* of its endpoint chunks are in ``within``.  Which
    cells those are follows from the cell's source chunk and its
    offsets segment alone (:func:`cell_endpoint_chunks`), so the answer
    costs no reads beyond the family listing and the presence manifest
    of each segment that survives.

    Without this a scoped read had nothing to go on but the whole
    family: one mesh patch at 10^6 vertices read every face in the level
    and spent 2.5 s of a 2.6 s read deduplicating their endpoints, to
    keep 242 of them.

    Args:
        level_group: Resolution level group.
        within: Chunk coordinates, in the family's ``sid_ndim`` arity.
        delta: Level delta.  Only ``0``: a cross-level record's endpoints
            sit on two different chunk grids, and one set of chunk
            coordinates cannot scope both.
        touching: Keep a cell when *any* of its endpoint chunks is in
            ``within``, not all of them.  A skeleton reader needs this:
            a record whose child was read but whose parent was not is
            what tells it the child is a root there, and without the
            record the child silently inherits its fragment predecessor
            as parent.  The source of such a cell may lie outside
            ``within`` (canonical placement files a record under its
            lowest endpoint chunk), so candidates are ``within`` shifted
            back by each offset.

    Returns:
        ``{offsets_segment: [cell_key, ...]}`` naming only cells that are
        present, cell keys sorted as :func:`read_link_arrays` visits
        them.  Pass it to ``read_link_arrays(cells=...)`` and use it to
        build the prefetch plan, so the two agree on what is read.
    """
    if delta != 0:
        raise ArrayError(
            f"link_cells_within supports delta=0 only, got delta={delta}: "
            "cross-level endpoints are not on the grid `within` is in"
        )
    family = links_group_path(delta)
    if not level_group.array_exists(family):
        return {}
    fam_meta = level_group.read_array_meta(family) or {}
    if "link_width" not in fam_meta or "sid_ndim" not in fam_meta:
        return {}
    link_width = int(fam_meta["link_width"])
    sid_ndim = int(fam_meta["sid_ndim"])

    src = np.asarray(
        sorted({tuple(int(c) for c in cc) for cc in within}), dtype=np.int64,
    ).reshape(-1, sid_ndim)
    if src.shape[0] == 0:
        return {}
    # Membership as a 1-D isin over raveled coords: no Python object per
    # chunk, and no dense table over a bounding box that two far-apart
    # chunks would make arbitrarily large.
    lo = src.min(axis=0)
    ext = src.max(axis=0) - lo + 1
    src_keys = np.ravel_multi_index((src - lo).T, ext)
    # A handful of chunks is tested as tuples against a set: the array
    # form below has a fixed numpy cost per segment.
    few = src.shape[0] <= _LINK_CELLS_SET_MAX
    src_rows = [tuple(c) for c in src.tolist()] if few else []
    src_set = set(src_rows)

    out: dict[str, list[str]] = {}
    for seg in list_link_offsets(level_group, delta):
        try:
            offsets = parse_offsets(seg, sid_ndim=sid_ndim, link_width=link_width)
        except ValueError as e:
            raise ArrayError(
                f"{family}/{seg}: offsets segment {seg!r} does not match the "
                f"family's sid_ndim={sid_ndim} link_width={link_width}: {e}"
            ) from e
        # Endpoint 0 is the source itself; at delta 0 the anchor is the
        # identity, so endpoint k is ``src + o_k``.
        if touching:
            # A source whose endpoint k lands in ``within`` is ``w - o_k``
            # for some w in it; every such source touches by construction.
            cand = np.unique(np.concatenate(
                [src] + [src - np.asarray(off, dtype=np.int64)
                         for off in offsets if any(off)],
                axis=0,
            ), axis=0)
            seg_path = f"{family}/{seg}"
            present = set(level_group.list_chunks(seg_path))
            keys = sorted(
                k for k in (_chunk_key(tuple(c)) for c in cand.tolist())
                if k in present
            )
            if keys:
                out[seg] = keys
            continue
        shifts = [off for off in offsets if any(off)]
        if few:
            ok = np.fromiter(
                (
                    all(
                        tuple(a + b for a, b in zip(c, off)) in src_set
                        for off in shifts
                    )
                    for c in src_rows
                ),
                dtype=bool, count=len(src_rows),
            )
        else:
            ok = np.ones(src.shape[0], dtype=bool)
            for off in shifts:
                rel = src + np.asarray(off, dtype=np.int64) - lo
                inside = np.all((rel >= 0) & (rel < ext), axis=1)
                keys = np.ravel_multi_index(
                    np.where(inside[:, None], rel, 0).T, ext,
                )
                ok &= inside & np.isin(keys, src_keys)
                if not ok.any():
                    break
        if not ok.any():
            continue
        seg_path = f"{family}/{seg}"
        present = set(level_group.list_chunks(seg_path))
        keys = sorted(
            k for k in (_chunk_key(tuple(c)) for c in src[ok].tolist())
            if k in present
        )
        if keys:
            out[seg] = keys
    return out


#: Most chunks :func:`link_cells_within` tests as Python tuples rather
#: than arrays.
_LINK_CELLS_SET_MAX = 256


def _perm_inverse_table(link_width: int) -> npt.NDArray[np.int64]:
    """``inverse[p]`` gathers a row placed under ``perm_idx`` ``p`` back
    into input order: the ``out[sigma[i]] = placed[i]`` of
    apply_perm_inverse, as one index per permutation."""
    import math

    from zarr_vectors.spatial.boundary import _lehmer_decode

    return np.stack([
        np.argsort(_lehmer_decode(p, link_width))
        for p in range(math.factorial(link_width))
    ]).astype(np.int64)


def _link_segment_blobs(
    level_group: Group,
    delta: int,
    *,
    include_intra: bool,
    cells: Mapping[str, Sequence[str]] | None,
    link_fragments: Mapping[str, Sequence[int]] | None,
) -> tuple[
    int, int, tuple[int, ...], tuple[int, ...],
    list[tuple[tuple[Any, ...], list[tuple[str, bytes | None]]]],
] | None:
    """``(link_width, sid_ndim, scale_src, scale_trg, segment_rows)`` for a
    link read (each row ``(seg_info, [(cell_key, blob)])``, ``blob`` None
    for a ranged cell), or ``None`` when the family has no layout."""
    family = links_group_path(delta)
    if not level_group.array_exists(family):
        return None
    fam_meta = level_group.read_array_meta(family) or {}
    if "link_width" not in fam_meta or "sid_ndim" not in fam_meta:
        return None
    link_width = int(fam_meta["link_width"])
    sid_ndim = int(fam_meta["sid_ndim"])
    directed = bool(fam_meta.get("directed", False))
    store = str(fam_meta.get("store", "canonical"))
    # Same-level anchoring is identity at any chunk scale. Reading the root
    # again to derive two equal scales adds metadata I/O but no information.
    if delta == 0:
        scale_src = scale_trg = (1,) * sid_ndim
    else:
        scale_src, scale_trg = _link_scales(level_group, delta, sid_ndim)

    # Two passes: work out every segment's layout and cells first, so all
    # of them are fetched in one batched prefetch rather than one read
    # per cell -- on an object store, one round trip instead of one per
    # cell.  ``cells`` scopes both passes; a cell ``link_fragments``
    # narrows is range-read on its own instead, so it stays out of the
    # prefetch, which would fetch it whole.
    segments: list[tuple[Any, ...]] = []
    for seg in (
        list_link_offsets(level_group, delta) if cells is None else sorted(cells)
    ):
        arr_name = f"{family}/{seg}"
        try:
            offsets = parse_offsets(
                seg, sid_ndim=sid_ndim, link_width=link_width,
            )
        except ValueError as e:
            raise ArrayError(
                f"{arr_name}: offsets segment {seg!r} does not match the "
                f"family's sid_ndim={sid_ndim} link_width={link_width}: {e}"
            ) from e
        if not include_intra and is_intra(offsets):
            continue
        arr_meta = level_group.read_array_meta(arr_name) or {}
        has_perm = bool(arr_meta.get(
            "has_perm",
            links_has_perm(
                offsets, delta=delta, directed=directed, store=store,
            ),
        ))
        ncols = (1 + link_width) if has_perm else link_width
        flat = delta == 0 and is_intra(offsets)
        cell_dtype = np.dtype(arr_meta.get("dtype", "int64"))

        cell_keys = sorted(
            level_group.list_chunks(arr_name) if cells is None else cells[seg]
        )
        ranged = (
            {k for k in cell_keys if k in link_fragments}
            if flat and link_fragments is not None else set()
        )
        segments.append((
            arr_name, offsets, has_perm, ncols, flat, cell_dtype,
            cell_keys, ranged,
        ))

    with _maybe_batched_reads(level_group, [
        (seg_info[0], [k for k in seg_info[6] if k not in seg_info[7]])
        for seg_info in segments
        if any(k not in seg_info[7] for k in seg_info[6])
    ]):
        segment_rows = [
            (seg_info, [
                (cell_key, None if cell_key in seg_info[7]
                 else level_group.read_bytes(seg_info[0], cell_key))
                for cell_key in seg_info[6]
            ])
            for seg_info in segments
        ]
    return link_width, sid_ndim, scale_src, scale_trg, segment_rows


@_device_result
def read_link_arrays(
    level_group: Group,
    *,
    delta: int = 0,
    include_intra: bool = True,
    cells: Mapping[str, Sequence[str]] | None = None,
    link_fragments: Mapping[str, Sequence[int]] | None = None,
) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]:
    """Every link record under ``links/<delta>/`` as two arrays.

    :func:`read_links` in array form: ``(chunks, vi)`` of shapes
    ``(M, L, sid_ndim)`` and ``(M, L)``, one row per record in exactly
    the order :func:`read_links` returns them -- offsets segments
    sorted, cells sorted within each, rows in write order -- and with
    the input endpoint order restored from ``perm_idx``.  So
    ``read_links(...)[i]`` is ``tuple(zip(map(tuple, chunks[i]), vi[i]))``.

    Offered because the per-record tuples are the cost of a large
    family: half a million faces took 8 s to build as tuples and a
    further 2 s to take apart again, for arithmetic -- a chunk offset
    plus a local index -- that is one gather over these arrays.  A
    ``store="duplicate"`` family returns each record once per copy,
    like :func:`read_links`.

    ``cells`` restricts the read to ``{offsets_segment: [cell_key,
    ...]}`` -- typically :func:`link_cells_within` -- and is what lets a
    scoped reader touch only the cells its chunks can reach.  ``None``
    (the default) reads every cell of every segment.

    ``link_fragments`` narrows the intra-chunk cell at delta 0 further:
    ``{cell_key: [fragment, ...]}`` keeps only those link fragments of
    that cell, in the order given; cells it does not name are read whole.
    Only meaningful where the fragments partition the cell usefully --
    one per vertex fragment, on a level claiming
    ``link_fragments_aligned`` -- which is the caller's to check.

    Returns empty ``(0, 0, 0)`` / ``(0, 0)`` arrays when the family is
    absent or holds no rows.
    """
    empty = (np.empty((0, 0, 0), dtype=np.int64), np.empty((0, 0), dtype=np.int64))
    layout = _link_segment_blobs(
        level_group, delta, include_intra=include_intra, cells=cells,
        link_fragments=link_fragments,
    )
    if layout is None:
        return empty
    link_width, sid_ndim, scale_src, scale_trg, segment_rows = layout
    # inverse[p] gathers a placed row back into input order: the
    # ``out[sigma[i]] = placed[i]`` of apply_perm_inverse, as one index.
    inverse: npt.NDArray[np.int64] | None = None
    chunk_parts: list[npt.NDArray[np.int64]] = []
    vi_parts: list[npt.NDArray[np.int64]] = []
    for (
        arr_name,
        offsets,
        has_perm,
        ncols,
        flat,
        cell_dtype,
        _keys,
        ranged,
    ), blobs in segment_rows:
        cell_rows: list[npt.NDArray[np.int64]] = []
        cell_chunks: list[tuple[ChunkCoords, ...]] = []
        for cell_key, blob in blobs:
            if cell_key in ranged:
                rows_arr = _link_fragment_rows(
                    level_group, arr_name, cell_key, link_fragments[cell_key],
                    ncols=ncols, dtype=cell_dtype,
                )
            else:
                if not blob:
                    continue
                rows_arr = _link_cell_rows(
                    blob, ncols=ncols, flat=flat, dtype=cell_dtype,
                )
            if rows_arr.size == 0:
                continue
            cell_rows.append(rows_arr)
            cell_chunks.append(cell_endpoint_chunks(
                _parse_chunk_key(cell_key), offsets, scale_src, scale_trg,
            ))
        if not cell_rows:
            continue
        counts = np.fromiter((r.shape[0] for r in cell_rows), dtype=np.int64, count=len(cell_rows))
        rows = np.concatenate(cell_rows, axis=0)
        placed_chunks = np.repeat(
            np.asarray(cell_chunks, dtype=np.int64).reshape(-1, link_width, sid_ndim),
            counts, axis=0,
        )
        if has_perm:
            if inverse is None:
                inverse = _perm_inverse_table(link_width)
            perm = rows[:, 0]
            if perm.size and (int(perm.min()) < 0 or int(perm.max()) >= inverse.shape[0]):
                raise ArrayError(
                    f"{arr_name}: perm_idx out of range [0, {inverse.shape[0]})"
                )
            gather = inverse[perm]
            rowsel = np.arange(rows.shape[0])[:, None]
            vi_parts.append(rows[:, 1:1 + link_width][rowsel, gather])
            chunk_parts.append(placed_chunks[rowsel, gather])
        else:
            vi_parts.append(np.ascontiguousarray(rows[:, :link_width]))
            chunk_parts.append(placed_chunks)
    if not vi_parts:
        return empty
    return (
        np.concatenate(chunk_parts, axis=0),
        np.concatenate(vi_parts, axis=0),
    )


def read_link_rows(
    level_group: Group,
    row_maps: Mapping[ChunkCoords, npt.NDArray[np.int64]],
    *,
    delta: int = 0,
    cells: Mapping[str, Sequence[str]] | None = None,
    touching: bool = False,
) -> npt.NDArray[np.int64]:
    """Link records under ``links/<delta>/`` as output rows, ``(M, L)``.

    :func:`read_link_arrays` fused with a remap: endpoint ``(c, vi)``
    becomes ``row_maps[c][vi]``, and a record is kept only when every
    endpoint maps to a row ``>= 0`` (chunk in ``row_maps``, ``vi`` inside
    its map, not ``-1``).  Same order as :func:`read_link_arrays`.

    ``cells`` scopes the read as in :func:`read_link_arrays`.  With
    ``touching``, a record is kept when its first endpoint maps, and an
    unmapped endpoint comes back as ``-1``.  Returns ``(0, L)`` when no
    record survives, ``(0, 0)`` when the family is absent.
    """
    layout = _link_segment_blobs(
        level_group, delta, include_intra=True, cells=cells,
        link_fragments=None,
    )
    if layout is None:
        return np.empty((0, 0), dtype=np.int64)
    link_width, _sid_ndim, scale_src, scale_trg, segment_rows = layout
    inverse: npt.NDArray[np.int64] | None = None
    parts: list[npt.NDArray[np.int64]] = []
    for (
        arr_name,
        offsets,
        has_perm,
        ncols,
        flat,
        cell_dtype,
        _keys,
        _ranged,
    ), blobs in segment_rows:
        for cell_key, blob in blobs:
            if not blob:
                continue
            rows = _link_cell_rows(blob, ncols=ncols, flat=flat, dtype=cell_dtype)
            if rows.size == 0:
                continue
            if has_perm:
                if inverse is None:
                    inverse = _perm_inverse_table(link_width)
                perm = rows[:, 0]
                if int(perm.min()) < 0 or int(perm.max()) >= inverse.shape[0]:
                    raise ArrayError(
                        f"{arr_name}: perm_idx out of range [0, {inverse.shape[0]})"
                    )
            maps = [row_maps.get(c) for c in cell_endpoint_chunks(
                _parse_chunk_key(cell_key), offsets, scale_src, scale_trg,
            )]
            if not touching and any(m is None for m in maps):
                continue
            vi = rows[:, 1:] if has_perm else rows
            placed = np.empty((rows.shape[0], link_width), dtype=np.int64)
            for k, table in enumerate(maps):
                if table is None or not len(table):
                    placed[:, k] = -1
                    continue
                v = vi[:, k]
                inside = (v >= 0) & (v < len(table))
                if inside.all():
                    placed[:, k] = table[v]
                else:
                    placed[:, k] = np.where(inside, table[np.where(inside, v, 0)], -1)
            if has_perm and placed.shape[0]:
                placed = np.take_along_axis(placed, inverse[rows[:, 0]], axis=1)
            ok = placed[:, 0] >= 0 if touching else (placed >= 0).all(axis=1)
            if not ok.all():
                placed = placed[ok]
            parts.append(placed)
    if not parts:
        return np.empty((0, link_width), dtype=np.int64)
    return np.concatenate(parts, axis=0)


def _link_fragment_rows(
    level_group: Group,
    arr_name: str,
    cell_key: str,
    fragments: Sequence[int],
    *,
    ncols: int,
    dtype: np.dtype,
) -> npt.NDArray[np.int64]:
    """The rows of the named link fragments of one intra-chunk cell.

    Each range fragment is fetched as its own byte range where the array
    allows it (:meth:`Group.read_cell_range`), so on an uncompressed
    store the rest of the cell is never read; otherwise the cell is read
    whole, once, and the fragments sliced out of it.

    Raises:
        ArrayError: If a named fragment is not in the cell's index -- a
            claim of alignment that the store does not bear out.
    """
    fi = read_link_fragment_index(level_group, _parse_chunk_key(cell_key))
    for f in fragments:
        if f < 0 or f >= fi.num_fragments:
            raise ArrayError(
                f"link fragment {f} of chunk {cell_key} requested, but the "
                f"cell has {fi.num_fragments}"
            )
    row_bytes = int(dtype.itemsize) * int(ncols)
    spans = [fragment_byte_range(fi, int(f), row_bytes) for f in fragments]
    if level_group.range_readable(arr_name) and all(sp is not None for sp in spans):
        parts = [
            np.frombuffer(
                level_group.read_cell_range(arr_name, cell_key, a, b), dtype=dtype,
            ).reshape(-1, ncols)
            for a, b in spans
        ]
        if not parts:
            return np.empty((0, ncols), dtype=np.int64)
        return np.concatenate(parts, axis=0).astype(np.int64, copy=False)
    blob = level_group.read_bytes(arr_name, cell_key)
    rows = _link_cell_rows(blob, ncols=ncols, flat=True, dtype=dtype)
    parts = [fragment_rows(rows, fi, int(f)) for f in fragments]
    if not parts:
        return rows[:0]
    return np.concatenate(parts, axis=0)


def fragment_byte_range(
    fi: ChunkFragmentIndex, fragment: int, row_bytes: int,
) -> tuple[int, int] | None:
    """Payload bytes of a range fragment's rows, or ``None`` for an
    explicit (gathered) fragment, which has no single span."""
    if not fi.is_range(fragment):
        return None
    start, count = fi.range(fragment)
    return int(start) * row_bytes, (int(start) + int(count)) * row_bytes


def vertex_range_requests(
    level_group: Group,
    fragments: Iterable[tuple[ChunkCoords, int]],
    *,
    dtype: np.dtype | str,
    ndim: int,
) -> list[tuple[str, str, int, int]]:
    """The ``batched_range_reads`` requests :func:`read_fragment` will make
    for ``(chunk, fragment)`` pairs, so a caller can prefetch them in one
    gather.  Explicit fragments, and arrays that cannot be range-read,
    contribute nothing: those reads go whole-cell either way."""
    if not level_group.range_readable(VERTICES):
        return []
    row_bytes = np.dtype(dtype).itemsize * int(ndim)
    out: list[tuple[str, str, int, int]] = []
    for cc, f in fragments:
        try:
            fi = read_vertex_fragment_index(level_group, cc)
        except (ArrayError, StoreError):
            continue
        if not 0 <= f < fi.num_fragments:
            continue
        span = fragment_byte_range(fi, int(f), row_bytes)
        if span is not None:
            out.append((VERTICES, _chunk_key(cc), *span))
    return out


def link_range_requests(
    level_group: Group,
    link_fragments: Mapping[str, Sequence[int]],
) -> list[tuple[str, str, int, int]]:
    """The requests ``read_link_arrays(link_fragments=...)`` will make
    against the intra-chunk array at delta 0, for prefetching -- see
    :func:`vertex_range_requests`."""
    policy = link_family_policy(level_group, 0)
    if policy is None or policy[1] is None:
        return []
    link_width, sid_ndim, directed, store = policy
    offsets = intra_offsets(sid_ndim, link_width)
    arr_name = links_path(0, offsets)
    if not level_group.range_readable(arr_name):
        return []
    arr_meta = level_group.read_array_meta(arr_name) or {}
    has_perm = bool(arr_meta.get(
        "has_perm",
        links_has_perm(offsets, delta=0, directed=directed, store=store),
    ))
    ncols = (1 + link_width) if has_perm else link_width
    row_bytes = np.dtype(arr_meta.get("dtype", "int64")).itemsize * ncols
    out: list[tuple[str, str, int, int]] = []
    for cell_key, frags in link_fragments.items():
        try:
            fi = read_link_fragment_index(level_group, _parse_chunk_key(cell_key))
        except (ArrayError, StoreError):
            continue
        for f in frags:
            if not 0 <= f < fi.num_fragments:
                continue
            span = fragment_byte_range(fi, int(f), row_bytes)
            if span is not None:
                out.append((arr_name, cell_key, *span))
    return out


def link_endpoints_to_rows(
    chunks: npt.NDArray[np.int64],
    vi: npt.NDArray[np.int64],
    chunk_offsets: Mapping[ChunkCoords, int],
) -> npt.NDArray[np.int64]:
    """Global row of every endpoint: ``chunk_offsets[chunk] + vi``.

    ``chunks`` and ``vi`` are what :func:`read_link_arrays` returns;
    ``chunk_offsets`` is where each chunk's rows start in a reader's
    concatenation.  An endpoint whose chunk the reader did not take is
    ``-1``, which is how a bbox or cells filter reaches the records.
    """
    m, link_width, sid_ndim = chunks.shape
    if m == 0:
        return np.empty((0, link_width), dtype=np.int64)
    flat = chunks.reshape(-1, sid_ndim)
    # Each endpoint's chunk as one integer (mixed radix over the range),
    # a linear table gather instead of ``np.unique(axis=0)``'s sort.
    lo = flat.min(axis=0)
    span = flat.max(axis=0) - lo + 1
    cells = int(np.prod(span.astype(object)))
    if cells <= max(4 * flat.shape[0], 1 << 20):
        key = np.ravel_multi_index(tuple((flat - lo).T), tuple(int(s) for s in span))
        table = np.full(cells, -1, dtype=np.int64)
        for cc, start in chunk_offsets.items():
            rel = np.asarray(cc, dtype=np.int64) - lo
            if len(cc) == sid_ndim and np.all(rel >= 0) and np.all(rel < span):
                table[np.ravel_multi_index(tuple(int(x) for x in rel),
                                           tuple(int(s) for s in span))] = start
        base = table[key].reshape(m, link_width)
    else:
        unique, inverse = np.unique(flat, axis=0, return_inverse=True)
        starts = np.fromiter(
            (chunk_offsets.get(tuple(row), -1) for row in unique.tolist()),
            dtype=np.int64, count=unique.shape[0],
        )
        base = starts[np.asarray(inverse).reshape(-1)].reshape(m, link_width)
    return np.where(base >= 0, base + vi, -1)


def _link_tuple_cell(
    level_group: Group,
    chunk_tuple: Sequence[ChunkCoords],
    delta: int,
) -> tuple[
    tuple[ChunkCoords, ...],
    ChunkCoords,
    tuple[ChunkCoords, ...],
    tuple[int, int, bool, str],
] | None:
    """Resolve an L-chunk tuple to the one ``(offsets, source, chunks)``
    cell that can hold its records, plus the family policy.

    The single definition :func:`read_links_for_tuple` and
    :func:`read_link_attributes_for_tuple` both consult, so a tuple cannot
    resolve to one cell in the links family and a different one in the
    attribute family that parallels it.

    Inverts :func:`~zarr_vectors.spatial.boundary._cell_placements` for a
    query that knows chunks but not vertex indices:

    - An **undirected canonical** family at delta 0 sorts its endpoints by
      ``(chunk, vi)``.  A ``vi`` only breaks ties between endpoints already
      in the same chunk, so it never reorders the chunk sequence — sorting
      the chunks alone reproduces the placement exactly, and callers may
      pass any order.
    - Every other family leads with input endpoint 0: ``directed`` and
      cross-level (``delta != 0``) force the identity placement, and
      ``duplicate`` files one copy per distinct incident chunk of which
      the identity is always one.  The tuple is taken as given, so its
      order is meaningful.

    Offsets are anchor-projected, which is what makes a ``delta != 0``
    query resolve against the owning level's chunk grid rather than
    differencing two incommensurable grids.

    Returns ``None`` when the family is absent or carries no policy.
    """
    policy = link_family_policy(level_group, delta)
    if policy is None:
        return None
    link_width, sid_ndim, directed, store = policy
    if len(chunk_tuple) != link_width:
        raise ArrayError(
            f"chunk_tuple has {len(chunk_tuple)} chunks; expected "
            f"link_width={link_width}"
        )
    chunks = tuple(tuple(int(c) for c in ch) for ch in chunk_tuple)
    if sid_ndim is None:
        # Family group predating the sid_ndim stamp: the query's own arity
        # is the only evidence, and the arity check below is then vacuous.
        sid_ndim = len(chunks[0]) if chunks else 0
    for c in chunks:
        if len(c) != sid_ndim:
            raise ArrayError(
                f"chunk_tuple element {c} has arity {len(c)}; "
                f"expected sid_ndim={sid_ndim}"
            )

    if delta == 0 and not directed and store == "canonical":
        chunks = tuple(sorted(chunks))
    src = chunks[0]

    from zarr_vectors.spatial.boundary import anchor_chunk

    scale_src, scale_trg = _link_scales(level_group, delta, sid_ndim)
    anchor = anchor_chunk(src, scale_src, scale_trg)
    offsets = tuple(
        tuple(int(c) - int(a) for c, a in zip(ch, anchor)) for ch in chunks[1:]
    )
    return offsets, src, chunks, (link_width, sid_ndim, directed, store)


def read_links_for_tuple(
    level_group: Group,
    chunk_tuple: Sequence[ChunkCoords],
    *,
    delta: int = 0,
) -> list[tuple[tuple[ChunkCoords, int], ...]]:
    """Read records that span exactly the L chunks in ``chunk_tuple``.

    The single-cell counterpart to :func:`read_links`: the tuple resolves
    to exactly one ``(offsets, source)`` cell, so only that cell is
    fetched.  See :func:`_link_tuple_cell` for how the tuple maps to it —
    in particular an **undirected canonical** family sorts the tuple
    internally (pass the chunks in any order), while a **directed** or
    **duplicate** family reads it as input order (``(A, B)`` and ``(B, A)``
    are different cells).  An all-equal tuple reads that chunk's
    intra-chunk links, which are no longer a separate family.
    ``len(chunk_tuple)`` must equal the family's ``link_width``.

    Returns ``[]`` if no records exist for that exact L-tuple.
    Records are returned in write order, each in original input
    endpoint order (``perm_idx`` is reversed for the caller).
    """
    resolved = _link_tuple_cell(level_group, chunk_tuple, delta)
    if resolved is None:
        return []
    offsets, src, chunks, (link_width, _sid_ndim, directed, store) = resolved

    full_name = links_path(delta, offsets)
    key = _chunk_key(src)
    if not level_group.chunk_exists(full_name, key):
        return []
    blob = level_group.read_bytes(full_name, key)
    if not blob:
        return []

    arr_meta = level_group.read_array_meta(full_name) or {}
    # Trust the stored width; fall back to recomputing it from the family
    # policy for an array written before it was stamped.  Guessing here
    # would silently mis-parse every row in the cell.
    has_perm = bool(arr_meta.get(
        "has_perm",
        links_has_perm(offsets, delta=delta, directed=directed, store=store),
    ))
    ncols = (1 + link_width) if has_perm else link_width
    rows_arr = _link_cell_rows(
        blob, ncols=ncols, flat=(delta == 0 and is_intra(offsets)),
        dtype=np.dtype(arr_meta.get("dtype", "int64")),
    )
    if rows_arr.size == 0:
        return []

    from zarr_vectors.spatial.boundary import apply_perm_inverse

    out: list[tuple[tuple[ChunkCoords, int], ...]] = []
    if not has_perm:
        # Identity placement only: rows are already input order.
        for vis in rows_arr[:, :link_width].tolist():
            out.append(tuple(zip(chunks, vis)))
        return out
    for row in rows_arr.tolist():
        perm_idx = int(row[0])
        placed_endpoints = list(zip(chunks, row[1:1 + link_width]))
        out.append(tuple(apply_perm_inverse(
            placed_endpoints, perm_idx, link_width,
        )))
    return out


@_device_result(on_device=True)
def read_link_attributes(
    level_group: Group,
    attr_name: str,
    dtype: np.dtype | str | None = None,
    *,
    delta: int = 0,
) -> npt.NDArray:
    """Read every per-link attribute row under ``link_attributes/<name>/<delta>/``.

    The whole-family counterpart to :func:`write_link_attributes`, and the
    attribute-side mirror of :func:`read_links`: rows come back in
    **(offsets segment, cell) sorted order**, which is exactly the order
    :func:`read_links` returns records, so attribute row ``i`` belongs to
    link record ``i``.  That shared enumeration is the ONLY thing aligning
    the two — nothing on disk ties a row to a record — so the two
    functions must not drift.

    Args:
        level_group: Resolution level group.
        attr_name: Attribute name.
        dtype: Parse the stored bytes as this dtype instead of the one on
            the array's meta.
        delta: Level delta.

    Returns:
        Array of shape ``(num_links,)`` or ``(num_links, *row_shape)``;
        empty when the family is absent or holds no rows.
    """
    group_path = link_attributes_group_path(attr_name, delta)
    if not level_group.array_exists(group_path):
        return np.array([], dtype=dtype or np.float32)

    blocks: list[npt.NDArray] = []
    row_shape: tuple[int, ...] = ()
    out_dtype = np.dtype(dtype) if dtype is not None else np.dtype(np.float32)
    segments = [
        (f"{group_path}/{seg}", sorted(level_group.list_chunks(f"{group_path}/{seg}")))
        for seg in list_link_attribute_offsets(level_group, attr_name, delta)
    ]
    # One batched prefetch for every cell of every segment, then decode.
    with _maybe_batched_reads(level_group, [(n, k) for n, k in segments if k]):
        fetched = [
            (full_name, [(k, level_group.read_bytes(full_name, k)) for k in keys])
            for full_name, keys in segments
        ]
    for full_name, blobs in fetched:
        meta = level_group.read_array_meta(full_name) or {}
        # ``dtype`` / ``row_shape`` come from each array's own meta — a
        # bare byte blob is undecodable without them.
        out_dtype = (
            np.dtype(dtype) if dtype is not None else np.dtype(meta["dtype"])
        )
        row_shape = tuple(meta.get("row_shape", ()))
        row_size = int(np.prod(row_shape)) if row_shape else 1
        row_bytes = out_dtype.itemsize * row_size
        for _cell_key, blob in blobs:
            if not blob:
                continue
            n = len(blob) // row_bytes
            arr = np.frombuffer(blob, dtype=out_dtype).reshape(
                (n, *row_shape) if row_shape else (n,),
            )
            blocks.append(arr.copy())
    if not blocks:
        return (
            np.empty((0, *row_shape), dtype=out_dtype) if row_shape
            else np.empty((0,), dtype=out_dtype)
        )
    return np.concatenate(blocks, axis=0)


def read_link_attributes_for_tuple(
    level_group: Group,
    attr_name: str,
    chunk_tuple: Sequence[ChunkCoords],
    dtype: np.dtype | str | None = None,
    *,
    delta: int = 0,
) -> npt.NDArray:
    """Read per-link attribute rows for the cell spanning ``chunk_tuple``.

    Returns rows in the same order :func:`read_links_for_tuple` returns
    records for the same tuple (cell write order).  The cell is resolved
    by :func:`_link_tuple_cell` against the **links** family's policy —
    attribute meta carries no ``directed`` / ``store`` — so both readers
    land on the same cell by construction.
    """
    resolved = _link_tuple_cell(level_group, chunk_tuple, delta)
    if resolved is None:
        return np.array([], dtype=dtype or np.float32)
    offsets, src, _chunks, _policy = resolved

    full_name = link_attributes_path(attr_name, delta, offsets)
    if not level_group.array_exists(full_name):
        return np.array([], dtype=dtype or np.float32)
    meta = level_group.read_array_meta(full_name) or {}
    if dtype is None:
        dtype = np.dtype(meta["dtype"])
    else:
        dtype = np.dtype(dtype)
    row_shape = tuple(meta.get("row_shape", ()))
    row_size = int(np.prod(row_shape)) if row_shape else 1
    row_bytes = dtype.itemsize * row_size

    key = _chunk_key(src)
    if not level_group.chunk_exists(full_name, key):
        return (
            np.empty((0, *row_shape), dtype=dtype) if row_shape
            else np.empty((0,), dtype=dtype)
        )
    blob = level_group.read_bytes(full_name, key)
    n = len(blob) // row_bytes
    return np.frombuffer(blob, dtype=dtype).reshape(
        (n, *row_shape) if row_shape else (n,),
    ).copy()


# ===================================================================
# Listing / introspection
# ===================================================================

def list_chunk_keys(
    level_group: Group,
    array_name: str = VERTICES,
) -> list[ChunkCoords]:
    """List all chunk coordinates that have data for an array.

    Args:
        level_group: Resolution level group.
        array_name: Array name (default: ``"vertices"``).

    Returns:
        Sorted list of chunk coordinate tuples.
    """
    # Delegated so the parse is cached for the duration of a
    # ``cached_nodes`` block — a reader that lists a level once per
    # query was re-splitting every key string in it each time.
    return level_group.list_chunk_coords(array_name)


def _list_deltas_under(level_group: Group, group_path: str) -> list[int]:
    """List signed level-delta segments present under a group path.

    Returns the sorted list of integers parsed from immediate child
    names that look like delta segments (``"0"``, ``"+N"``, ``"-N"``).
    Returns an empty list when the parent group is absent.  Used by the
    public ``list_link_deltas`` / ``list_link_attribute_deltas`` helpers
    (and indirectly by readers and validators that walk the multiscale
    link layout).
    """
    if not level_group.array_exists(group_path):
        return []
    try:
        sub = level_group[group_path]
    except Exception:
        return []
    deltas: list[int] = []
    for name in sub:
        try:
            deltas.append(parse_delta(name))
        except ValueError:
            continue
    return sorted(deltas)


def list_link_deltas(level_group: Group) -> list[int]:
    """Sorted list of ``<delta>`` values present under ``links/`` in a level."""
    return _list_deltas_under(level_group, LINKS)


def list_link_attribute_deltas(level_group: Group, name: str) -> list[int]:
    """Sorted list of ``<delta>`` values present under ``link_attributes/<name>/``."""
    return _list_deltas_under(level_group, f"{LINK_ATTRIBUTES}/{name}")


def _box_cell_range(
    bbox: tuple[npt.NDArray, npt.NDArray],
    chunk_shape: tuple[float, ...],
    grid_lo: npt.NDArray,
    grid_hi: npt.NDArray,
) -> tuple[npt.NDArray, npt.NDArray] | None:
    """The inclusive cell range a bbox covers, clamped to the grid.

    ``None`` means the box selects nothing: it is inverted, it carries a
    NaN, or it lies entirely off the grid.

    Clamping happens in float space on purpose.  An infinite bound has to
    land on the grid edge, and casting ``inf`` to ``int64`` lands on
    ``INT64_MIN`` instead — silently, with only a RuntimeWarning.  The
    disjoint test likewise runs before the clamp: a box entirely to the
    left of the grid would otherwise clamp onto the leftmost cell and
    match it.

    Clamping cannot lose a chunk.  Every present coord was bounds-checked
    against this same grid when it was written, so ``present`` is a subset
    of it and the cells the clamp removes are cells that cannot exist.
    """
    cs = np.asarray(chunk_shape, dtype=np.float64)
    lo = np.floor(np.asarray(bbox[0], dtype=np.float64) / cs)
    hi = np.floor(np.asarray(bbox[1], dtype=np.float64) / cs)
    if np.isnan(lo).any() or np.isnan(hi).any():
        return None
    if np.any(hi < lo):
        return None
    if np.any(hi < grid_lo) or np.any(lo > grid_hi):
        return None
    return (
        np.clip(lo, grid_lo, grid_hi).astype(np.int64),
        np.clip(hi, grid_lo, grid_hi).astype(np.int64),
    )


# A box smaller than this always takes the probe path, whatever the level
# holds.  Below it both sides are trivial and the branch should not flicker.
_BOX_PROBE_FLOOR = 64


def _chunks_in_box(
    level_group: Group,
    chunk_shape: tuple[float, ...],
    bbox: tuple[npt.NDArray, npt.NDArray],
    array_name: str,
) -> set[ChunkCoords]:
    """Chunk coords present in the level that ``bbox`` touches.

    Refused on a composite level (:mod:`zarr_vectors.core.sources`): a
    source's cells are in the source's grid, so this level's grid says
    nothing about where they are. Read a composite's objects through their
    manifests.

    Resolved from whichever side is smaller.  Asking the box which of its
    cells exist costs one probe per cell it names; asking the level which
    of its cells are in the box costs one test per cell present.  Taking
    the smaller side bounds the work by ``min(box, level)``, and both
    directions are real: a one-cell box on a million-chunk level, and a
    whole-domain box on a sparse one.

    Iterating the level was the only option here until now, which made a
    point query cost O(chunks in the level) — 222 ms to locate one chunk
    on a 10^6-chunk level, before any data moved.

    The probe path deliberately works off the **raw** manifest rather
    than parsed coordinates.  ``nonempty_chunks`` is stored sorted, so a
    key can be found by bisection with no preparation at all, whereas
    parsing it into tuples costs 4.2 ms at 8k chunks and 53 ms at 97k —
    an order of magnitude more than the scan this function exists to
    avoid.  Answering a targeted query must not pay to describe the level
    it is targeting.

    This does not deepen the reliance on ``nonempty_chunks`` that the
    comment in :mod:`zarr_vectors.types.polylines` warns about: the
    resolution has always been an intersection with that manifest, and
    only the direction of the intersection changes here.
    """
    from zarr_vectors.core.sources import is_composite

    if is_composite(level_group):
        raise ArrayError(
            "a spatial box query over a composite level (chunk sources) is not "
            "supported: its sources' cells are in their own grids; read its "
            "objects through their manifests")
    from bisect import bisect_left
    from itertools import product

    # Sorted keys, exactly as stored -- no parse.
    present = level_group.list_chunks(array_name)
    if not present:
        return set()

    nd = len(chunk_shape)
    grid = level_group.chunk_grid_bounds(array_name)
    if grid is None:
        return _chunks_in_box_unbounded(
            level_group, chunk_shape, bbox, array_name,
        )
    origin, shape = grid
    n_lead = len(shape) - nd
    if n_lead < 0:
        # Key arity narrower than the chunk shape: not a grid this
        # function understands.  Let the caller's legacy path decide.
        return _chunks_in_box_unbounded(
            level_group, chunk_shape, bbox, array_name,
        )
    if origin is None:
        origin = (0,) * len(shape)

    grid_lo = np.asarray(origin[n_lead:], dtype=np.float64)
    span = _box_cell_range(
        bbox, chunk_shape, grid_lo,
        grid_lo + np.asarray(shape[n_lead:], dtype=np.float64) - 1,
    )
    if span is None:
        return set()
    lo, hi = span

    # How many keys the box could name, counted in O(ndim) without
    # materialising any of them.  The leading axes are dense, so a store
    # binned by an attribute multiplies the candidate count by the bin
    # count -- and correctly falls back to the scan once that outgrows
    # the level.
    lead_ranges = tuple(
        range(int(origin[i]), int(origin[i]) + int(shape[i]))
        for i in range(n_lead)
    )
    n_cand = int(np.prod(hi - lo + 1, dtype=np.int64))
    for r in lead_ranges:
        n_cand *= len(r)

    if n_cand <= max(len(present), _BOX_PROBE_FLOOR):
        spatial = tuple(range(int(a), int(b) + 1) for a, b in zip(lo, hi))
        found: set[ChunkCoords] = set()
        for coords in product(*lead_ranges, *spatial):
            key = ".".join(map(str, coords))
            i = bisect_left(present, key)
            if i < len(present) and present[i] == key:
                found.add(coords)
        return found

    # The level is the smaller side.  Test each present coord against the
    # clamped span directly -- the box is never enumerated, so a
    # whole-domain query on a fine grid cannot blow up here.
    lo_t = tuple(int(x) for x in lo)
    hi_t = tuple(int(x) for x in hi)
    return {
        c for c in list_chunk_keys(level_group, array_name=array_name)
        if all(
            lo_t[d] <= v <= hi_t[d] for d, v in enumerate(c[-nd:])
        )
    }


def _chunks_in_box_unbounded(
    level_group: Group,
    chunk_shape: tuple[float, ...],
    bbox: tuple[npt.NDArray, npt.NDArray],
    array_name: str,
) -> set[ChunkCoords]:
    """The pre-existing resolution, for a level with no readable grid.

    Kept byte-for-byte so a layout the bounded path does not recognise
    behaves exactly as it did before it existed.

    ``chunks_intersecting_bbox`` speaks spatial coords, but a store
    written with ``chunk_by_attribute`` prefixes every key with a bin
    axis.  Intersecting the two directly matched nothing, so a bbox on
    such a store resolved to zero chunks and the caller got an empty
    result rather than its data.  Compare on the trailing spatial dims,
    which is an identity for un-binned keys.
    """
    from zarr_vectors.spatial.chunking import chunks_intersecting_bbox

    target = set(chunks_intersecting_bbox(
        np.asarray(bbox[0]), np.asarray(bbox[1]), tuple(chunk_shape),
    ))
    nd = len(chunk_shape)
    return {
        k for k in list_chunk_keys(level_group, array_name=array_name)
        if tuple(k[-nd:]) in target
    }


def resolve_chunk_keys(
    level_group: Group,
    chunk_shape: tuple[float, ...],
    *,
    bbox: tuple[npt.NDArray, npt.NDArray] | None = None,
    chunks: list[ChunkCoords] | None = None,
    array_name: str = VERTICES,
) -> list[ChunkCoords]:
    """Resolve the chunk_keys present in a level, intersected with the
    bbox-implied set and the explicit ``chunks`` whitelist.

    Combination of filters is AND: a chunk must be physically present
    *and* satisfy every supplied constraint.

    Args:
        level_group: Resolution level group.
        chunk_shape: Physical chunk size per spatial dimension.
        bbox: Optional ``(min_corner, max_corner)``. Intersected with the
            stored keys via :func:`chunks_intersecting_bbox`.
        chunks: Optional explicit whitelist of chunk coordinate tuples.
            Pass ``[]`` for "no chunks" (yields an empty result). Pass
            ``None`` (the default) for "no filter".  A tuple with one
            entry per spatial axis names a spatial cell, and on a level
            chunked by an attribute it selects that cell in every bin --
            matched on the key's trailing components, as a box is.  A
            tuple with the extra leading bin names one key exactly.
        array_name: Array whose chunk keys to enumerate.

    Returns:
        Sorted list of chunk coordinate tuples.

    Raises:
        ValueError: If a tuple in ``chunks`` has the wrong arity for
            this store.
    """
    if bbox is None and chunks is None:
        # Nothing to filter by: the listing is the answer.  Returned as a
        # copy, and without consulting ``chunk_shape`` — a caller with no
        # filter has no reason to have one, and passes None.
        return list(list_chunk_keys(level_group, array_name=array_name))

    if bbox is not None:
        keys = _chunks_in_box(level_group, chunk_shape, bbox, array_name)
    else:
        keys = set(list_chunk_keys(level_group, array_name=array_name))

    if chunks is not None:
        expected_arity = len(chunk_shape)
        exact: set[ChunkCoords] = set()
        spatial: set[ChunkCoords] = set()
        for c in chunks:
            t = tuple(int(x) for x in c)
            if len(t) == expected_arity:
                spatial.add(t)
            elif len(t) == expected_arity + 1:
                # Some stores (e.g. attribute-binned points / graphs) prefix
                # spatial chunk coords with an extra binning axis, giving
                # keys of length ``expected_arity + 1``. Accept those too.
                exact.add(t)
            else:
                raise ValueError(
                    f"chunks tuple {c!r} has arity {len(t)}; "
                    f"expected {expected_arity} (or {expected_arity + 1} "
                    f"for attribute-binned stores)"
                )
        # A spatial tuple is what ``Grid`` hands out, and on a binned level
        # it used to match no key at all: the keys lead with the bin.  It
        # names the cell in every bin, as a box does (``_chunks_in_box``
        # also compares on the trailing axes).  On a spatial level the tail
        # is the whole key, so this is the old exact match.
        keys = {
            k for k in keys
            if k in exact or k[len(k) - expected_arity:] in spatial
        }

    return sorted(keys)


def count_fragments(
    level_group: Group,
    chunk_coords: ChunkCoords,
) -> int:
    """Count fragments in a chunk by reading the fragment-index header."""
    return len(read_vertex_fragment_index(level_group, chunk_coords))


# ===================================================================
# Internal helpers
# ===================================================================

def _read_modify_write_blob(
    level_group: Group,
    full_name: str,
    key: str,
    *,
    decode_fn,
    merge_fn,
    encode_fn,
    initial,
) -> tuple[Any, Any]:
    """Read-modify-write a single blob with caller-supplied codec hooks.

    Returns ``(combined, existing)`` — callers need ``existing`` to compute
    the row-index of the newly-appended portion.

    Atomicity: ``write_bytes`` is delete-then-create, not strictly atomic;
    treat it as last-writer-wins.  The pattern is NOT cross-writer-safe.
    Callers MUST serialise concurrent writes to the same blob.
    """
    try:
        raw = level_group.read_bytes(full_name, key)
    except StoreError:
        raw = b""
    # An allocated-but-never-written cell reads back b"" — the vlen fill
    # value — which means "nothing here yet", not "corrupt".  Only StoreError
    # used to signal absence; since every per-chunk array became a single
    # vlen array, absence usually arrives as empty bytes instead, and
    # decode_fn raises ArrayError on those.  Treat both as absent.
    existing = decode_fn(raw) if raw else initial
    combined = merge_fn(existing)
    level_group.write_bytes(full_name, key, encode_fn(combined))
    return combined, existing


def read_vertex_fragment_index(
    level_group: Group,
    chunk_coords: ChunkCoords,
) -> ChunkFragmentIndex:
    """Read and decode the ``vertex_fragments/<chunk>`` blob.

    Returns the v0.6 :class:`ChunkFragmentIndex` view describing how rows of
    ``vertices/<chunk>`` partition into fragments.
    """
    key = _chunk_key(chunk_coords)
    raw = level_group.read_bytes(VERTEX_FRAGMENTS, key)
    return decode_fragments(raw)


def read_link_fragment_index(
    level_group: Group,
    chunk_coords: ChunkCoords,
) -> ChunkFragmentIndex:
    """Read and decode the ``link_fragments/<chunk>`` blob (delta=0 only)."""
    key = _chunk_key(chunk_coords)
    raw = level_group.read_bytes(LINK_FRAGMENTS, key)
    return decode_fragments(raw)


def _reshape_link_buffer(
    raw: bytes,
    dtype: np.dtype,
    link_width: int,
) -> npt.NDArray[np.integer]:
    """Return a ``(M_total, link_width)`` view onto a ``links/0/<chunk>`` blob.

    Falls back to a 1-D array when ``link_width == 1``.
    """
    arr = np.frombuffer(raw, dtype=dtype)
    return arr.reshape(-1, link_width) if link_width > 1 else arr


def _slice_link_range(
    raw: bytes,
    start: int,
    count: int,
    dtype: np.dtype,
    link_width: int,
) -> npt.NDArray[np.integer]:
    """Return rows ``[start, start+count)`` from a ``links/0/<chunk>`` blob."""
    row_size = int(dtype.itemsize) * int(link_width)
    seg = raw[int(start) * row_size : (int(start) + int(count)) * row_size]
    arr = np.frombuffer(seg, dtype=dtype)
    return arr.reshape(-1, link_width) if link_width > 1 else arr


def _reshape_vertex_buffer(
    raw: bytes,
    dtype: np.dtype,
    ndim: int,
) -> npt.NDArray[np.floating]:
    """Return a ``(N_total, ndim)`` view onto a ``vertices/<chunk>`` blob.

    Falls back to a 1-D array when ``ndim == 1``.
    """
    arr = np.frombuffer(raw, dtype=dtype)
    return arr.reshape(-1, ndim) if ndim > 1 else arr


def _fragment_vertex_extent(fi: ChunkFragmentIndex) -> int:
    """Return the number of underlying vertices a fragment index spans.

    This is ``max(referenced vertex index) + 1`` across every fragment —
    equal to the length of the ``vertices`` array the chunk's per-vertex
    attributes align 1:1 with (Core-1's fragment 0 is a range covering
    all vertices, so it sets this extent; explicit twins only reference a
    subset).  Used by :func:`read_chunk_attributes` to recover the
    attribute's true per-vertex column width.

    Delegates to :attr:`ChunkFragmentIndex.vertex_extent`, which reduces
    over the whole index buffer instead of walking fragment by fragment.
    """
    return fi.vertex_extent


def _slice_vertex_range(
    raw: bytes,
    start: int,
    count: int,
    dtype: np.dtype,
    ndim: int,
) -> npt.NDArray[np.floating]:
    """Return rows ``[start, start+count)`` from a ``vertices/<chunk>`` blob."""
    bytes_per_vertex = int(dtype.itemsize) * int(ndim)
    seg = raw[int(start) * bytes_per_vertex : (int(start) + int(count)) * bytes_per_vertex]
    arr = np.frombuffer(seg, dtype=dtype)
    return arr.reshape(-1, ndim) if ndim > 1 else arr


def _read_vertex_offsets(
    level_group: Group,
    chunk_coords: ChunkCoords,
    *,
    bytes_per_vertex: int | None = None,
) -> npt.NDArray[np.int64]:
    """Read the ``(K,)`` int64 vertex byte offsets for a chunk.

    Computed from the v0.6 ``vertex_fragments/<chunk>`` index.  Every
    fragment must be a contiguous range over rows of ``vertices/<chunk>``
    — the only shape the existing writer produces.  Stores written by
    future writers that materialise non-contiguous / shared-row
    fragments must use the higher-level fragment-index API directly;
    this helper raises rather than silently lying about a byte offset
    that doesn't exist.

    Args:
        level_group: Resolution level group.
        chunk_coords: Spatial chunk coordinates.
        bytes_per_vertex: Bytes per vertex row.  When omitted it is
            inferred from the ``vertices/`` array's ``dtype`` metadata
            and the root NGFF axes count.
    """
    if bytes_per_vertex is None:
        vmeta = level_group.read_array_meta(VERTICES)
        vdtype = np.dtype(vmeta.get("dtype", "float32"))
        ndim = _infer_vert_ndim(level_group)
        bytes_per_vertex = int(vdtype.itemsize) * int(ndim)
    fi = read_vertex_fragment_index(level_group, chunk_coords)
    if fi.num_fragments == 0:
        return np.empty(0, dtype=np.int64)
    offsets = np.empty(fi.num_fragments, dtype=np.int64)
    for i in range(fi.num_fragments):
        if not fi.is_range(i):
            raise ArrayError(
                f"vertex_fragments/{_chunk_key(chunk_coords)} fragment {i} "
                "is non-contiguous; byte-offset access requires every "
                "fragment to be a contiguous range over rows of "
                "vertices/<chunk>.  Use read_vertex_fragment_index() "
                "directly for non-contiguous fragments.",
            )
        start, _count = fi.range(i)
        offsets[i] = int(start) * int(bytes_per_vertex)
    return offsets




# Downstream imports the pre-promotion spelling; keep it resolving so a
# consumer is not broken by a rename that gains them nothing.
_expand_blocks = expand_manifest_blocks
