Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/zarr-indexing/changes/497.doc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A new `lazy_indexing_asyncio` example plans reads with `LazyArray.parts()` and fetches them through its own asyncio code over `zarr.AsyncArray`, including a chunk cache that overlapping views share. The integrations guide gains a section on consumer-owned I/O with `Partition.source_selection` and `IndexTransform.decompose()`.
12 changes: 12 additions & 0 deletions packages/zarr-indexing/docs/examples/lazy_indexing_asyncio.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
--8<-- "lazy_indexing_asyncio/README.md"

`LazyArray` owns the plan that indexing determines: which chunks a view touches, what to
request from each, and where each block lands. The consumer's event loop owns concurrency
and I/O. Each part carries its chunk's domain and its read relative to that chunk, so the
cache needs no coordinate arithmetic of its own.

## Source Code

```python
--8<-- "lazy_indexing_asyncio/lazy_indexing_asyncio.py"
```
45 changes: 45 additions & 0 deletions packages/zarr-indexing/docs/guide/integrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,51 @@ view = LazyArray(source).with_reader(unit_step_reader)
For strided selections, the ratio of cover cells to selected cells depends on
stride, length, and endpoint alignment. Partitioning can reduce that cover.

### Consumer-owned I/O: parts as backend requests

The slab and partitioned regimes above both read *through* the wrapper. A
consumer with its own I/O layer (an async store, an HTTP endpoint, a connection
pool) can instead use the wrapper only to plan, and perform every read itself.
[`Partition.source_selection`][zarr_indexing.lazy_array.Partition.source_selection]
lowers a part's read to a NumPy basic selection on the wrapped array, and the
part's `out_selection` places whatever comes back. The lowering is conservative:
it raises
[`NoBasicSelectionError`][zarr_indexing.errors.NoBasicSelectionError], a
`ValueError`, for every part it cannot spell exactly. That includes every part
of a query of more than one coordinate (`oindex`, `vindex`, a mask) and a few
boxes, such as transposed or broadcast axes. For those parts,
[`IndexTransform.decompose`][zarr_indexing.transform.IndexTransform.decompose]
splits the read into a cover of ascending slices to fetch and a residual to
read from the fetched block in memory. It refuses only a transform that reads a
negative coordinate.

```python
--8<-- "snippets/integrations.py:consumer-owned-io"
```

[`Partition.chunk_local_selection`][zarr_indexing.lazy_array.Partition.chunk_local_selection]
is the same read relative to the part's chunk, for a consumer that caches
decoded chunks, and it refuses exactly when `source_selection` does.
`projection.chunk_domain` locates that chunk in the source, so it is what to
fetch, and the whole domain, not only its origin, is a sound cache key: views
partitioned with different grids can have chunks that start at one point and
differ in extent. `base_coords` counts cells of whatever grid the view was
partitioned with, so it keys a cache only together with that grid.

A backend may accept less than NumPy does. `source_selection` can contain a new
axis (`None`) or a negative-step slice, and `zarr.AsyncArray.getitem` accepts
neither, so a Zarr consumer fetches the cover for those parts too. A source that
accepts only unit-step slices fetches the cover of
[`decompose_unit_step`][zarr_indexing.transform.IndexTransform.decompose_unit_step]
for every part. The [asyncio example](../examples/lazy_indexing_asyncio.md)
reads through `zarr.AsyncArray` with `asyncio.gather`: one request per part, the
cover for the parts Zarr cannot request, and a cache of decoded chunks that
overlapping views share.

When the wrapper's own reader can perform the I/O,
[`zarr_indexing.iteration`](../api/iteration.md) reads many views and loads each
chunk they share once, synchronously.

## napari-like consumer

This is a **napari-like consumer**, not a napari integration. It models the
Expand Down
38 changes: 37 additions & 1 deletion packages/zarr-indexing/docs/snippets/integrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@

import numpy as np

from zarr_indexing import IndexDomain, LazyArray
from zarr_indexing import (
IndexDomain,
LazyArray,
NoBasicSelectionError,
Partition,
ReadContext,
numpy_reader,
)


# --8<-- [start:zarr-consumer]
Expand Down Expand Up @@ -165,3 +172,32 @@ def materialize(view: LazyArray) -> Any:
for key in slab_source.keys
)
# --8<-- [end:dense-box-repartition]


# --8<-- [start:consumer-owned-io]
def read_part(part: Partition, consumer_io: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
"""Read one part through the consumer's own I/O, never through the wrapper."""
try:
selection = part.source_selection
except NoBasicSelectionError:
cover, residual = part.view.transform.decompose()
out = np.empty(part.view.shape, dtype=part.view.dtype)
numpy_reader.read_into(consumer_io[cover], ReadContext(residual), out)
return out
return consumer_io[selection]


recorder = RecordingArray(np.arange(100).reshape(10, 10), chunks=(4, 4))
planner = LazyArray(recorder)
consumer_io = np.arange(100).reshape(10, 10) # stands in for the consumer's I/O layer

for request, expected in (
(planner[1:9:2, 4:], consumer_io[1:9:2, 4:]), # each part is a basic selection
(planner.oindex[[9, 0, 0], 2:7], consumer_io[[9, 0, 0], 2:7]), # no part is
):
assembled = np.empty(request.shape, dtype=request.dtype)
for part in request.parts():
assembled[part.out_selection] = read_part(part, consumer_io)
assert (assembled == expected).all()
assert recorder.keys == [] # the planner's own source was never read
# --8<-- [end:consumer-owned-io]
53 changes: 53 additions & 0 deletions packages/zarr-indexing/examples/lazy_indexing_asyncio/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Lazy Indexing with asyncio

This example uses `zarr_indexing.LazyArray` only to plan reads, while its own asyncio code
performs every read through `zarr.AsyncArray`. The package has no scheduler and no async
I/O: `parts()` says which chunks a view needs, what to read from each, and where the values
belong, and the consumer decides when and how to fetch them.

The example shows how to:

- Fetch every part of a view at once with `asyncio.gather`, sending each part's
`source_selection` (integers and slices, in the array's own coordinates) to
`AsyncArray.getitem`, and place each block at the part's `out_selection`
- Fetch the parts that Zarr cannot request directly through their cover instead: a
part with a new axis (`None`) or a negative step, which NumPy accepts and Zarr does not,
and a part of a gather of more than one coordinate (`oindex`, `vindex`, a mask), for which
`source_selection` raises `NoBasicSelectionError`. `IndexTransform.decompose()` splits
the part's read into a cover of ascending slices, which Zarr always accepts, and a
residual that `numpy_reader` reads from the fetched block
- Cache decoded chunks for many overlapping views: fetch each chunk a part needs
(`projection.chunk_domain`) once, keyed by that domain, then read the part from the cached
chunk with `chunk_local_selection`. Overlapping views read at once share the fetches
- Prove that the consumer did all the I/O: the wrapper's reader fails if it is ever used,
and a store that counts reads shows one read for each part, and through the cache, one
read for each chunk

`AsyncArray` is only one possible backend. The adapter needs a single
`async def getitem(selection)` that accepts integers and positive-step slices, so the same
code can read from any async source that speaks Zarr's selections. A backend that accepts
all of NumPy's basic selections can send `source_selection` for more parts, and one that
accepts only unit-step slices can fetch the cover of `decompose_unit_step()` for every part.

To read many views through the wrapper's own reader instead, sharing the chunks they have in
common, use the functions of `zarr_indexing.iteration`, such as `iter_values` and
`read_stacked`. They read synchronously.

## Running the Example

The script declares its dependencies inline
([PEP 723](https://peps.python.org/pep-0723/)), so the easiest way to run it is
with [uv](https://docs.astral.sh/uv/), which installs them automatically:

```bash
cd packages/zarr-indexing
uv run --with-editable . examples/lazy_indexing_asyncio/lazy_indexing_asyncio.py
```

Alternatively, run it with plain Python, in which case you must first install
`zarr`, `numpy`, and this checkout of `zarr-indexing` yourself:

```bash
cd packages/zarr-indexing
python examples/lazy_indexing_asyncio/lazy_indexing_asyncio.py
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "zarr>=3.1",
# "zarr-indexing>=0.1",
# "numpy==2.4.3"
# ]
# ///
#

"""
Plan reads with zarr_indexing.LazyArray, and perform them with asyncio
"""

from __future__ import annotations

import asyncio
from typing import Any

import numpy as np
import zarr
import zarr.api.asynchronous
from zarr.storage import MemoryStore, WrapperStore

from zarr_indexing import (
BasicSelection,
IndexDomain,
IndexTransform,
LazyArray,
NoBasicSelectionError,
Partition,
ReadContext,
numpy_reader,
)


class CountingStore(WrapperStore[MemoryStore]):
"""A store that counts how many chunks are read from it."""

reads = 0

async def get(self, key: str, prototype: Any, byte_range: Any = None) -> Any:
if key.startswith("c/"): # a chunk of the array at the root of the store
self.reads += 1
return await self._store.get(key, prototype, byte_range)


class RefuseReads:
"""A reader that fails if anything reads through the wrapper, which here only plans."""

def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None:
raise AssertionError("the example read through the wrapper")


def make_source(store: CountingStore) -> zarr.Array:
"""Create a chunked Zarr array, whose data the async handle reads from the same store."""
array = zarr.create_array(store=store, shape=(40, 30), chunks=(10, 10), dtype="i4")
array[:] = np.arange(40 * 30).reshape(40, 30)
return array


# --- Read a view, one request per part ---------------------------------------------------


def zarr_selection(part: Partition) -> BasicSelection | None:
"""The part's read as a selection that `AsyncArray.getitem` accepts, or `None`.

`source_selection` refuses a part that no basic selection reads, such as a query's
gather. Zarr accepts integers and positive-step slices, but not NumPy's newaxis (`None`)
or a negative step, which `source_selection` may contain.
"""
try:
selection = part.source_selection
except NoBasicSelectionError:
return None
for item in selection:
reverses = isinstance(item, slice) and item.step is not None and item.step < 0
if item is None or reverses:
return None
return selection


def finish_in_memory(block: np.ndarray, transform: IndexTransform, view: LazyArray) -> np.ndarray:
"""Read `transform` from a fetched block into a new array of the view's shape."""
out = np.empty(view.shape, dtype=view.dtype)
numpy_reader.read_into(block, ReadContext(transform), out)
return out


async def fetch_part(part: Partition, source: zarr.AsyncArray) -> np.ndarray:
"""Fetch the values of one part through `source`."""
selection = zarr_selection(part)
if selection is not None:
return np.asarray(await source.getitem(selection))
# Every other part fetches its cover, one ascending slice per axis, which Zarr always
# accepts. The residual then does the rest in memory: it adds a new axis, reverses,
# gathers, transposes or broadcasts.
cover, residual = part.view.transform.decompose()
block = np.asarray(await source.getitem(cover))
return finish_in_memory(block, residual, part.view)


async def read(view: LazyArray, source: zarr.AsyncArray) -> np.ndarray:
"""Fetch every part of `view` at once, and place each where it belongs."""
parts = list(view.parts())
blocks = await asyncio.gather(*(fetch_part(part, source) for part in parts))
out = np.empty(view.shape, dtype=view.dtype)
for part, block in zip(parts, blocks, strict=True):
out[part.out_selection] = block
return out


# --- Read many views through a cache of chunks -------------------------------------------


class ChunkCache:
"""Chunks of `source`, each fetched once, keyed by the chunk's domain in the source.

A part names its chunk with `projection.chunk_domain`, the region of the source that the
cell of the view's grid covers. Views share cached chunks when their grids agree, as the
views indexed from one `LazyArray` do. Keying by the whole domain, not only its origin,
keeps a view partitioned differently from reading a chunk of the wrong extent.

The cache holds tasks rather than arrays, so a read that needs a chunk that another read
is fetching waits for that fetch. A failed fetch stays cached; a real cache would drop it.
"""

def __init__(self, source: zarr.AsyncArray) -> None:
self.source = source
self.chunks: dict[IndexDomain, asyncio.Task[np.ndarray]] = {}

def chunk(self, domain: IndexDomain) -> asyncio.Task[np.ndarray]:
"""The chunk whose domain is `domain`, fetched now if no read has needed it yet."""
if domain not in self.chunks:
bounds = zip(domain.inclusive_min, domain.exclusive_max, strict=True)
region = tuple(slice(start, stop) for start, stop in bounds)
self.chunks[domain] = asyncio.create_task(self.fetch(region))
return self.chunks[domain]

async def fetch(self, region: tuple[slice, ...]) -> np.ndarray:
return np.asarray(await self.source.getitem(region))

async def read(self, view: LazyArray) -> np.ndarray:
"""Read `view` from cached chunks, fetching the ones it needs at once."""
parts = list(view.parts())
# Shielded, so that cancelling this read does not cancel a fetch other reads await.
fetches = (asyncio.shield(self.chunk(part.projection.chunk_domain)) for part in parts)
chunks = await asyncio.gather(*fetches)
out = np.empty(view.shape, dtype=view.dtype)
for part, chunk in zip(parts, chunks, strict=True):
try:
# The part's read, relative to the start of its chunk.
out[part.out_selection] = chunk[part.chunk_local_selection]
except NoBasicSelectionError:
# NumPy reads any transform, such as a gather's, from an array in memory.
transform = part.projection.chunk_transform
out[part.out_selection] = finish_in_memory(chunk, transform, part.view)
return out


# --- Put it together ---------------------------------------------------------------------


async def read_each_part(
planner: LazyArray, source: zarr.AsyncArray, store: CountingStore, data: np.ndarray
) -> None:
"""Read views of every kind at once, with one request for each part."""
views_and_expected = [
# Each part of these lowers to a selection that Zarr accepts, and is fetched with it.
(planner[5:35, 3:27], data[5:35, 3:27]),
(planner[::4, 7], data[::4, 7]),
# The parts of these fetch a cover instead: Zarr has no new axis or negative step,
# and a gather has no basic selection at all.
(planner[None, 5:35, 3:27], data[None, 5:35, 3:27]),
(planner[35:4:-3, ::-2], data[35:4:-3, ::-2]),
(planner.oindex[[30, 2, 2], 4:10], data[[30, 2, 2]][:, 4:10]),
]
store.reads = 0
results = await asyncio.gather(*(read(view, source) for view, _ in views_and_expected))
for result, (_, expected) in zip(results, views_and_expected, strict=True):
np.testing.assert_array_equal(result, expected)
parts = sum(len(list(view.parts())) for view, _ in views_and_expected)
print(f"read {len(results)} views of {parts} parts with {store.reads} chunk reads")
# Each part lies in one chunk, because the planner's grid is the array's chunk grid.
assert store.reads == parts


async def read_through_cache(
planner: LazyArray, source: zarr.AsyncArray, store: CountingStore, data: np.ndarray
) -> None:
"""Read overlapping views at once: each chunk that any of them needs is read once."""
store.reads = 0
cache = ChunkCache(source)
first, second, gathered = await asyncio.gather(
cache.read(planner[5:25, 3:27]),
cache.read(planner[15:35, ::2]),
cache.read(planner.oindex[[30, 2, 2], 4:10]),
)
np.testing.assert_array_equal(first, data[5:25, 3:27])
np.testing.assert_array_equal(second, data[15:35, ::2])
np.testing.assert_array_equal(gathered, data[[30, 2, 2]][:, 4:10])
print(f"read 3 views through the cache with {store.reads} chunk reads")
# The first view needs 9 chunks and the second 9, of which 3 are new. The gather needs
# 2 chunks, both already requested for the other views.
assert store.reads == len(cache.chunks) == 12


async def read_views(store: CountingStore, planner: LazyArray, data: np.ndarray) -> None:
source = await zarr.api.asynchronous.open_array(store=store)
await read_each_part(planner, source, store, data)
await read_through_cache(planner, source, store, data)


def main() -> None:
store = CountingStore(MemoryStore())
source = make_source(store)
# The planner reads only the array's shape and chunks; the async code reads its data.
planner = LazyArray(source).with_reader(RefuseReads())
asyncio.run(read_views(store, planner, source[:]))


if __name__ == "__main__":
main()
Loading