Skip to content
Open
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
4 changes: 4 additions & 0 deletions docs/guides/chunking.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ da = lazycogs.open(
da.max(dim="time").compute() # each time step runs in its own dask task
```

### dask.distributed

Chunked arrays can be computed on a `dask.distributed` cluster. Each worker opens its own DuckDB client and queries `href` itself, so `href` must be readable from every worker, e.g. a path on a shared filesystem or an `s3://` URL with DuckDB credentials set up. A client passed as `duckdb_client=` must be picklable.

## Spatial chunks

Avoid spatial chunks unless you are under memory pressure. lazycogs handles spatial I/O concurrency internally through its async event loop — adding spatial dask tasks layers extra DuckDB query overhead on top of I/O that was already happening concurrently.
Expand Down
20 changes: 19 additions & 1 deletion src/lazycogs/_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import numpy as np
from affine import Affine
from pyproj import CRS, Transformer
from rustac import DuckdbClient
from xarray.backends.common import BackendArray
from xarray.core import indexing

Expand All @@ -25,7 +26,6 @@
from collections.abc import Callable

from async_geotiff import Store
from rustac import DuckdbClient

from lazycogs._mosaic_methods import MosaicMethodBase
from lazycogs._temporal import _TimeStep
Expand Down Expand Up @@ -283,6 +283,10 @@ class MultiBandStacBackendArray(BackendArray):
duckdb_client: ``DuckdbClient`` instance used for all STAC queries.
Constructed with default settings in :func:`open` when not supplied
by the caller.
owns_duckdb_client: Whether :func:`open` constructed ``duckdb_client``.
If so, pickling drops it and unpickling builds a fresh default
client, since rustac's client can't be pickled. A caller-supplied
client is pickled as is.
bands: Ordered list of STAC asset keys, one per band.
time_steps: Sorted temporal steps, one entry per time step.
dst_affine: Affine transform of the full output grid.
Expand Down Expand Up @@ -347,6 +351,7 @@ class MultiBandStacBackendArray(BackendArray):
max_concurrent_reads: int = field(default=32)
path_from_href: Callable[[str], str] | None = field(default=None)
errors: Literal["ignore", "raise"] = field(default="raise")
owns_duckdb_client: bool = field(default=False)
shape: tuple[int, ...] = field(init=False)
_dst_to_4326: Transformer | None = field(init=False, repr=False, compare=False)

Expand Down Expand Up @@ -381,6 +386,19 @@ def __deepcopy__(self, memo: dict[int, object]) -> MultiBandStacBackendArray:
memo[id(self)] = self
return self

def __getstate__(self) -> dict[str, Any]:
"""Return the state to pickle, minus a DuckDB client lazycogs made."""
state = self.__dict__.copy()
if self.owns_duckdb_client:
state["duckdb_client"] = None
return state

def __setstate__(self, state: dict[str, Any]) -> None:
"""Restore pickled state, rebuilding a DuckDB client lazycogs made."""
if state["owns_duckdb_client"]:
state["duckdb_client"] = DuckdbClient()
self.__dict__.update(state)

def _resolve_spatial_window(
self,
y_key: int | np.integer | slice,
Expand Down
8 changes: 8 additions & 0 deletions src/lazycogs/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,7 @@ def _build_dataarray(
*,
parquet_path: str,
duckdb_client: DuckdbClient,
owns_duckdb_client: bool,
resolved_bands: list[str],
time_steps: list[_TimeStep],
bbox: tuple[float, float, float, float],
Expand Down Expand Up @@ -403,6 +404,7 @@ def _build_dataarray(
multi = MultiBandStacBackendArray(
parquet_path=parquet_path,
duckdb_client=duckdb_client,
owns_duckdb_client=owns_duckdb_client,
bands=resolved_bands,
time_steps=time_steps,
dst_affine=dst_affine,
Expand Down Expand Up @@ -640,6 +642,10 @@ def strip_bucket(href: str) -> str:
resolution=...,
)

rustac's ``DuckdbClient`` can't be pickled, so to compute on
``dask.distributed`` workers, leave this as ``None`` or pass a
picklable client.

errors: How to handle a failed item-band read during chunk
materialization (e.g. a storage error or rate-limit response).
``"raise"`` (default) raises the first such failure as
Expand All @@ -660,6 +666,7 @@ def strip_bucket(href: str) -> str:
duration.

"""
owns_duckdb_client = duckdb_client is None
if duckdb_client is None:
duckdb_client = DuckdbClient()
if not href.endswith((".parquet", ".geoparquet")):
Expand Down Expand Up @@ -760,6 +767,7 @@ def strip_bucket(href: str) -> str:
return _build_dataarray(
parquet_path=href,
duckdb_client=duckdb_client,
owns_duckdb_client=owns_duckdb_client,
resolved_bands=resolved_bands,
time_steps=time_steps,
bbox=bbox,
Expand Down
71 changes: 71 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
from __future__ import annotations

import asyncio
import pickle
from unittest.mock import AsyncMock, patch

import numpy as np
import pytest
import rustac
from obstore.store import MemoryStore
from pyproj import Transformer
from rustac import DuckdbClient

import lazycogs
Expand Down Expand Up @@ -1083,3 +1085,72 @@ async def fake_open(path: str, *, store):
store=MemoryStore(),
path_from_href=lambda href: href.split("/", 3)[-1],
)


def _synthetic_cog_parquet(synthetic_cog, tmp_path) -> str:
"""Write a one-item parquet pointing at the synthetic COG."""
west, south, east, north = Transformer.from_crs(
"EPSG:32632",
"EPSG:4326",
always_xy=True,
).transform_bounds(500_000, 5_579_520, 520_480, 5_600_000)
item = {
"type": "Feature",
"stac_version": "1.0.0",
"id": "synthetic",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[west, south],
[east, south],
[east, north],
[west, north],
[west, south],
],
],
},
"bbox": [west, south, east, north],
"properties": {"datetime": "2023-01-15T10:00:00Z"},
"links": [],
"assets": {
"B04": {
"href": synthetic_cog.as_uri(),
"type": "image/tiff; application=geotiff; profile=cloud-optimized",
"roles": ["data"],
},
},
}
parquet = str(tmp_path / "items.parquet")
rustac.write_sync(parquet, [item])
return parquet


def test_open_result_survives_pickling(synthetic_cog, tmp_path):
"""A chunked array computes the same after a pickle round trip."""
da = lazycogs.open(
_synthetic_cog_parquet(synthetic_cog, tmp_path),
bbox=(500_000, 5_599_360, 500_640, 5_600_000),
crs="EPSG:32632",
resolution=10.0,
chunks={"x": 32, "y": 32},
)

restored = pickle.loads(pickle.dumps(da)).values # noqa: S301

assert (restored != 0).all()
np.testing.assert_array_equal(restored, da.values)


def test_open_pickles_caller_duckdb_client_as_is(synthetic_cog, tmp_path):
"""A caller's client is pickled as is, not swapped for a default one."""
da = lazycogs.open(
_synthetic_cog_parquet(synthetic_cog, tmp_path),
bbox=(500_000, 5_599_360, 500_640, 5_600_000),
crs="EPSG:32632",
resolution=10.0,
duckdb_client=DuckdbClient(),
)

with pytest.raises(TypeError, match="DuckdbClient"):
pickle.dumps(da)
Loading